January 7, 2011

Is it possible to Copy images from web to your Hard Drive?

Question by Starx

I am trying to create a page for just personal use. What I want to do is, create a system through which I can download images to my local hard disk, directly by providing the link through a localhost like WAMP. The reason I am trying to do is, I want the images to be automatically sorted onto my hard disk. My form field will be something like this

<form method="POST" action="process.php">
   <input type="text" name="URL" id="URL" />
   <input type="text" name="category" id="category" />
   <input type="text" name="subcategory" id="category" />
   <input type="submit">
</form>

Now, in the process.php

//This is just a sample... So please ignore the roughness of the coding

copy($_POST['url'],$_POST['category']."/".$_POST['subcategory']."/somename.jpg");

// If you noticed, the categories and subcategories are actually the name of directory, where I want the picture to go be saved....

I am thinking my approach is wrong. How can I achieve something like this?

Error

Warning: copy(images/image.jpg) [function.copy]: failed to open stream: No such file or directory in

Answer by Starx

Ok, I used curl instead to achieve what i am expecting. Here is the piece of code

$img = $_POST['url'];
$fullpath = $_POST['category']."/".$_POST['subcategory']."/".basename($img);
$ch = curl_init ($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec($ch);
curl_close ($ch);                   
$fp = fopen($fullpath,'x');
fwrite($fp, $rawdata);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!