I am trying to upload an image to the server.
I hava a form with a couple of inputs...
INSIDE this form, I have an Iframe which contains another form for the upload, this because I dont want the original form to submit().
The original form basically:
<form> ...... bla bla bla alot of inputs....<iframe src="pic_upload.html"></iframe></form>
Here is pic_upload.html:
</head>
<body><form name="pic_form" id="pic_form" action="bincgi/imageUpload.php" method="post" target="pic_target"><input name="pic_file" type="file" id="pic_file" size="35" onchange="this.form.submit();"></form><div id="pic_target" name="pic_target" style="width:80px; height:80px;"></div></body>
</html>
Here is imageUpload.php:
<?php
$destination_path = getcwd().DIRECTORY_SEPARATOR;
//echo $destination_path;
$result = 0;
$target_path = $destination_path . basename($_FILES['pic_file']['name']);
if(#move_uploaded_file($_FILES['pic_file']['tmp_name'], $target_path)) {
$result = 1;
}
?>
I get this error: Undefined index: pic_file on line 5 in imageUpload.php
ALSO, if I get this to work, is there a good way to display the uploaded image inside the target of the form?
Thanks alot!
PS: I will add javascript to the tags because maybe thats what I need here!
Don't forget about form attribute
enctype="multipart/form-data"
The form needs to be like this
<form enctype="multipart/form-data" action="__URL__" method="POST">
Check out this PHP.net documentation for more information.
You first need to test if $_FILES has an item with the key pic_file. So use the isset function to do so:
$destination_path = getcwd().DIRECTORY_SEPARATOR;
//echo $destination_path;
$result = 0;
if (isset($_FILES['pic_file'])) {
$target_path = $destination_path . basename($_FILES['pic_file']['name']);
if (#move_uploaded_file($_FILES['pic_file']['tmp_name'], $target_path)) {
$result = 1;
}
}
Related
I want to post multiple images by posting the url's but I don't know how to do this because I am new to PHP.
<?PHP
if(isset($_POST['post_image']))
{
$image_url=$_POST['image_path'];
$data = file_get_contents($image_url);
$new = '../images/myimage.jpg';
$upload =file_put_contents($new, $data);
if($upload) {
echo "<img src='../images/myimage.jpg'>";
}else{
echo "Please upload only image files";
}
}
?>
The problem with your script is, that you are not saving the file anywhere. So you have no access to it when trying to return it to the client.
In order to save an image using a POST you need to make sure you have set the following enctype inside your form.
<form action="upload.php" method="post" enctype="multipart/form-data">
Then you can use this function to save the img
move_uploaded_file($_FILES["myImg"], "/path/to/imgDir")
And later show it to the client using:
echo "<img src='/path/to/imgDir/myImg'>"
For more information about the topic i advice you to consult the following URL
https://www.w3schools.com/php/php_file_upload.asp
I'm working on a function to upload images to my website fileserver and at the same time would create a thumb preview and create an entry to my mysql database. So long the function to upload_image() is working, it uploads the image and creates a thumb perfectly.
The issue is, that when I click the submit button to upload the image selected, the PHP function do its job but will return a BLANK PAGE. Yes, I know, "another blank page of death question, go find all the other 53 posts related to this question and find a solution" right? Well, it's not that simple.
I have tried every single method in those questions and another bunch that I've found over this forsaken place called internet and nothing works for me, I always get the same Blank Page of death with no warning or error.
What have I tried would you ask? The following would just represent a relevant set of solutions that I recall:
Configuring PHP.INI's options for error: DONE. Even creating the log file for every single detailed error.
Overriding PHP.INI's options from the php file function with the settings: DONE. Also I have used a script from some answers that override error log protocol.
Place an exit('wtf') function from start to bottom to see if its an Syntax error or an error on a certain line: DONE. Every single line will print WTF on the god forsaken Blank Page.
Well, there are other solutions I have tried, be my guest and offer some answers and I would tell you if I have already tried it.
Lets get to it then. My HTML code that calls the php file is:
<form action="assets/php/image_uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile" id="fileToUpload">
</br>
</br>
<input type="text" name="title" value="Titulo" size="64">
<br>
<br>
<input type="submit" value="Upload Image" name="submit">
</form>
And my image_uploader.php code is:
<?php
function upload_image()
{
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
$name = "image_" . date('Y-m-d-H-i-s') . "_" . uniqid() . ".jpg";
$type= $_FILES["myfile"]["type"];
$size= $_FILES["myfile"]["size"];
$temp= $_FILES["myfile"]["tmp_name"];
$error= $_FILES["myfile"]["error"];
if ($error > 0)
{
die("Error uploading file! code $error.");
}
else
{
if($type=="image/png" || $size > 2000000)//condition for the file
{
die("Format not allowed or file size too big!");
}
else
{
if(move_uploaded_file($temp, $root . "/images/fulls/" . $name))
{
list($ancho, $alto) = getimagesize($root . "/images/fulls/" .$name);
$nuevo_alto = 212;
$nuevo_ancho = 212;
$dx = 0;
$dy = 0;
$sx = 0;
$sy = 0;
if($ancho == $alto)
{
}
else
{
if($ancho > $alto)
{
$nuevo_ancho = $ancho * (212/$alto);
}
else
{
$sy = $alto/2 - $nuevo_alto/2;
$alto = $ancho;
}
}
$thumb = imagecreatetruecolor($nuevo_ancho, $nuevo_alto);
$origen = imagecreatefromjpeg($root . "/images/fulls/" .$name);
imagecopyresampled($thumb, $origen, $dx, $dy, $sx, $sy, $nuevo_ancho, $nuevo_alto, $ancho, $alto);
imagejpeg($thumb, $root . "/images/thumbs/" .$name);
imagedestroy($thumb);
echo "The file ". basename( $_FILES["myfile"]["name"]). " has been uploaded.";
}
}
}
}
if(isset($_POST['submit']))
{
upload_image();
}
?>
try this:
$new_file = $root . "/images/fulls/" . $name;
copy($temp, $new_file);
if(!is_file($new_file)) {
die('cannot copy file');
}
also wrap main part with:
try{
}
catch(Exception $ex) {die('['.$ex->getLine().'] '.$ex->getMessage());}
Placed the code into the HTML file which was renamed later to have the extension .php and called the function in the form section as:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<input type="file" name="myfile" id="fileToUpload">
</br>
</br>
<input type="text" name="title" value="Titulo" size="64">
<br>
<br>
<input type="submit" value="Upload Image" name="submit">
</form>
And now it works as if it was magic, I do not know if htmlspecialchar() function has anything to do with it, but now the code works with no errors. Therefore I would post this as an answer but reminding you to not consider this as a solution to the BLANK PAGE death screen.
I am working on a page that allows the user to "upload" multiple files at once (they are stored locally in folders relative to their type).
My problem is that when I try to pass $upFile1 and $fileInfo1 to writeResults() to update $fileInfo1 with information about $upFile1, the echoed result is empty.
I did some research and this appears to be a scoping issue, but I'm not sure about the best way to get around this having just started learning PHP last month.
Any help would be greatly appreciated.
foo.html
<!DOCTYPE HTML>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form method="post" action="foo.php" enctype="multipart/form-data">
<p>
<b>File 1:</b><br>
<input type="file" name="upFile1"><br/>
<br/>
<b>File 2:</b><br>
<input type="file" name="upFile2"><br/>
<br/>
</p>
<p>
<input type="submit" name="submit" value="Upload Files">
</p>
</form>
</body>
</html>
foo.php
<?php
$upFile1 = $_FILES['upFile1'];
$upFile2 = $_FILES['upFile2'];
$fileInfo1 = "";
$fileInfo2 = "";
// Check if directories exist before uploading files to them
if (!file_exists('./files/images')) mkdir('./files/images', 0777, true);
if (!file_exists('./files/text')) mkdir('./files/text', 0777, true);
// Copies the file from the source input to its corresponding folder
function copyTo($source) {
if (($source['type'] == 'image/jpg') || ($source['type'] == 'image/png')) {
#copy($source['tmp_name'], "./files/images/".$source['name']);
}
if ($source['type'] == 'text/plain') {
#copy($source['tmp_name'], "./files/text/".$source['name']);
}
}
// Outputs file data for input file to destination
function writeResults($source, $destination) {
$destination .= "You sent: ";
$destination .= $source['name'];
$destination .= ", a ";
$destination .= $source['size'];
$destination .= "byte file with a mime type of ";
$destination .= $source['type'];
$destination .= ".";
// echoing $destination outputs the correct information, however
// $fileInfo1 and $fileInfo2 aren't affected at all.
}
// Check if both of the file uploads are not empty
if ((!empty($upFile1['name'])) || (!empty($upFile2['name']))) {
// Check if the first file upload is not empty
if (!empty($upFile1['name'])) {
copyTo($upFile1);
writeResults($upFile1, $fileInfo1);
}
// Check if the second file upload is not empty
if (!empty($upFile2['name'])) {
copyTo($upFile2);
writeResults($upFile2, $fileInfo2);
}
} else {
die("No input files specified.");
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<p>
<!-- This is empty -->
<?php echo "$fileInfo1"; ?>
</p>
<p>
<!-- This is empty -->
<?php echo "$fileInfo2"; ?>
</p>
</body>
</html>
you are passing the values of $fileInfo1 and $fileInfo2 but they are empty. After that there is no relation between the $destination value and the fileininfo values.
Change your function to return the $destination value.
Change your writeResults command to $fileInfo1 = writeResults($upFile1);
Use the & sign to pass variables by reference
function addOne(&$x) {
$x = $x+1;
}
$a = 1;
addOne($a);
echo $a;//2
function writeResults($source, &$destination) {
$destination .= "You sent: ";
$destination .= $source['name'];
$destination .= ", a ";
$destination .= $source['size'];
$destination .= "byte file with a mime type of ";
$destination .= $source['type'];
$destination .= ".";
// echoing $destination outputs the correct information, however
// $fileInfo1 and $fileInfo2 aren't affected at all.
}
Adding & in front of $destination will pass the variable by reference, instead of by value. So modifications made in the function will apply to the variable passed, instead of a copy inside the function.
For part of my web app, I'm attempting to upload 1 file under 2 different names. The first name is the original file name that the user specified. This is to be used for reference later on in my app. The second name is an altered name (simply adding in a counter variable). For uploading a single file using move_uploaded_file($name, $path), it works like a charm. When I attempted to call one move_uploaded_file(...) after the other, only the first function would upload a file. The second function would not return an error message.
After looking online, it seemed that this could be accomplished with a loop. I placed the names and the paths in an array, loop through it with a foreach loop but only the first file is uploaded.
Below are the files and their relevant portions as some are lengthy.
mainPage.php applies a header across all of my pages.
verifyFile.php is the file that does the uploading as well as verifying the bulk processing to check that the file is valid.
workPage.php
<?php
session_start();
require("mainPage.php");
?>
<link rel = "stylesheet" type = "text/css" href = "CSS/workpageCSS.css" />
<div id = "pageContainer">
<form enctype = "multipart/form-data" action = "verifyFile.php" method = "post">
<table border = "0" cellpadding = "2" cellspacing = "5">
<tr>
<td>
<label for = "fileName">Select file to upload</label>
</td>
<td>
<input type = "file" name = "file" id = "fileName" placeholder = "Choose file path" autofocus = "autofocus" required = "required" />
</td>
</tr>
<tr>
<td></td>
<td><input type = "submit" value = "Load file" /></td>
</tr>
</table>
</form>
</div>
Portion of verifyFile.php that uploads the file.
Attempt 1:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
$dupFile = appendFileName(basename($_FILES['file']['name']));
$origToUpload = basename($_FILES['file']['name']);
$targetPath = ("uploads/".$dupFile);
$origTargetPath = "uploads/".$origToUpload;
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
#echo("Successfully uploaded ".basename($_FILES['file']['name']));
} else {
echo("Failed 1<br />");
}
/*move_uploaded_file($_FILES['file']['tmp_name'], $origTargetPath); Does not upload but no errors are generated */
?>
Attempt 2
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1')
$filesToUpload = array($targetPath, $origTargetPath);
foreach($filesToUpload as $toUpload) {
if(move_uploaded_file($_FILES['file']['tmp_name'], $toUpload)) {
echo("worked!"); /* first time is successful and $targetPath is loaded onto my server */
} else {
echo("neg"); /* nothing is uploaded and returns neg */
}
}
?>
$origTargetPath and $targetPath are both valid since if I reverse them in my array, only the first file is correctly uploaded.
For additional information, I'm using Apache via XAMPP.
When you call move_upload_file, php will move the file from the file temporary location, to the one you specified. So you can't move the file twice.
What you are looking for is the copy function. In your case (first attempt):
copy($targetPath, $origTargetPath);
You could also consider symlink
I'm trying to implement a small update profile pic form.
<form method="post" action="<?php echo $filename;?>" name="change_picture_form" id="change_picture_form" enctype="multipart/form-data">
<input type="hidden" name="action" value="change_picture" />
<input type="file" name="new_user_picture">
<input type="submit" class="submitButton" value="Save Changes"/>
</form>
The target php file has the following code:
echo $_FILES['new_user_picture']['size']." ";
echo $_FILES['new_user_picture']['tmp_name']." ";
echo $_FILES['new_user_picture']['name']." ";
echo $_FILES['new_user_picture']['error']." ";
echo $_FILES['new_user_picture']['type']." ";
$picture_uploaded = $_FILES["new_user_picture"]["tmp_name"];
if( is_uploaded_file( $picture_uploaded ) ) {
$imagesize = getimagesize( $picture_uploaded );
switch( $imagesize[2] ) {
case IMAGETYPE_PNG:
$extension = '.png';
echo "<script>console.log('Reached here!!')</script>";
try {
$image_original = imagecreatefrompng( $picture_uploaded );
if (!$image_original)
echo '<script>console.log("not image original")</script>';
} catch(Exception $e) {
echo "<script>console.log('Error!!')</script>";
}
break;
case IMAGETYPE_JPEG: ....
...
}
}
Here, I have similar code for many image types. I tested this code by trying to uploading a png image. The first 5 echo statements display expected results - the size, error value of zero, the name, the type and the temp name.
I get "Reached here!!" on my console.
imagecreatefrompng, however, seems to crash silently. Try-catch somehow doesn't seem to catch the error.
Help? Thanks!
I haven't handled file uploads in PHP in forever, but is it possible that this line:
$picture_uploaded = $_FILES["new_user_picture"]["tmp_name"]
should be
$picture_uploaded = $_FILES["new_user_picture"] ?
The first line, as is, should be getting you the uploaded file's file name, whereas the second line (the edited line above) should be a reference to the file itself.
HTH.
EDIT: Well, seeing as how my answer is incorrect... does this help? http://www.php.net/manual/en/function.imagecreatefromstring.php
. There's a helper function in the user notes/comments that might simplify what you're doing