Drupal: Add image/file into Profile2 programmatically

0 votes
96 views
asked Dec 7, 2015 in Programming by wikiandroid (10,110 points)
This is not a question, after all hard times, I could get a solution about this. I will share the codes in the answer section below.

1 Answer

0 votes
answered Dec 7, 2015 by wikiandroid (10,110 points)
 
Best answer
<?

//First upload image
if (isset($_FILES['file']))
{
    if ($_FILES["file"]["error"] > 0)
    {
        echo "Error: " . $_FILES["file"]["error"] . "<br>";
    }
    else
    {
        if (!file_exists("public://". $_FILES["file"]["name"]))
            move_uploaded_file($_FILES["file"]["tmp_name"],"public://" . $_FILES["file"]["name"]);
    }
}
    
$file_drupal_path =  "public://" . $_FILES["file"]["name"];
// Create file object and update files table
// Load the files contents
$image = file_get_contents("http://***************/******/******.png");

// Returns the new file object
$file = file_save_data($image, $file_drupal_path, FILE_EXISTS_RENAME);

/*
print_r($file);
[fid] => 177
[uid] => 1
[filename] => testrapor.png
[uri] => public://katalog/reports/testrapor.png
[filemime] => image/png
[filesize] => 462
[status] => 1
[timestamp] => 1449239202
[rdf_mapping] => Array     ()
[display] => 1
[description] =>
*/

//$profile->field_dosya['und'][0]=(array)$file;
$profile->field_file['und'][0] = (array)$file;//array( 'fid' => $file->fid, 'display' => 1, 'description' => '', );
//print_r($profile);
...