PHP - Unable to create file

5.7k Views Asked by At

I am trying to create a file on my web server with an option chosen from a web form. The file never gets created and I keep getting the "Can't Open File" message.

<?php
    if(isset($_POST["style"])) {
            $boots = $_POST["style"];
    }
    $file = "bootsstyle";
    if(!file_exists($file)) {
            touch($file);
            chmod($file, 0777);
    }
    $openFile = fopen($file, "w+") or die("Can't open file");
    fwrite($openFile, $boots);
    fclose($openFile);
?>

I have been scouring the Internet for an hour and am not sure where I am going wrong. I have checked the permissions in the directory and they are 0777.

2

There are 2 best solutions below

0
On
$boots = "your data";
$file = "bootsstyle";
if(!file_exists($file)) {
    touch($file);
    chmod($file, 0777);
}
$openFile = fopen($file, "w+") or die("Can't open file");
fwrite($openFile, $boots);
fclose($openFile);
$myfile=fopen($file, "r");
echo fread($myfile,filesize($file));
fclose($myfile);
0
On

The problem is with the permissions for the directory in which you are trying to create the file. The directory in which the php script is located must be writable by the user group named www-data. There are two methods to solve this.

Method 1: Changing permission of directory

You can just change the permission of directory to 777. To do this, open a terminal and navigate to the directory in which your php script resides. Now execute the command

sudo chmod 777 ./

Method 2: Making www-data as owner of directory

Open a terminal and navigate to the directory containing the php script. Now, execute the command

sudo chown www-data ./ && sudo chmod 774 ./

You can learn more about Linux permissions and the difference between 774 and 777 from
https://linode.com/docs/tools-reference/linux-users-and-groups/

Note:
Opening a file in w+ mode create the file if it does not exist. So you do not have to touch it.

Note:
The above code is tested on kali linux 2017.3.2 running LAMP server.