PHP Code

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 = "";
    $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;
    ftp_mkdir($conn_id, $dirname);
    ftp_chmod($conn_id, 666, $dirname); // read & write for everyone


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

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

  3. Hi..
    This is good one what i am searching for.

    Mr.Sangram Keshari Patra

Leave a Reply

Your email address will not be published. Required fields are marked *

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.
Anti-spam image