title: Drupal 7 - Upload Image Programmatically
body: <p>I would like to upload an image in a custom module. The image must be permanently saved and renamed if needed. Later I want to be able to display the image somewhere on my form or wherever I want.</p>
  
  <p>My current code:</p>
  
  <pre><code>function my_module_name_new_form()
  {
   ....
  
  $form['icon'] = array
  (
      '#type' =&gt; 'file',
      '#title' =&gt; t('Icon'),
      '#description' =&gt; t('Click "Chose File" to select an image to upload.')
  );
  
   ....
  }
  </code></pre>
  
  <p>In the submit hook I have:</p>
  
  <pre><code>// Icon
  $filename = $form_state['values']['icon'];
  $dest = file_build_uri($filename); 
  file_save_data('My data', $dest, FILE_EXISTS_RENAME); 
  </code></pre>
  
  <p>Nothing happens... I couldn't find any Drupal 7.x compatible modules either that somehow make life easier here.</p>
  
  <p><strong>Solution:</strong></p>
  
  <pre><code>//----------------------------
  // Icon
  //----------------------------  
  $dest_dir = file_default_scheme() . '://';// Note: file_directory_path() was removed in Drupal 7.x. // $dest_dir contains the destination directory for the file. 
  
  $validators = array('file_validate_extensions' =&gt; array('jpg png gif'));
  
  //Save file
  if ($file = file_save_upload('icon', $validators, $dest_dir))
  {
      $filename = $file-&gt;filename;        
      $file_content = file_get_contents($dest_dir.$filename); // Fatal error: Cannot access empty property in C:\xampp\htdocs\drupal\modules\custom\achievements\achievements.module on line 446
  }
  else
  {
      form_set_error('icon', 'Could not upload file.');
  }
  // To display the image: // die('&lt;IMG SRC="'.file_create_url($dest_dir.$filename).'"/&gt;');
  //----------------------------  
  </code></pre>