Snippet Code : How to Force Download Image from Unsplash.com with PHP

Who does not know unsplash? Unsplash is a website that provides free large size images, you can use for any purpose. Their promise is: give 1 HD image, high quality for free every day. The images you can use for a blog post, templates, brochures or in print.

Well, I need a way to transfer the picture into my server. Here’s the code I used. Perhaps, you will need it.

<?php 
$file = 'https://ununsplash.imgix.net/photo-1422479516648-9b1f0b6e8da8?q=75&fm=jpg&s=c5f2b3df2a4c71532b3b354b8766503c';
download($file);

function download($url) {
    set_time_limit(0);
    $ch = curl_init();
	$rename="newname_".date('y_m_d_G_i_s');
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $r = curl_exec($ch);
    curl_close($ch);
    header('Expires: 0'); // no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
    header('Cache-Control: private', false);
    //header('Content-Type: application/force-download');
    //header('Content-Disposition: attachment; filename="' . basename($url) . '"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . strlen($r)); // provide file size
    header('Connection: close');
    //echo $r;
	
	$fp = fopen("$rename.jpg",'w');
	fwrite($fp, $r); 
	fclose($fp);
}
?>

I am was tested it and working 100%.

If this snippet is help you, please share in your social network.

Want to get new wordpress theme? just visit our brand new wordpress theme directory

Leave a Reply

Your email address will not be published. Required fields are marked *