title: Write binary file in PHP
body: <p>I have wrote a PHP file which will save a JPEG file in the server and part of the code is listed as follow:</p>
  
  <pre><code>    //create folder if folder not exist
  if (!is_dir($save_path)){
  
      $old = umask(0);
      $flag = @mkdir($save_path,0777);
      umask($old); 
  
  if(isset($flag)){
      $string = 'Folder Create Success!'."\n";
  }else{
      $string= 'Folder Create Fail!'."\n";
  }
  echo $string;
  
  }else{
  
     echo "Folder exist!!!!";
  
  }
  
  
  //write the content to the server
  $base=$_REQUEST['image'];
  $binary=base64_decode($base);
  header('Content-Type: image/jpg; charset=utf-8');
  
  if(!$file = fopen($path, 'wb')){
  
      echo 'Image upload Fail!'."\n";
      return;
  }
  else
  {
  
      fwrite($file, $binary);
      fclose($file);
  
  }
  </code></pre>
  
  <p>The problem is when I run the code, if the folder does not exist, it create the folder only but the content can't save in the folder. The error message is :</p>
  
  <p>[Thu Jul 05 16:59:06 2012] [error] [client 10.95.61.220] PHP Warning:  fopen(/mnt/csis/upload/newphoto/others/12346_test/12346_test_2012-07-05_others_abc.jpg): failed to open stream: Permission denied in /var/www/html/upload_image.php on line 57</p>
  
  <p>However, if I run the code again, since the folder was created in the past, it work properly. The content can save in the folder......</p>
  
  <p>Anything I get wrong? I try to find the answer on the web but still can't solve the problem.</p>
  
  <p>Anyone can help, many thanks!</p>