title: Base64 image string into image file using PHP
body: <p>I need code to convert a base64 image string into an image file and write into local directory using PHP. I tried:</p>
  
  <pre class="lang-php prettyprint-override"><code>function user_profile_photo(){
              $input = urldecode(file_get_contents('php://input'));
              $received = json_decode($input, true);
              $user_id = $received['user_id'];
              $img = $received['imagecode'];
              $imagedata = base64_decode($img);
              $image_path='uploads/images/'.$user_id;             
              $path = '/var/www/html/empengapp/uploads/images/'.$user_id;
              if (!file_exists($path)) {
                     mkdir($path, 0755, true);
               }
  
  $new_name = date('ymd').time().'.jpg';
  $pathwithfile = '/var/www/html/empengapp/uploads/images/'.$user_id.'/'.$new_name;
  $success = file_put_contents($pathwithfile, $imagedata);
  var_dump($imagedata);exit;
  
  
  
  
              $this-&gt;output
                  -&gt;set_status_header(200)
                  -&gt;set_content_type('application/json', 'utf-8')
                  -&gt;set_output(json_encode($resp, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
                  -&gt;_display();
                  exit;
      }//end of function user_profile_photo
  </code></pre>
  
  <p>It is writing a file with given extension, but when you try to open file it shows an invalid file error.</p>