File manage sample

Public

Migration create file manually

</> CopyGet raw version
php
  1. /**
  2.   * Checks if image file exists and if not, creates one
  3.   * @param string $path
  4.   * Image path, excluding name
  5.   * @return integer
  6.   * File fid
  7.   */
  8. function prepare_image_file($path, $folder, $dst_folder) {
  9. $full_path = $folder . $path;
  10.  
  11. if (!file_exists($full_path)) {
  12. return NULL;
  13. }
  14.  
  15. // Check if image exists
  16. $uri = $dst_folder . $path;
  17. $check = db_select('file_managed', 'f')
  18. ->fields('f', array('fid'))
  19. ->condition('uri', $uri)
  20. ->execute()
  21. ->fetchField();
  22.  
  23. if ($check) {
  24. // File already imported
  25. return $check;
  26. }
  27.  
  28. // If file exists
  29. $image = file_get_contents($full_path); // string
  30. $xpath = $dst_folder . $path;
  31. $file = file_save_data($image, $xpath, FILE_EXISTS_REPLACE);
  32. $fid = $file->fid;
  33.  
  34. return $fid;
  35. }