3

Normally when saving a node with the content type form, uploading a file will automatically rename it if the file name is already in the database.

I am creating nodes programatically. Everything works fine, except if the file name is in the database it fails as this is, of course, a unique field.

What function does Drupal use to check if the name already exists and chanages it accordingly? I could write one, but as drupal already seems to handle this perfectly, I dont see a reason to reinvent the wheel. Here is my code for the file saves.

$file = new stdClass();
$file->filename = basename($local_path);
$file->filepath = $local_path;
$file->uri = $local_path;
$file->filemime = $mime;
$file->filesize = filesize($local_path);

$file->uid = $uid; 
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

$images[] = array(
'fid' => $file->fid,
'alt' => $page_data['title'],
'title' => $page_data['title']
);

1 Answer 1

3

Drupal uses the file_create_filename() function to do that, you can call it like this:

$basename = drupal_basename($local_path);
$directory = drupal_dirname($local_path);
$local_path = file_create_filename($basename, $directory);

$file = new stdClass();
$file->filename = drupal_basename($local_path);
$file->filepath = $local_path;
// etc...
2
  • In your code you used $local_path = file_create_path($basename, $directory);. Did you mean $local_path = file_create_filename($basename, $directory)?
    – blue928
    Commented Feb 27, 2012 at 7:36
  • Yes I did, sorry!
    – Clive
    Commented Feb 27, 2012 at 8:04

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.