Change Folder Permissions using PHP

Change Folder Permissions using PHP

Sometimes it’s useful to enable visitors to your site to upload content, for example, photos, which can then be displayed on the site.

Folders on a website, for example, an images folder will typically have permissions of 755, which means that normal visitors to the site will be unable to upload content into the folder. They will receive an error message when they try to do so.

In order to allow the upload, one solution is to temporarily change the permissions on the folder to 777 before the upload is made, and then to change them back to 755 after the upload has been made.

The following PHP script shows how you can do this using PHP’s ftp_site command. This script only changes the permissions one way (to 777), it doesn’t change them back. You would need to extend the script or write another one to do this. The line that reads $mod = ‘0777′; // permissions to be set is the one that determines what the permissions are going to be set to.

<?php

// Set up variables

$host = ‘www.pcx3.com’; // host (website) that contains the folder you want to change

$user = ‘username’; // username to log onto the host

$password = ‘password’; // password to log onto the host

$folder = ‘public_html/test/’; // folder name to change

$mod = ‘0777′; // permissions to be set

// connect to FTP site

$conn = ftp_connect(”$host”);

if (!$conn)

{

echo ‘Error: Could not connect to ftp server’;

exit;

}

// log in to FTP site

@ $result = ftp_login($conn, $user, $password);

if (!$result)

{

echo “Error: Could not log on as $user”;

ftp_quit($conn);

exit;

}

// try to change the permissions on the directory

if (ftp_site($conn, ‘CHMOD ‘.$mod.’ ‘.$folder)) {

echo “Successfully changed permissions”;

}

else {

echo “There was a problem changing the permissions”;

ftp_quit($conn);

exit;

}

// close the connection

ftp_close($conn);

?>

The script is fairly straight forward. You initially set up a few variables for the host name and stuff like that, you then connect to the FTP site, log on to the site, change the permissions of the folder, and then finally log off.

The path to the folder (assigned to $folder) will be something like ‘public_html/…/’. Check with your ISP if you’re not sure what this is.

Have fun!

whoami
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.