Rik89
Rik89

Reputation: 135

chmod($file) not working exactly as I want it to

I was using the chmod($path, $mode, bool) function, but it wasn't setting permissions correctly, so I am now trying:

$fp = fopen($path, 'w');
fclose($fp);
chmod($path, 0750);  //changed to add the zero
return true;

problem is when I use the first method it creates the path ok... something like this uploads/2013/name/1/file.pdf(correct) but the permissio0ns are incorrect.

when I use the second method it creates a file with no extension: uploads/2013/name/1(incorrect) but the permissions are correct...

Here is my code:

if($_POST["upload"]){

$year = date('Y');

//path to directory
$path = $_SERVER["DOCUMENT_ROOT"] . '/uploads/' . $year . '/' . strtolower(str_replace(' ','',$_POST["username"])) . '/' . $_POST["month"];

//path to file
$target_path = $path . '/' . basename($_FILES['uploadedfile']['name']);

$filename = basename($_FILES['uploadedfile']['name']);

/* $ext = substr($filename, strrpos($filename, '.') + 1); */

if(!is_dir($path) && !file_exists($target_path)) {

    mkdir($path, 0750, true);

    chmod($path, 0750, true);  //changed to add the zero

    if(($_FILES["uploadedfile"]["type"] == "application/pdf") && ($_FILES["uploadedfile"]["size"] < 550000)) {

        if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)){

            print "<div class='success'>The file " . "<span class='filename'>" . basename( $_FILES['uploadedfile']['name']) . "</span>" . " has been uploaded</div>";
        }
    } else {

        print "<div class='error'>Wrong file format</div>";

    }

} else {

    print "<div class='error'>File already exists!</div>";

}

}

Upvotes: 0

Views: 199

Answers (2)

jami
jami

Reputation: 300

It looks like your script is executed in a webserver context. So it may be that the webserver-user did not have the rights to change the file rights or a system umask is set.

Since php's chmod is only a wrapper for systems chmod you could easily try this command as the executing user.

For example on my system (www-data is the apache user)

$ cat /etc/*release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.10
DISTRIB_CODENAME=quantal
DISTRIB_DESCRIPTION="Ubuntu 12.10"
NAME="Ubuntu"
VERSION="12.10, Quantal Quetzal"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu quantal (12.10)"
VERSION_ID="12.10"
$ sudo su - www-data -s /bin/bash
$ chmod 750 myfile

Upvotes: 0

Jesper Blaase
Jesper Blaase

Reputation: 2400

Looks like your running into an issue with umask try doing a:

umask(0)

in the beginning of your script.

The default umask is fetched from your system configuration and is normaly 0022 and this is applied everytime you do a chmod in php so a chmod 0777 with a umask of 0022 turns into a 0755

Upvotes: 1

Related Questions