File writing is a very important part in PHP programming. We need to do this many time. Every time when you do this, you need to give 777 permission to the directory in which you are going to write the file.By this you become eligible for creating , writing,reading and deleting the file by your PHP code. This is not a secure way. Giving this permission to any of you directory can create big security problems. And of course your server guys will never suggest you to do this.
So what to do – Either go for less featured permissions (775 , 770 etc) but they have their own restrictions. Here I give you a way to write the file without bothering of your directory permissions. This way is to write file through FTP. PHP has a strong collection of FTP functions that are very useful in file writing. With the help of this you can easily write your file without fighting with your server guys for specific permissions.
Here is the code of file writing though PHP..
<?php
/*
################################# File Writing Through FTP ##########################
Subject :File writing through FTP (An alternative of 777 permission )
Developed By :Hitesh Mathpal
E mail :hitesh.mathpal@gmail.com
*/
Class ftpUtility
{
/*
* variable declarations
*/
var $ftpHost;
var $ftpUser;
var $ftpPassword;
var $ftpstream;
/*
* @param1 is the name of the FTP Host where you want to write the file
* @param2 is the user name of the FTP Host where you want to write the file
* @param3 is the password of the FTP Host where you want to write the file
*/
function __construct($host,$user,$pass)
{
$this->ftpHost=$host;
$this->ftpUser=$user;
$this->ftpPassword=$pass;
$this->ftpstream=ftp_connect($this->ftpHost);
}
/*
Checks the FTP connection.
*/
function checkFTP()
{
if(ftp_login($this->ftpstream, $this->ftpUser,$this->ftpPassword))
return true;
else
return false;
}
/*
/*@Param1 is the path where you want to write the file
/*@Param2 is the content that is to be written in the file
*/
function ftpWrite($filePath,$content)
{
$temp = tmpfile();
fwrite($temp,$content);
fseek($temp,0);
$upload=ftp_fput($this->ftpstream, $filePath,$temp,FTP_BINARY);
if($upload)
return true;
else
return false;
}
/* Close FTP stream */
function ftpclose()
{
ftp_close($this->ftpstream);
}
}
############################################### File Writing #########################################
$ftpHost=”www.example.com”;
$ftpUser=”XXXXXXXXXXXXXXXXXXX”;
$ftpPassword=”XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX”;
$filePath = “public_html/testing/myfile.txt”;
$content=”My FTP test”;
$ftp=new ftpUtility();
if($ftp->checkFTP())
{
if($ftp->ftpWrite($filePath,$content))
echo “Cheers! Check your file!”;
else
echo “Error: Try again.”;
}
$ftp->ftpclose();
?>
NOTE: You can use either the FTP details of root or can create separate FTP credentials of the directory in which you wanna perform the action (Your server guys can help you in second option)
« Cheat Sheets for Front-end Web Developers Tập 1 – Phong thần bảng(2008) »
