Thomas Hutton
Thomas Hutton

Reputation: 803

Saving Images to Disk from a URL with PHP

I'm trying to save images from a URL to my computer with a PHP file. It works when the card I search for has only one name; however, when I try to do it for a card with multiple names I get:

Warning: file_get_contents(http://gatherer.wizards.com/Handlers/Image.ashx?name=black lotus&type=card&.jpg): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\xampp\htdocs\MTGFetcher\results.php on line 6

Here's my code for my cardfetch.php;

<form action="results.php" method="post">

Name of card: <br>

<input type="text" name="cardname" value="cardresult">

<input type="submit" value="Submit">

</form>

And for my results.php:

<?php

$results = $_POST['cardname'];
$url = "http://gatherer.wizards.com/Handlers/Image.ashx?name=" . $results . "&type=card&.jpg";
$img = "Pictures/$results.jpg";
file_put_contents($img, file_get_contents($url));
?>

<img src="<?php echo $url ?>">

Why is it not working with multiple words?

Upvotes: 0

Views: 92

Answers (1)

aynber
aynber

Reputation: 23001

The space may be throwing things off. Use http_build_query and it will convert any bad characters:

$query_array = array('name'=>$_POST['cardname'], 'type'=> 'card', '.jpg');
$url = "http://gatherer.wizards.com/Handlers/Image.ashx?".http_build_query($query_array);

You may have to play with the array, since the "&type=card&.jpg"; is a bit odd.

Upvotes: 1

Related Questions