File write in PHP by FTP (Without 777 Permission)

Posted By: Matpal - December 16, 2011
Writing Files in PHP requires file writing permission in the specific directory. For reading and writing and file to the specific directory requires 777 permission. Giving that permission is not considered as secure.
Here we show an example where you can write file via FTP in that specific directory.


<?php

/*
#################### File Writing Through FTP ##########
Subject      :File writing through FTP (An alternative of 777 permission )
Developed By :Desicoding

*/

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();

?>

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.