How can I use php to download an image from URL (eg: https://www.google.com/images/srpr/logo3w.png) then save it? This is what I came up with so far, it gives me an error in 'file_put_contents' function.
<form method="post" action="">
<textarea name="text" cols="60" rows="10">
</textarea><br/>
<input type="submit" class="button" value="submit" />
</form>
<?php
$img = "no image";
if (isset($_POST['text']))
{
$content = file_get_contents($_POST['text']);
$img_path = '/images/';
file_put_contents($img_path, $content);
$img = "<img src=\"".$img_path."\"/>";
}
echo $img;
?>
It gives me the error:
[function.file-put-contents]: failed to open stream: No such file or directory in C:\wamp\www\img.php
The /images/
directory is located in the same directory of the php file and is writable.
Saving image from URL is very useful when you want to copy an image dynamically from the remote server and store in the local server. The file_get_contents() and file_put_contents() provides an easiest way to save remote image to local server using PHP. The image file can be saved straight to directory from the URL.
You can force images or other kind of files to download directly to the user's hard drive using the PHP readfile() function. Here we're going to create a simple image gallery that allows users to download the image files from the browser with a single mouse click. Let's create a file named "image-gallery.
php $folder = "upload/"; $file = basename( $_FILES['image']['name']); $full_path = $folder. $file; $tax= $full_path; if(in_array($filetype, $allowed)){ // Check whether file exists before uploading it if(file_exists("upload/" . $_FILES["photo"]["name"])){ echo $_FILES["photo"]["name"] .
You cannot save the image with your existing code because you do not provide a file name. You need to do something like:
$filenameIn = $_POST['text'];
$filenameOut = __DIR__ . '/images/' . basename($_POST['text']);
$contentOrFalseOnFailure = file_get_contents($filenameIn);
$byteCountOrFalseOnFailure = file_put_contents($filenameOut, $contentOrFalseOnFailure);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With