Search This Blog

Google Analytics

Wednesday, May 23, 2007

PHP: Create Directory, Safe Mode Headache, etc

Many times when creating directories via script on a Linux/Unix machine can result in permission problems. Below will make sure it work provided FTP username and password provided is a user id with higher rights.

function site_mkdir($dir)
{
    if (is_dir($_SERVER['DOCUMENT_ROOT'] . '/' . $dir))
    {
        return(true);
    }
 
    if (!$ftp_connection = ftp_connect('ftp.server'))
    {
        return(false);
    }
 
    if (!ftp_login($ftp_connection, 'user', 'password'))
    {
        return(false);
    }
 
    if (!ftp_chdir($ftp_connection, 'httpdocs'))
    {
        return(false);
    }
 
    $dir_list = explode('/', $dir);
    foreach ($dir_list as $current)
    {
        if ($current != '')
        {
            if (!@ftp_chdir($ftp_connection, $current))
            {
                if (!ftp_mkdir($ftp_connection, $current))
                {
                    ftp_close($ftp_connection);
                    return(false);
                }
                else
                {
                    ftp_site($ftp_connection, 'CHMOD 0777 '.$current);
                    ftp_chdir($ftp_connection, $current);
                }
            }
        }
    }
 
    ftp_close($ftp_connection);
 
    return(true);
}

It does this:
  • check if the dir to create already exists; if it does, simply quit, otherwise continue
  • login to my ftp server (same server as the script is running on)
  • change to the base dir ($dir will use this as a base reference)
  • split up $dir and walk through the list
  • check if dir exists
  • if not, create it
  • if not, chmod it to 0777
  • if exists, just continue
  • closes connection

Speed is a little slower then I wanted. But when dir allready exists there is no real speed difference. So I 'solved' the speed problem by creating the dirs when I know they will be needed in the future, rather than creating them at the moment I need them.

1 comment:

  1. This is very helpful in making FTP username and password in PHP without getting any permission problem in making directories via script on Linux and Unix machine. I am learning so much from this.

    ReplyDelete

Do provide your constructive comment. I appreciate that.

Popular Posts