Alex
Alex

Reputation: 59

How do I download and save images from url

I have this URL

'http://2.bp.blogspot.com/-LBbpkomI7JQ/VnLmeFZANgI/AAAAAAAAWhc/MsdZjtxN0HQ/s0-Ic42/RCO001.jpg '

I tried to do some search and did this

$file = fopen("C:\Users\Alex\Desktop\script.txt", "r");
$links = array();

while (!feof($file)) {
$links[] = fgets($file);
}

fclose($file);

foreach($links as $num => $link)
{
echo "'".$link."'";
save_image("'".$link."'","'".$num."'".".jpg");

}

var_dump($links);
function save_image($inPath,$outPath)
{ //Download images from remote server
$in=    fopen($inPath, "rb");
$out=   fopen($outPath, "wb");
while ($chunk = fread($in,8192))
{
    fwrite($out, $chunk, 8192);
}
fclose($in);
fclose($out);
}

All urls are in my script.txt file so I am storing them in an array then calling each url one by one but it says

 failed to open stream: Invalid argument 

Anything missing or wrong?

Upvotes: 1

Views: 83

Answers (2)

Patrizio Bekerle
Patrizio Bekerle

Reputation: 409

You could try this implementation (works great for me):

<?php

$links = explode("\n", file_get_contents("C:\Users\Alex\Desktop\script.txt"));

foreach($links as $num => $link)
{
    echo $link . "\n";
    save_image($link, $num.".jpg");
}

function save_image($inPath, $outPath)
{
    $inPath = trim($inPath);
    if ($inPath != "") {
        file_put_contents($outPath, file_get_contents($inPath));
    }
}

assuming your script.txt looks like this

http://2.bp.blogspot.com/-LBbpkomI7JQ/VnLmeFZANgI/AAAAAAAAWhc/MsdZjtxN0HQ/s0-Ic42/RCO001.jpg

Upvotes: 1

Mateusz Palichleb
Mateusz Palichleb

Reputation: 795

In this line:

$file = fopen("C:\Users\Alex\Desktop\script.txt", "r");

Your backslashes might be converted into special chars by PHP, this could cause a problem, so look at this topic: failed to open stream: Invalid argument

Second thing: It might be a problem with fopen configuration

Edit your php.ini and set:

allow_url_fopen = On

You can check this value (it's probably false):

var_dump(ini_get('allow_url_fopen'));

You'll need to speak to your web host, or try another method. Mabye CURL is enabled?

You should also check your display_errors and error_reporting values. PHP should have complained loudly about being unable to open the URL.

Upvotes: 1

Related Questions