Download image from URL using php code? [duplicate] - php

This question already has answers here:
Saving image from PHP URL
(11 answers)
Closed 6 years ago.
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.

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);

file_put_contents() requires first parameter to be file name not the path.

What is your error ? But you have the right way to do what you want to do.
Just take care in your code, I can see file_put_contents($img_path, but $img_path is a path to a folder.
You need to write something like :
example
$img_path="home/downloads/my_images";
file_put_contents($img_path."/flower.jpg");

file_put_contents($img_path, $content);
To what are you putting to?? i think you have made a mistake with get and put. or missed to specify the full path including the file name and extension

I added one condition to accepted answer to check the image type as follows,
if (exif_imagetype($_POST['text']) == IMAGETYPE_PNG) {
$filename = './images/'.basename($_POST['text']);
file_put_contents($filename, $content);
}
from above example I show how to check png images before download the files and for more content types you can find here .

Related

Trying to upload image to a folder and save its location in DB error

I keep getting this error and I do not know why.
Upload form
<?php
require_once 'processor/dbconfig.php';
if(isset($_POST['submit']))
{
if($_FILES['image']['name'])
{
$save_path="newimages"; // Folder where you wanna move the file.
$myname = strtolower($_FILES['image']['tmp_name']); //You are renaming the file here
move_uploaded_file($_FILES['image']['tmp_name'], $save_path.$myname); // Move the uploaded file to the desired folder
}
$hl = $_POST['headline'];
$fd = $_POST['feed'];
$st = $_POST['story'];
$tp = $_POST['type'];
if($user->send($h1,$fd,$st,$tp,$save_path,$myname))
{
echo 'Success';
$user->redirect("input.php");
}
}
?>
<form enctype="multipart/form-data" method="post">
<input type="text" name="headline">
<input type="text" name="feed">
<textarea cols="15" id="comment" name="story" placeholder="Message" rows="10"></textarea>
<input type="text" name="type">
<input type="file" name="image">
<input type="submit" name="submit">
</form>
Here is my SEND function
public function send($hl,$fd,$st,$tp,$save_path,$myname)
{
try
{
$stmt = $this->db->prepare("
INSERT INTO news(headline,feed,story,type,folder,file)
VALUES(:headline, :feed, :story, :type, :foler, :file);
");
$stmt->bindparam(":headline", $hl);
$stmt->bindparam(":feed", $fd);
$stmt->bindparam(":story", $st);
$stmt->bindparam(":type", $tp);
$stmt->bindparam(":folder", $save_path);
$stmt->bindparam(":file", $myname);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
And finally, Here is my Error.
Warning: move_uploaded_file(newimages//var/tmp/phpyctf0k) [function.move-uploaded-file]: failed to open stream: No such file or directory in /nfs/c11/h05/mnt//domains/concept/html/input.php on line 12
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/var/tmp/phpyctf0K' to 'newimages//var/tmp/phpyctf0k' in /nfs/c11/h05/mnt//domains/concept/html/input.php on line 12
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Yes I did create a new folder named newimages as well.
so you're saying you've made a folder in the same relative directory of the current running php script called newimages, in which you want to upload this file. just to be absolutely clear, this is not an absolute path, and that's OK.
$save_path="newimages";
I think it needs a trailing slash, as it appears in your output, but not in your example code.
$save_path="newimages/";
on this line, you are making the whole path and filename to lowercase of the temporary file in your absolute path /var/tmp/phpyctf0k
$myname = strtolower($_FILES['image']['tmp_name']); //You are renaming the file here
so on this line, you are appending the local relative path newimages with the whole absolute path of the temp file /var/tmp/phpyctf0k, so this now indicates to the PHP interpreter that you intend to move a file to a directory that doesn't exist newimages/var/tmp/phpyctf0k
move_uploaded_file($_FILES['image']['tmp_name'], $save_path.$myname); // Move the uploaded file to the desired folder
in order to fix it, you could use something like basename
move_uploaded_file($_FILES['image']['tmp_name'], $save_path.basename($myname)); // Move the uploaded file to the desired folder
or perhaps $_FILES['image']['name'] as #Sean commented.
move_uploaded_file($_FILES['image']['tmp_name'], $save_path.strtolower($_FILES['image']['name'])); // Move the uploaded file to the desired folder

Display the uploaded image after uploading on the web page

I am trying to display the image that i have uploaded and moved to the desired location. Here is the code below.
if(isset($_FILES['image']))
// image upload from upload.html
{
session_start();
$_SESSION['str'];
$_SESSION['img'];
$image = basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES['image']['tmp_name'], $_SESSION['str'].'_5'.$_SESSION['img']);
//I am trying to display the uploaded pic
echo '<img src= "$image"/>';
}
The image is stored at the location $_SESSION['str']. How can i display this uploaded image.
You're using the wrong path to show the image. You're using the orginal name of the image $_FILES["image"]["name"] that was uploaded and then you use the move_uploaded_file function to move and save the file as $_SESSION['str'].'_5'.$_SESSION['img'] so that doesn't match (can't see how your session variables are created).
Also, is the location where you save the uploaded file to accessable by the client side? Move the file in the public area of your web application.
Update
I now understand from your comment that you want to save the file in a private location and then show that file in a <img> element in some HTML template.
I changed the example code to embed the uploaded image into the HTML with base64.
You can use this function for creating the embed code. I took it from the answer from this question How to embed images...
function dataUri($file, $mime)
{
$contents = file_get_contents($file);
$base64 = base64_encode($contents);
return 'data:' . $mime . ';base64,' . $base64;
}
So then you can use it like:
session_start();
// absolute path including the path to the public folder
$image_dest_path = './public/img/' . $_SESSION['str'] . '_5' . $_SESSION['img'];
// move file to server location
move_uploaded_file($_FILES['image']['tmp_name'], $image_dest_path);
// imbed the image into the HTML.
echo '<img src= "' . dataUri($image_dest_path, 'image/jpg') . '"/>';
First of you say the location is stored in $_SESSION['str'] but you try to place an image with the value of basename($_FILES["image"][""name]).
Second; you should be using session_start() at the top of your page.
Third; in order to use a variable in a string, you need to use double quotes (") in stead of single quotes ('). Like so:
echo "<img src='$_SESSION['str']">;
But I'd use this:
echo '<img src="'. $_SESSION['str'] .'" >';
Also, are you sure you're not getting any errors? If you don't see any try placing this at the top of your file:
error_reporting(E_ALL);
ini_set('display_errors', 1);
iam assuming that $_SESSION['str'] session variable is the path till the folder where the image is stored
Use the below code, give the complete url of the image:
echo "<img src = '".$_SESSION['str'].DIRECTORY_SEPARATOR.$image."'"." />";
how to call the node js method in angular js?

Uploading File from Custom Form HTML

I'm trying to upload a file from my custom HTML form to a PHP script. Here is the code that I have in my HTML.
<form action="test.php" method="post" enctype="multipart/form-data">
<input id="txt" class="button" type = "text" value = "Choose File" onclick ="javascript:document.getElementById('file').click();">
<input id = "file" type="file" style='visibility: hidden;' name="img" onchange="ChangeText(this, 'txt');"/>
<input type="submit">
</form>
Here is the test.php file:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$target = "i/";
if (move_uploaded_file($_FILES['img']['tmp_name'], $target)) {
echo "The file " . basename($_FILES['img']['name']) . "has been uploaded";
}
Here's the error on the page:
Warning: move_uploaded_file(): The second argument to copy() function cannot be a directory in /var/www/BLOCKED/test.php on line 7
Warning: move_uploaded_file(): Unable to move '/tmp/phpNxxB72' to 'i/' in /var/www/BLOCKED/test.php on line 7.
Yes it's permissions of the directory are 777.
the 2nd argument of move_uploaded_file should be a file name (with path) not a directory
$target = "i/".basename($_FILES['img']['name']);
The error is correct. The 2nd parameter to move_uploaded_file() is not a directory, it should be a file. You just need to append the file's name to $target in the 2nd parameter. For example:
if (move_uploaded_file($_FILES['img']['tmp_name'], $target.$_FILES['img']['name'])) {
echo "The file " . basename($_FILES['img']['name']) . "has been uploaded";
}
move_uploaded_file function should be like this:
move_uploaded_file($_FILES['img']['tmp_name'], $target. $_FILES["img"]["name"])
add file name at end, as $target is a directory/folder only.
Tantibus, as you can read here:
http://php.net/manual/en/function.move-uploaded-file.php
You must specify the file name to your target file.
$target = "i/".basename($_FILES['img']['name']);
you probably missed this.

PHP move_uploaded_file() failing on host

I have a script that uploads some files through php's move_uploaded_file().
Tested on my localhost it works fine. The problem arises when trying to do the same thing on a host. I already red all the topics in that matter here - but none of them solved my problem.
CODE:
<?php
$folder = 'img';
if (isset($_FILES['test'])) {
if (is_writable($folder))
echo 'Writable';
else
echo 'IMG is not writable';
$tmp_name = $_FILES['test']['tmp_name'];
$name = $_FILES['test']['name'];
if (move_uploaded_file($tmp_name, $folder . '/' . $name)) {
echo 'File was uploaded';
}
else {
echo 'File was not uploaded';
}
}
else {
echo 'No file - no operation';
}
?>
<html>
<body>
<form action="" enctype="multipart/form-data" method="POST">
<input type="file" name="test" />
<input type="submit" value="Test" />
</form>
</body>
</html>
MESSAGE is as follows:
Writable
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\php9E75.tmp' to 'img/20130113_114901.jpg' in F:\hshome\ctc-ultralife\ultralife.com\new\admin\index_files\function\test2.php on line 11
File was not uploaded
Folder seems writable. Even if the file is not uploaded, it is created with the specified name in the folder (even if it is an empty file).
I do not know the absolute path of the server - it is not mine.
Your help will be much appreciated.
Thanks in advance.
Warning: complete stab in the dark. I don't know if this is the case, as I don't work on Windows servers.
It may be that the / needs to be a \. I don't think Windows handles the slash being the other way. That would explain why it can find your directory, but not the file within it.
I think you have to give an absolute path to the move_uploaded_file function.
EDIT:
If you don't know the absolute path, you can use the __DIR__ constant to make up an absolute path.
Assuming you've the img folder in the function folder, you can write something like this:
$fullPath = __DIR__ . '/img/' . $name;
if (move_uploaded_file($tmp_name, $fullPath)) {
echo 'File was uploaded';
} else { // ... }
In order to understand the real problem, you've to look into the error log.

Getting complete PATH of uploaded file - PHP

I have a form(HTML, PHP) that lets the end user upload a file to update the database(MySQL) with the records in the uploaded file(specifically .csv). However, in the phpscript, I can only get the filename and not the complete path of the file specificed. fopen() fails due to this reason. Can anyone please let me know how I can work on finding the complete path?
HTML Code:
<html>
<head>
</head>
<body>
<form method="POST" action="upload.php" enctype="multipart/form-data">
<p>File to upload : <input type ="file" name = "UploadFileName"></p><br />
<input type = "submit" name = "Submit" value = "Press THIS to upload">
</form>
</body>
</html>
PHP Script:
<?php
.....
......
$handle = fopen($_FILES["UploadFileName"]["name"], "r"); # fopen(test.csv) [function.fopen]: failed to open stream: No such file or directory
?>
name refers to the filename on the client-side. To get the filename (including the full path) on the server-side, you need to use tmp_name:
$handle = fopen($_FILES["UploadFileName"]["tmp_name"], 'r');
$target='uploads/'.basename($_FILES['UploadFileName']['name']);
if(move_uploaded_file($_FILES['UploadFileName']['tmp_name'],$target)) {
//Insert into your db
$fp = fopen($target, "r");
}
I wrote like this:
$filePath = realpath($_FILES["file"]["tmp_name"]);
This gave me the full path to the uploaded file in PHP. If you find 0 bytes problem in file download, just modify this content-lenght line like this
header("Content-Length: ".filesize($filePath));
Where $filePath should be absolute path to file not just file handle.
Use the following code,
$handle = fopen($_FILES["UploadFileName"]["tmp_name"], 'r');
I use like this...
<?php
$NameOriginal = $_FILES["UploadFileName"]['name'];
$Typo_Image = $_FILES["UploadFileName"]['type'];
$name_Temp = $_FILES["UploadFileName"]['tmp_name'];
?>

Categories