Search code examples
phpfopenfwrite

Php fopen write in css file -> file empty


i have this following php code :

     $filename = '/front/style.css';
    $cssfile='#h1{font-size:12px}';
     if($id_file=fopen($filename, "w+"))
        {  
            echo'file exist';
         $id_file=fopen($filename, "w+");
         flock($id_file,1);
         fwrite($id_file,$cssfile); 
         flock($id_file,3);
         fclose($id_file);
        }
        else
        {
            echo "file don t exist";
        }

My file is empty but with space. My file exist and it s writable. I have nothing in my apache logs. I m using Mamp with php 5.3.2.

Any ideas ? Thx


Solution

  • A few mistakes I can see are:

    1. You are using fopen to check if a file exists. That does not work. With the w+ mode PHP will try to create the file if it does not exist. Use the file_exits function to check the existence of a file.

    2. You are opening the same file twice.

    Also use PHP constants(LOCK_SH, LOCK_UN) for the second argument of flock. That will make your program more readable.