Sunday, June 7, 2009

Copy an image from a remote URL to a local file

 

This code copies the remote image to your local server. it is pretty basic as it does not check if the file already exists. For that, use the rename if exist function.

<?
//original image
$img = "http://www.images.com/anyimage.jpg";
//isolate the filename from the URL
$fname= basename($img); 
//directory to copy to (must be CHMOD to 777)
$copydir = "/var/www/upload/";   // change as required
$data = file_get_contents($img);
$file = fopen($copydir . $fname, "w+");
fputs($file, $data);
fclose($file);
?>

Other possibility:


// example usage: download_file('whatever.jpg');
function download_file($filename, $mimetype = 'application/octet-stream')
{
  if (!file_exists($filename) || !is_readable($filename)) return false;
  $base = basename($filename);
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=$base");
  header("Content-Length: " . filesize($filename));
  header("Content-Type: $mimetype");
  readfile($filename);
  exit();
}

-------------------------------------

A third possibility:

<?php
$handle = fopen(“http://content8.flixster.com/photo/10/89/19/10891930_tml.jpg”, "rb");
$contents = '';
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
fclose($handle);
?>

De $contents can then be saved

 

Or even simpler:

<?
getfile('http://content8.flixster.com/photo/10/89/19/10891930_tml.jpg','upload' );

// $url is the url of the file
// $dir is the directory to save the file to relative to the current working directory
function getfile($url, $dir){
file_put_contents($dir.substr($url,strrpos($url,'/'),strlen($url)), file_get_contents($url));
}
?>

Obviously this works for non-image files as well

No comments:

Post a Comment