Skip to content

Instantly share code, notes, and snippets.

@samundra
Forked from roshanbh/download-file-from-http.php
Last active March 12, 2022 22:45
Show Gist options
  • Save samundra/7819411 to your computer and use it in GitHub Desktop.
Save samundra/7819411 to your computer and use it in GitHub Desktop.
<?php
/**
* Saves remote image using Curl request
* @param string $img URL from which image is to be retrieved
* @param string $fullpath Full path to the image
* @param string $imageVerify Fullpath where image will be saved.
* @see http://stackoverflow.com/questions/10890617/grabbing-image-with-curl-php
*/
function saveImage($img, $fullpath = null, $imageVerify = true) {
// Verify that we have image files
if ($imageVerify === true) {
$file = getimagesize($img);
$mime = $file['mime'];
if (!in_array($mime, $this->validImages)) {
$this->_errors[] = $img . ' is not valid image. Skipped.';
return false;
}
}
$this->_current_queue = pathinfo($img);
if ($this->preserve_filename == true) {
$filename = '';
if ($this->prefix) {
$filename .= $this->prefix;
}
$filename .= mt_rand();
if ($this->suffix) {
$filename .= $this->suffix;
}
$ext = isset($this->_current_queue['extension']) ? $this->_current_queue['extension'] : 'jpg';
$filename .= '.' . $ext;
//$filename = $this->prefix.'_'.$t.'_'. $this->suffix . '.'.$this->_current_queue['extension'];
} else {
$fn = $this->_current_queue['filename'];
$ext = isset($this->_current_queue['extension']) ? $this->_current_queue['extension'] : 'jpg';
$filename = md5($fn . me_rand() . rand(5, 15)) . '.' . $ext;
//$filename = $this->_current_queue['basename'];
}
$this->_files[] = $filename;
if ($fullpath === null) {
$filepath = $this->_dirname . $filename;
$ch = curl_init($img);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$rawdata = curl_exec($ch);
curl_close($ch);
// Remove the previously stored file
if (file_exists($filepath)) {
unlink($filepath);
}
} else {
$filepath = $fullpath;
}
$fp = fopen($filepath, 'w');
fwrite($fp, $rawdata);
fclose($fp);
}
?>
@umut58tr
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment