March 20th, 2006

PHP: Create a Folder with Proper Permissions Via FTP

If you're running a PHP application on a shared host, it's common to have trouble creating folders and uploading files to them. You may get the following error, but this code will get you past it:

"Warning: chown(): Operation not permitted in /home/username/public_html/test.php on line 45"

"Warning: move_uploaded_file(): SAFE MODE Restriction in effect. The script whose uid is ### is not allowed to access /home/username/public_html/images/testdir owned by uid 33 in /home/username/public_html/test.php on line 47"

Basically, When safe_mode is on, PHP checks to see if the owner of the current script matches the owner of the file to be operated on by a file function or its directory. So if your script runs as 'nobody', or as 'root' and you create a folder with that script, you won't even be able to upload to it!. So you need to create the folder with your userid, and the only way to do that is with FTP. Here's the code:

function ftp_chmod($ftpstream,$chmod,$file)  {
    //you dont need this at php5, only at php4
    $old=error_reporting(); //save old
    error_reporting(0); //set to none
    $result=ftp_site($ftpstream, "CHMOD ".$chmod." ".$file);
    error_reporting($old);//reset to old
    return $result; //will result TRUE or FALSE
}

//create a directory with correct permissions and ftp-user:
function ftp_makemydir($dirname) {
    $dirname = "public_html/images/".$dirname; //start at the right place
    $host = "127.0.0.1";
    $user = "your username";
    $pass = "your password";
    $conn_id = ftp_connect($host);
    $login_result = ftp_login($conn_id, $user, $pass);
    if ((!$conn_id) || (!$login_result)) {
          //insert error text here;
    die;
    }
    ftp_mkdir($conn_id, $dirname);
    ftp_chmod($conn_id, 666, $dirname); // read & write for everyone
    ftp_quit($conn_id);
}

  • Share/Save/Bookmark

2 Responses to ' PHP: Create a Folder with Proper Permissions Via FTP '

Subscribe to comments with RSS or TrackBack to ' PHP: Create a Folder with Proper Permissions Via FTP '.

  1. Guest PHP USer said,

    on July 29th, 2006 at 3:14 pm

    what does $folder refer to? not the same as $dirname

  2. sfs said,

    on December 4th, 2008 at 1:31 am

    could u please sent the code for copying some files to the newly created folder??

Leave a reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word