Attach an existing file to a node programmatically



/**
 * Code that will enable attachment of a pre-existing file on the filesystem
 * to a node that requires it. 
 */
function attach_file(&$node, $file_location, $lang = 'en') {
  global $doc_base_path;

  $file_location = str_replace('\\','/', $file_location);

  $actual_file = $doc_base_path . "/" . stripslashes($file_location);
  if (!file_exists($actual_file)) {
    print "**** FILE NOT FOUND ****\n";
    print $actual_file;
    print "^^^^ FILE NOT FOUND ^^^^\n";
  } else {

    print "File GOOD\n";
    print "Filesize: " . filesize($actual_file);
  }

  $file_arr = array(
    "uid" => 1,  // Set owner ID
    "filename" => stripslashes(substr($file_location, strrpos($file_location, '/') +1 )),
    "uri" => "public://myportal_docs/" . stripslashes($file_location),
    "filemime" => "application/msword",  // set this accordingly or inspect the file for it.
    "filesize" => filesize(stripslashes($doc_base_path . "/" . $file_location)),
    "status" => 1,
    "timestamp" => time(),
    "rdf_mapping" => array(),
    "display" => 1,
    "description" => null,
  );

  $myfile_obj = (object)$file_arr;
  $file_with_id = file_save($myfile_obj);

  $file_arr_with_id = (array)$file_with_id;

  $node->field_mydoc_file[$lang][0] = $file_arr_with_id;
}