3

i am trying to save a remote image to a file using php curl but the file never get saved! could any one help me how to troublshoot this problem ? the image file never get created and but echo $returned_content has the data!

 <? $returned_content = get_data('http://somesite.com/43534545345dfsdfdsfdsfds.jpg'); echo $returned_content; $fp = fopen('43534545345dfsdfdsfdsfds.jpg', 'w'); fwrite($fp, $returned_content); fclose($fp); /* gets the data from a URL */ function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $data = curl_exec($ch); curl_close($ch); return $data; } ?> 
4
  • When u echo $returned_content do you see data? Also change 'w' to 'wb' Commented Nov 4, 2013 at 0:41
  • Thanks for reply.yes i see the data.what chmod should i put for folder that has the php script without creating security problem ? Commented Nov 4, 2013 at 0:45
  • 755 should be fine normally Commented Nov 4, 2013 at 2:55
  • i tried 755 but i get error cant open file 43534545345dfsdfdsfdsfds.jpg error! Commented Nov 4, 2013 at 22:32

2 Answers 2

6
<?php $ch = curl_init('http://www.example/2012/09/flower.jpg'); $fp = fopen('/localProject/imagesFolder/newname.jpg', 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp); ?> 
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

 <?php function getImagen($url, $rename, $ch) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec ($ch); curl_close ($ch); $fp = fopen("$rename.jpg",'w'); fwrite($fp, $rawdata); fclose($fp); } $ch = curl_init(); $image ="http://sampleurl.com/imagen.jpg"; getImagen ($image, "imagen", $ch); ?> 

Works 100% :)

3 Comments

what chmod should i put for folder that contains the script ? and how to use the same file name as orginal file name?for example how to use file name from any dynamic image url and use that name to save that image ? how to error checking if the file saved or not ?
use file_exist for the error checking and, in var $rename of the script you can save any name. (sorry for my english) and... maybe your folder that contains the script need permission.
Note that this requires holding the entire file in memory before writing it. Wastes memory and will fail on larger files. See CURLOPT_FILE to allow curl to write to a file as it is actively downloading the remote resource

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.