Hello.

$ link - address of the picture.

$ site - the address to which you upload the image

$url['photo'] = new CURLFile($link); $ch = curl_init($site); curl_setopt($ch, CURLOPT_POST, true); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt($ch, CURLOPT_POSTFIELDS, $url); curl_close($ch); 

If the $ link is the address of a local (/var/www/olo-lo/123.jpg) picture, then everything works, if it is from the outside, it does not work. How to get a picture via https without saving to the file system and immediately upload it to the required address?

I tried it in different ways, and get the image through file_get_contents () and without it, and use CURLFile () with and without options ... There is only one correct solution. Which one

  • Not that. I tried, did not work. I understand that somehow the image is not correctly transferred to the curl_setopt line ($ ch, CURLOPT_POSTFIELDS, $ url); - polger
  • And why do you write the url in the post data? php.net/manual/ru/function.curl-setopt.php CURLOPT_URL to specify the address of the appeal serves. - Visman
  • Do not quite understand. $ url is already an object from CURLFile () - polger
  • Do you want to send a file from your server to a remote one? - Visman

1 answer 1

Since CURLFile only works with local files, why not download the image to disk?

 $link = 'https://example.com/image.jpg' $link_local = tempnam(sys_get_temp_dir(), 'FOO'); file_put_contents($link_local,file_get_contents($link)); $url['photo'] = new CURLFile($link_local,'image/jpeg','image.jpg'); $ch = curl_init($site); curl_setopt($ch, CURLOPT_POST, true); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt($ch, CURLOPT_POSTFIELDS, $url); curl_close($ch); unset($url['photo']); unlink($link_local); 

you may need to change the header of the User-Agent if the site blocks downloading images from php, and / or add the Referrer header if the site blocks hotlink

PS download from https sites requires the php_openssl library php_openssl and the allow_url_fopen option (both can be viewed in phpinfo)

 extension=php_openssl.dll allow_url_fopen = On 
  • But this is a crutch ... Write the file to hard, read, delete. And so many, many times. The picture is downloaded without problems. - polger
  • @polger Well, in this case, the "correct" solution would be: get the file as a stream and, in the process of receiving, send it to the server. Both for receiving and sending, in such a case, you will have to manually make requests through fsockopen, or use libraries ... HTTP implementation sheet chunked, multipart request ... You can write all this on php, but it is difficult. - Sanya_Zol September
  • And save to disk as you wrote is not such a big problem. Great option. ))) - polger