title: saving blob to image files in php
body: <p>I have an image in my database saved as a large BLOB. and now I want to retrieve it and save it to my file system.</p>
  
  <p>for this purpose I have done the following, but the images that were saved to my file system were corrupted ones.</p>
  
  <p>Approach1:</p>
  
  <pre><code>$basedir = 'images/';
  $imagename = strtolower(preg_replace('/([^\w\d\-_]+)/', '-', $row-&gt;name));
  $filename = $basedir . $imagename . '_' . $row-&gt;id. '.jpg';
  $file_content = base64_decode($row-&gt;image_data);
  return file_put_contents($filename, $file_content);
  </code></pre>
  
  <p>Approach2:</p>
  
  <pre><code>$basedir = 'images/';
  $imagename = strtolower(preg_replace('/([^\w\d\-_]+)/', '-', $row-&gt;name));
  $filename = $basedir . $imagename . '_' . $row-&gt;id . '.jpg';
  fopen($filename,'w');
  if($fh = fopen("{$filename}", "wb")) {
      fwrite($fh, base64_decode($row-&gt;image_data));
      fclose($fh) ;
  }
  </code></pre>
  
  <p>Please help!!!</p>