3

I have the following code:

    <?php
        $myfile = fopen("code2.css", "w") or die("Unable to open file!");
        $txt = "John Doe\n";
        fwrite($myfile, $txt);
        $txt = "Jane Doe\n";
        fwrite($myfile, $txt);
        fclose($myfile);
    ?>
?>

code2.css is in the same folder as my PHP file, but it throws me:

Unable to open file all the time.

How can I fix this?

Update: After playing with permissions the error dissapeared, but still my file won't be updated.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
stranger4js
  • 269
  • 4
  • 15

3 Answers3

3

Check the properties of code2.css. You must found the "read only" permission to it, and change it to "Read and Write". After that your code will work.

If you are using a Linux system, then execute:

sudo chmod 777 code2.css
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Neo
  • 407
  • 5
  • 18
  • And where is the solution so that OP's code work?! Here i only see a comment! – Rizier123 Dec 16 '14 at 13:49
  • actually I used the same code just removed unnecessary ?> and it worked – Neo Dec 16 '14 at 13:54
  • Maybe for you, but OP clearly said in the comment's under his question that it didn't worked for him! (See: http://stackoverflow.com/questions/27505561/cant-open-file-php/27505943?noredirect=1#comment43441136_27505561) – Rizier123 Dec 16 '14 at 13:55
  • for your kind of information it didnot worked in my system too ... but what ever the procedure I have followed in my system, after that I got the two lines written in code2.css. This is the only reason why I have not put comment and posted separate answer – Neo Dec 16 '14 at 14:00
2
<?php  
    $myfile = fopen("code2.css", "w") or die("Unable to open file!");
    $txt = "John Doe\n";
    fwrite($myfile, $txt);
    $txt = "Jane Doe\n";
    fwrite($myfile, $txt);
    fclose($myfile);//just removed the closing php tag from here and it is working fine 
?>
2

fopen() returns false and generates an E_WARNING alert on fail.
You should begin with displaying all warnings, you'll get more information on the issue:

error_reporting(E_ALL);
ini_set('display_errors', '1');

Please post the warning. Probably rights on your file or folder. Please make sure your webserver has write rights on it. What system are you running your localhost on?

fpierrat
  • 739
  • 7
  • 25