Skip to main content
edited tags
Link
avpaderno
  • 97.9k
  • 15
  • 164
  • 284
Tweeted twitter.com/#!/StackDrupal/status/414478715658452992
Source Link

file_save_data fails in CLI

I'm trying to create a file attachment in a Drupal content node from a command line script. When I'm calling file_save_data(), passing a public://something URL as destination, it fails. I've tracked down the failure to the is_dir("public://") call in Drupal's file.inc that somehow returns false.

Attachments work from the regular Web interface - there's r-x permission on all relevant folders. The script should be running under the same user as Apache - I call it from Apache in the first place, using PHP's exec(). When I call is_dir(DRUPAL_ROOT."/sites/default/files") - that is, on the underlying filesystem folder - it returns TRUE, so it's probably not permissions. Looks as if the URL wrappers are somehow off when running under CLI. There's no open_basedir in php.ini, no safe mode either.

For completeness' sake, here's the relevant portion of the script:

//Drupal bootstrapping
define('DRUPAL_ROOT', getcwd());
require_once('./includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$user = user_load(1);

//Some irrelevant stuff here...
$file_content = file_get_contents($file_name); //Comes from somewhere else
$file = file_save_data($file_content,
        "public://".$file_name, FILE_EXISTS_REPLACE); //Returns false! :(

And here's how I call the script from my custom module:

function mymodule_entity_insert($entity, $type)
{
    if($type == "node" && $entity->type == "mytype")
    {
        $module_path = drupal_get_path('module', "mymodule"); //That's where the script is
        exec("php $module_path/thescript.php  ".
            ">/home/me/drlog.txt ".
            "2>/home/me/drlog.txt &");
    }
}