Tell me more ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

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']
);
share|improve this question

1 Answer

up vote 2 down vote accepted

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...
share|improve this answer
In your code you used $local_path = file_create_path($basename, $directory);. Did you mean $local_path = file_create_filename($basename, $directory)? – blue928 Feb 27 '12 at 7:36
Yes I did, sorry! – Clive Feb 27 '12 at 8:04
thanks! great advice! – blue928 Feb 27 '12 at 10:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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