Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download image from URL using php code? [duplicate]

Tags:

url

php

image

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.

like image 723
Sarah Avatar asked Mar 21 '12 09:03

Sarah


People also ask

How to copy image from URL in PHP?

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.

How can I download image from PHP code?

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.

How to save image URL in database in PHP?

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"] .


1 Answers

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);
like image 88
Jon Avatar answered Sep 21 '22 14:09

Jon