0

I'm trying to post a photo to Facebook and it works as long as the image is in the same folder as the PHP script:

  $file= "myimage.png";
    $args = array(
        'message' => 'Photo from application',
        );
      $args[basename($file)] = '@' . realpath($file);
    $ch = curl_init();

What do I need to change to make it work for external images, e.g.:

$file= "http://www.example.com/myimage.png";
Matt
  • 2,981
  • 5
  • 23
  • 33

2 Answers2

3

You must first download the image to your server then use that path. Here's an example of downloading the image to a temporary file:

$temp_name = tempnam(sys_get_temp_dir(), "external");
copy($file, $temp_name);
// ...
$args[basename($file)] = '@' . realpath($temp_name);
1

To be sure file is downloaded without damage I prefer this way.

$path = '/where/to/save/file';
$url = 'http://path.to/file';

$remote = fopen($url, "rb");
if($remote) {
    $local = fopen($path, "wb");
    if($local) {
        while(!feof($remote)) {
            fwrite($local, fread($remote, 1024 * 8 ), 1024 * 8);
        }
    }
}
if ($remote) fclose($remote);
if ($local)  fclose($local);

I recommend using uniqid() to generate the path.

Then pass the path to your code.

Since the file will now be local it should upload just fine.

transilvlad
  • 13,974
  • 13
  • 45
  • 80
  • Hi can you please explain more I'm trying to upload image using your code but I didn't succeed. Thank you – Bynd Apr 04 '19 at 14:22
  • The code downloads it does not upload. The ticket title is confusing. Uploading files is more complicated since you probably also need to authenticate. – transilvlad Apr 05 '19 at 17:19