Following code shows how to get an image file by providing an URL and to save it in the local drive.
function file_get_contents_curl($url) {
$file_data=array('data'=>null,'info'=>array('http_code'=>null));
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$file_data['data'] = curl_exec($ch);
if (!curl_errno($ch)) {
$info = curl_getinfo($ch);
$file_data['info'] = $info;
}
curl_close($ch);
return $file_data;
}
$file_data = $this->file_get_contents_curl($url);
$ext = null;
if($file_data['info']['http_code'] == 200 && strpos($file_data['info']['content_type'], 'text/html') === false ){
if($file_data['info']['content_type'] == "image/jpeg"){
$ext = ".jpeg";
}else if($file_data['info']['content_type'] == "image/jpg"){
$ext = ".jpg";
}else if($file_data['info']['content_type'] == "image/png"){
$ext = ".png";
}else if($file_data['info']['content_type'] == "image/gif"){
$ext = ".gif";
}
if(!empty($ext)){
$dir = 'images/by_name';
$is_saved = file_put_contents( $dir.'/'.$file_name.$ext, $data);
if($is_saved >0 ){
echo "Product name : $product_name :: Image File Name : $new_file_name :: Image file name by Id : $new_file_name_by_id :: Extension :". $file_data['info']['content_type'] .":: Is saved by name: $is_saved_by_name :: Is saved by Id: $is_saved_by_id<br>";
}
}
}
Comments
Post a Comment