Attach file grammatically to a node in Drupal 7

The below code shows how to upload a file to the field of the node programmatically

$file_path = 'sites/default/files/'.$fname;

$node = node_load($nid);
$file = new stdClass;
$file->uid = $node->uid;
$file->filename = pathinfo($file_path, PATHINFO_BASENAME);
$file->uri = $file_path;
$file->filemime = file_get_mimetype($file_path);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;

// Save file object to make it a 'managed file'.
file_save($file);

// We will save file under this location. public:// if it is a public file
$destination = 'private://';

// Make sure destination directory exists before moving files to that path.
// This will create directory if it does not exists.
file_prepare_directory($destination, FILE_CREATE_DIRECTORY);

// Now attach file to the file field.
$node->field_attachement[$node->language][0] = (array) $file;

// Default file type field comes with this extra properties.
$node->field_attachement[$node->language][0]['display'] = 1;
$node->field_attachement[$node->language][0]['description'] = 'Description of the file';

// Save node to make the attachment effective.
node_save($node);

You need to upload your file to the server first then run the code after setting the path of the file on your server.
$file_path = ‘sites/default/files/’.$fname;
Just change the $nid variable to your variable

Leave a Comment.