1

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.

7
  • Try to check output of php_info, it might be that local file operations are disabled for security reasons? Commented Dec 13, 2014 at 10:42
  • Well; does the file_exists get called? Does that barf out? If the file exists you might not have access to the file anyway.. Commented Dec 13, 2014 at 10:44
  • PHP has some "security" options that could be blocking you Commented Dec 13, 2014 at 10:44
  • dude your code is working Commented Dec 13, 2014 at 10:44
  • Since you use the w+ flag in open, touch is not necessary and chmod seems a bad idea to me. (at least with 777). Commented Dec 13, 2014 at 10:44

2 Answers 2

2
$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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.