Skip to content

Instantly share code, notes, and snippets.

@zuhairkareem
Forked from liberatr/create_file.php
Created August 7, 2016 10:00
Show Gist options
  • Save zuhairkareem/59c23dab9614a4a78faa18b7f07885bb to your computer and use it in GitHub Desktop.
Save zuhairkareem/59c23dab9614a4a78faa18b7f07885bb to your computer and use it in GitHub Desktop.
Programmatically save a file to Drupal from your local file system.
/**
* Saves a file on your local file system you want to copy to Drupal default files directory.
* This assumes you have bootstrapped Drupal.
* Originally written to be invoked within a Behat context.
*/
use Drupal\file\Entity\File;
$file = new File(array(), 'file');
$file->setFilename("image-fact.jpg");
$file->setPermanent();
$file->setFileUri(rtrim(realpath("/var/www/backup/files"), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$file->getFilename());
$file->set('langcode', $file->language()->getId());
$file->setChangedTime(time());
$dest = file_build_uri(drupal_basename($file->GetFileUri()));
$result = file_copy($file, $dest, FILE_EXISTS_REPLACE);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment