Copy image from url to server PHP

As I was working for image module I got opportunity to understand copy image from URL to server. Simple source code will copy remote image and store into server.

But you need consider about the bandwidth and storage capacity of the image which you are trying copy from remote. If you are copying the image from unknown URL, image need to be scanned properly before storing into server.

For us it’s a server to server which is accessible within our organisation, so its a safer side.

Where the script will useful

Script will useful while uploading the image from API side, now a days lots of website providing upload options. If it’s from front end user can browse the image and upload. But in API side it’s not possible for browsing the image in that case user can upload image via the script.

About the script

This script will validate image and upload into server, which have entry log store information about date-time, ip address, file-name and url. Let’s walk through our script.


class copyImageUrl 
	public $url;
	public $fileName;

		Validating external image url and saving into server
		Using curl
	function getImage($url) {
		$this->url = $url;
		$ch = curl_init($this->url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1) ;
		$content = curl_exec($ch);
		$info = curl_getinfo($ch);	
			checking the contenttype is have image or not
			setting the filename and storing the image into server
		if (stristr($info["content_type"],"image")) {
			$arr = explode("/",$info["url"]);
			$this->fileName =  end($arr);
			header("Content-type: ".$info["content_type"]);
			$handler = fopen($this->fileName,"w");
		log entry with information of datetime, ip, filename and url
		using file_put_contents
	function log($logName) {
		if (isset($logName)) {
			$strLog = "date_time:".date("Y-m-d H:i:s").",ip_address:".$_SERVER["REMOTE_ADDR"].",file_name:".$this->fileName.",url:".$this->url."\r\n";
			file_put_contents($logName.'.log',$strLog, FILE_APPEND);


<?php require_once("copyImageUrl.php");
// creating object
$obj = new copyImageUrl;

// passing the remote image into getImage method

// if you want to enable the entry log, just pass the filename which want to be created