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";
3

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Hi can you please explain more I'm trying to upload image using your code but I didn't succeed. Thank you
The code downloads it does not upload. The ticket title is confusing. Uploading files is more complicated since you probably also need to authenticate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.