2

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 &");
    }
}
1
  • You might be using a different user when executing a script than the apache user.
    – Berdir
    Dec 20, 2013 at 16:16

1 Answer 1

1

Stupid bug. The script would change the current directory. Drupal code, it seems, assumes that it will be running from Drupal root, so the file attachment paths are relative internally. chdir(DRUPAL_ROOT) before calling file_save_data fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.