I'm making a PHP upload form, but need to add some additional data to each image based on what the user types in. For example, they choose the file to upload and type in the name, height, width, and price of that file, then hit submit. That information needs to be stored with the photo or appended to the metadata.
Here's what I have for submitFile.php:
<form enctype="multipart/form-data" action="Upload.php"
method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="100000000" />
Select a File: <input name="uploaded_file" type="file" /><br/>
<input type="submit" value="Upload" />
And here's what I have for Upload.php:
<?php
$uploaddir = "uploads/images";
$uploadfile = $uploaddir.basename($_FILES['uploaded_file']['name']);
echo "<pre style= font-size:20px>";
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$uploadfile))
{
echo "<b>File has been successfully uploaded!</b>.\n";
}
else{
echo "<b>File upload failed!</b>.\n";
}
echo '<br/>Here is some more debugging info:'."<br/>";
echo "Name:".$_FILES["uploaded_file"]["name"]."<br/>";
echo "File Type:".$_FILES["uploaded_file"]["type"]."<br/>";
echo "File Size:".($_FILES["uploaded_file"]["size"]/1024)." Kb<br/>";
echo "Temp File:".$_FILES["uploaded_file"]["tmp_name"]."<br/>";
echo "</pre>";
?>
</form>
For JPEGs (and maybe TIFFs?), you should use something like this.
However, for PNGs, checkout this answer.
Related
HTML code is below
Upload Your pic only in jpg (Less 1 MB)
<input type="file" title="Upload Your pic in jpg (Less 1 MB)" accept="image/jpeg" required="" class="select-style" tabindex="1" name="file[]" multiple />
PHP code is below:
echo $_POST[$_FILES['file[]']];
echo $_POST[$_FILES["file"]["size"]];
Your fomr must contain
enctype="multipart/form-data"
Like :-
<form name="upload" id="upload" method="post" action="" enctype="multipart/form-data">
You can use $_FILES['file']['size'][0]; to get size of uploaded file
Hope this will help you
Thanks
Ok..
here is my HTML Page page name stack.html
<form name="upload" id="upload" method="post" action="stack.php" enctype="multipart/form-data">
<input type="file" title="Upload Your pic in jpg (Less 1 MB)" accept="image/jpeg" required="" class="select-style" tabindex="1" name="file[]" multiple />
<input type="submit" value="submit">
</form>
and here my PHP page page name stack.php
<?php
if(!empty($_FILES)){
echo "<pre>";
print_r($_FILES);
echo "</pre>";
exit;
}
?>
See if it gives any luck. Try it in php file..
foreach($_FILES as $file){
print_r($file['size']);
print_r($file['name']);
//if you want total size of all images
echo array_sum($file['size']);
//if you want individual name
for($i=0;$i<count($file['name']);$i++){
echo $file['name'][$i];
echo $file['size'][$i];
}
}
I have created a registration form which reads user data and send it to other php page which shows all the entered details. I was able to send its data to other php page using $_POST[] ,
but I am not able to send the images.
the below code is for the upload button which takes the image from user
<tr>
<td>Upload Image :</td>
<td><INPUT TYPE="file" NAME="image" required="required"></td>
</tr>
I have tried this using php but no luck
<? php
$img = $_POST['image'];
echo echo "<img src=$img>" ?>
So what could I do to send an image from one page to another using javascript or php?
The file selected by the user is sent over as data, so you have to pick up this data, save it somewhere, and then it is that "somewhere" that you would echo in an IMG tag.
W3Schools has an example of uploading and saving an image that you could adapt: http://www.w3schools.com/php/php_file_upload.asp
You have a problem in you uploading script.. To improve it:
HTML code:
<tr>
<td>Upload Image :</td>
<td>
<form action="" method="post" enctype="multipart/form-data" name="uploader" id="uploader">
<input type="file" name="image" required="required">
<input name="upl" type="submit" id="upl" value="Upload">
</form></td>
</tr>
PHP code:
if( $_POST['upl'] == 'Upload') {
$img = 'images/'.$_FILES['image']['name'];
if(#copy($_FILES['image']['tmp_name'],$img)) echo '<img src="'.$img.'">';
else echo 'ERROR!';
}
upload the file, move it from temp to a folder, display it from that folder
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Image:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
and
<? php
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "<img src= 'upload/" . $_FILES["file"]["name"] . "'>";
?>
done
Hey guys what I'm trying to do is build an upload page for various games across different game consoles. I will admit I am new to php and I'm just trying to figure things out.I have ran into a strange problem via uploading images. I do not understand why this fails because one attribute in the array works perfectly fine. It uploads the results from the form with no problem. The other three attributes all fail. Using the exact same function and methods.
//// this the form block for uploading ////
<form action="process.php" method="post" enctype="multipart/form-data">
<!--xbox -->
<div class="form">
<h3>Xbox 360</h3>
<!-- title of post/ game name -->
<p><label for="xboxtitle"> Title of Game </lable></p>
<input type="text" name="xboxtitle" size=20 /><br />
<!-- image uploader -->
<p><label for="xbox-image">Game Image:</label><sup>*png, png, bmp, jpeg and jpg only!</sup></p>
<input type="file" name="xboximage" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<!-- large text box -->
<p><label for="xboxtext">Displayed text:</label><sup> * limit of 250 characters allowed.</sup></p>
<textarea cols=40 rows=10 name="xboxtext"></textarea>
<!-- price box -->
<p><label for="xboxprice">Price of item</label></p>
<input type="text" name="xboxprice" size=8 /><br />
</div>
<!-- p3 -->
<div class="form">
<h3>Playstation 3</h3>
<!-- title of post/ game name -->
<p><label for="ps3title"> Title of Game </lable></p>
<input type="text" name="ps3title" size=20 /><br />
<!-- image uploader -->
<p><label for="ps3image">Game Image:</label><sup>*png, png, bmp, jpeg and jpg only!</sup></p>
<input type="file" name="ps3image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<!-- large text box -->
<p><label for="ps3text">Displayed text:</label><sup> * limit of 250 characters allowed.</sup></p>
<textarea cols=40 rows=10 name="ps3text"></textarea>
<!-- price box -->
<p><label for="ps3price">Price of item</label></p>
<input type="text" name="ps3price" size=8 /><br />
</div>
<!-- wii -->
<div class="form">
<h3>Wii</h3>
<!-- title of post/ game name -->
<p><label for="wiititle"> Title of Game </lable></p>
<input type="text" name="wiititle" size=20 /><br />
<!-- image uploader -->
<p><label for="wiiimage">Game Image:</label><sup>*png, png, bmp, jpeg and jpg only!</sup></p>
<input type="file" name="wiiimage" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<!-- large text box -->
<p><label for="wiitext">Displayed text:</label><sup> * limit of 250 characters allowed.</sup></p>
<textarea cols=40 rows=10 name="wiitext"></textarea>
<!-- price box -->
<p><label for="wiiprice">Price of item</label></p>
<input type="text" name="wiiprice" size=8 /><br />
</div>
<!-- PC -->
<div class="form">
<h3>PC</h3>
<!-- title of post/ game name -->
<p><label for="pctitle"> Title of Game </lable></p>
<input type="text" name="pctitle" size=20 /><br />
<!-- image uploader -->
<p><label for="pcimage">Game Image:</label><sup>*png, png, bmp, jpeg and jpg only!</sup></p>
<input type="file" name="pcimage" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<!-- large text box -->
<p><label for="pctext">Displayed text:</label><sup> * limit of 250 characters allowed.</sup></p>
<textarea cols=40 rows=10 name="pctext"></textarea>
<!-- price box -->
<p><label for="pcprice">Price of item</label></p>
<input type="text" name="pcprice" size=8 /><br />
</div>
<p><input type="submit" id="submit" class="bigbutton" value="Upload" /></p>
</form>
///// this is the process.php page ///
<?php
include ("includes/logincheck.php");
?>
<?php
// Call our connection file
require("dbacess.php");
///////////////////////////////////////////////////////////////////////////////////////////////////
// create validating image types function
function is_valid_type($file)
{
// This is an array that holds all the valid image MIME types
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
// declare possible forms in array.
$arr = array("xbox","ps3", "wii", "pc");
// push the array through the following code
//while giving $value the proper form prefix
foreach ($arr as &$value) {
//$value Variables
$title = $_POST[$value . 'title'];
$text = $_POST[$value . 'text'];
$price = $_POST[$value . 'price'];
$image = $_FILES[$value .'image'];
//validate info or redirect
if ($title && $text && $price && $image['name'] != "" )
{
// Sanitize our inputs
$title = mysql_real_escape_string($title);
$text = mysql_real_escape_string($text);
$price = mysql_real_escape_string($price);
$image['name'] = mysql_real_escape_string($image['name']);
// Build our target path full string. This is where the file will be moved to
// Build Partial Target Path
$TARGET_PATH = "../../images/newreleasesuploads/";
$TARGET_PATH .= "$value/";
//creates upload path
$UPLOAD_PATH = $TARGET_PATH;
$UPLOAD_PATH .= $image['name'];
// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, png, or bmp in {$value} field. Please select a correct file type.";
header("Location: welcome.php");
exit;
}
// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($UPLOAD_PATH))
{
$_SESSION['error'] = "A file with that name already exists when trying to update $value page. Please rename file something different or remove the existing files";
header("Location: welcome.php");
exit;
}
//create current date variable
$date = date("Y-m-d");
$date .= date(" h:i:s");
// count # of entries
$entry = mysql_query("SELECT * FROM new{$value}");
$NUMBER_OF_ROWS = mysql_num_rows($entry);
// Count # of entries delete if index is 10 or more.
if($NUMBER_OF_ROWS >=10){
// find oldest entry by date
$sqldate ="SELECT * FROM new{$value}
WHERE date = (SELECT MIN(date) FROM new{$value})";
$oldestdate = mysql_query($sqldate) or die ("could not access DB to find oldest entry" . mysql_error());
//grabs data from that row
$row = mysql_fetch_assoc($oldestdate);
//adds filename to delete path
$DELETE =$TARGET_PATH;
$DELETE .=$row['filename'];
// parse row date to variable
$deletedate = $row['id'];
//terminates entry
$deletedate = "DELETE FROM new{$value}
WHERE id = $deletedate";
$deleteoldest = mysql_query($deletedate) or die ("could not delete oldest date entry" . mysql_error());
//terminates file
unlink($DELETE);
$_SESSION['message'] .= "The oldest entry was deleted to make room for the new upload.";
}
// attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($image['tmp_name'], $UPLOAD_PATH))
{
// Placing a reference of the images location into the database, *not* putting the image into the database.
$sql = "insert into new{$value} (date, title, description, price, filename) values ('$date', '$title', '$text', '$price', '" . $image['name'] . "' )";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
//message to let user know image was uploaded correctly
$_SESSION['message'] .= "The {$value} entry was uploaded correctly";
}
else {
// A common cause of file moving failures is because of bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writable also make sure directory is not READ ONLY
$_SESSION['error'] = "Could not upload file. Check read/write permissions on the directory";
header("Location: welcome.php");
exit;
}
}
// declare variable for error display
$i = 0;
// validate to make sure all are filled
if($title !=""){$i++;}
if($text !=""){$i++;}
if($price !=""){$i++;}
if($image['name'] !=""){$i++;}
elseif ($i!=0) {
//validate that more then one but not all box
$_SESSION['error'] = "Only $i of the fields for $value were filled. Please refill all fields or no fields for $value";
header("Location: welcome.php");
exit;
}
}
// return to upload page
header("Location: welcome.php");
exit;
?>
Whats happening is the xbox value in the array pushes through however ps3 wii and pc all send back the error "You must upload a jpeg, gif, png, or bmp in ps3 field. Please select a correct file type." which it should if the image is a wrong file type. However I can upload the same image simultaneously or singularly and the xbox will pass every time while the others will fail. Could anyone tell me why this is? and possibly how to fix it?
Thanks for your time in advance
Fixed my own problem after doing some more research I had two options. The problem was that I was trying to upload multiple files without having the configuration on Apache.
option 1) modify the form like so (this allows only one upload at a time)
<div class="form">
<form action="newreleasesprocess.php" method="post" enctype="multipart/form-data">
<h3>Playstation 3</h3>
<!-- title of post/ game name -->
<p><label for="ps3title"> Title of Game </lable></p>
<input type="text" name="ps3title" size=20 /><br />
<!-- image uploader -->
<p><label for="ps3image">Game Image:</label><sup>*png, png, bmp, jpeg and jpg only!</sup></p>
<input type="file" name="ps3image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<!-- large text box -->
<p><label for="ps3text">Displayed text:</label><sup> * limit of 250 characters allowed.</sup></p>
<textarea cols=40 rows=10 name="ps3text"></textarea>
<!-- price box -->
<p><label for="ps3price">Price of item</label></p>
<input type="text" name="ps3price" size=8 /><br />
<p><input type="submit" id="submit" value="Upload" /></p>
</form>
</div>
However this gets rid of multiple uploads at once and for what I am using it for this is not fine.
option 2) reconfigure the max_file_uploads in the configuration .ini from 1 to 4( or what ever you want)
I went with option 2.
hope this solution helps anyone else who encounters the same issue
Thanks again to anyone that looked into my problem
I'm currently uploading a single file successfully with the following form:
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
And with the following script:
<?php
error_reporting(E_ALL);
if (($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "C:/inetpub/wwwroot/PHP_Ramp/upload/" . $_FILES["file"]["name"]);
if ($moved) {
echo "Move: Success <br/>";
}
else {
echo "Move Failed <br/>";
}
echo "Stored in: " . "C:/inetpub/wwwroot/PHP_Ramp/upload/" . $_FILES["file"]["name"];
}
}
else
{
echo "Invalid file";
}
?>
I'm now trying to allow the user to select three different files from the form. I've found a few guides that show how to do something similar, but I can't quite get it working.
I've modified the form as follows (to include three inputs):
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="file" name="file" id="file" />
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
But I'm not sure how to modify the php to handle all three files. I know I need to iterate through _FILES but everything I've tried isn't working. Any pointers would be appreciated.
Each file element must have a unique name, or use PHP's array shorthand:
<input type="file" name="file1" />
<input type="file" name="file2" />
or
<input type="file" name="file[]" />
<input type="file" name="file[]" />
Remember - the name attribute defines how you'll identify that field on the server, and if you use the same name multiple times, PHP will overwrite previous copies with the latest one as it parses through the submitted data. The array notation ([]) tells PHP that you INTENDED to have multiple fields with the same name, and that each copy it finds should be added to an array, not overwritten.
For the unique name version, you'd handle each as you are right now with the single file.
For the array version, PHP has a design stupidity that requires slightly different handling. You end up with a $_FILES array that looks like
$_FILES = array(
'fieldname' => array(
'name' => array(
0 => 'first file',
1 => 'second file',
etc...
)
)
)
You need to change
<input name="file" />
to
<input name="file[]" />
To make them into an array.
Then in your script, you reference them as:
$_FILES['file']['name'][0]; // first file
$_FILES['file']['name'][1]; // second file
Note you can replace name with any of the other file properties that you usually would use on a single file (e.g. size, type etc).
Alternatively, you can give them all different names:
<input name="firstfile" />
<input name="secondfile" />
Then in your script:
$_FILES['firstfile']; // first file
$_FILES['secondfile']; // second file
You can select multiple file in single input like this..
<input type="file" name="pic[]" id="pic" accept="image/*" multiple="multiple"/>
This input box can accept multiple files by pressing control key. Now you can access them in php like this
$_FILES['file']['name'][0]; // first file
$_FILES['file']['name'][1]; // second file
KISS Code with some explanations:
There is fully functional simple code below to get you started. You can add error checking, max size stuff etc after you get something simple working.
The $_FILES array is a 3 dimensional array built into PHP, and that's where all the uploaded file info is stored.
There will only be ONE element for each 'name=' part of the HTML INPUT tag.
So if your INPUT tag looks like this:
<INPUT name="InpFile[]" type="file" />
The $_FILES array will have one top array element named 'InpFile'.
Also notice the [] after the InpFile.....that tells PHP that each time you use an input tag with that same 'name' it will add it to that same $_FILES array top element.
Within that one element there are 5 other array elements with the names: 'name', 'type', 'tmp_name', 'error', and 'size'.
And each one of those array elements will contain the data for each file that is uploaded.
Your first uploaded file name will be in $_FILES ['InpFile']['name']['0']
And the other info about your first uploaded file will also be in the array the same way, for example the size of the first file will be in $_FILES ['InpFile']['size']['0']
Each subsequent file name will be in $_FILES ['InpFile']['name'][1], $_FILES ['InpFile']['name'][2]....etc
After your upload, each file will have a random temporary name in the $_FILES ['InpFile']['tmp_name'][0...n] element, which is the name that it uses to first upload the files to a temporary area.
SO, after you upload, you have to move the files from the temporary area to where you want them.
That is done with this statement:
move_uploaded_file($_FILES['InpFile']['tmp_name'][$Key],
$_FILES['InpFile']['name'][$Key] )
or die("Move from Temp area failed");
In the foreach statement below, $Key and $Name are only there so that $Key will get assigned increasing numbers for each iteration...i.e. 0, 1, 2.....etc, and that you can then use $Key to reference the name, tmp_name, etc of each file in the array.
This code lets you do it all on one page, since the form actually calls itself (action="") to post. So the first time the page is loaded, you would get an error in the php code because $_FILES hasn't been set yet......so all the code is in an If statement: If ($_FILES).
After you submit the form, it will do it's thing and then echo a status for each file after it's been moved to your area.
Also, this code will upload the file to the same directory the page is in...you can change all that using info from other posts on SO.
<FORM action="" method="post" enctype="multipart/form-data">
<P align="center"><B>Choose Files</B><BR>
<BR>
File One:
<INPUT name="InpFile[]" type="file" />
<BR>
<BR>
File Two:
<INPUT name="InpFile[]" type="file" />
<BR>
</P>
<P align="center"><BR>
<INPUT type="submit" name="submit" value="UpLoad">
</P>
</FORM>
<H3 align="center"> </H3>
<H3 align="center">Status:</H3>
<P align="center"> </P>
<P align="center">
Put this PHP Code right here on the same page:
<?php
If ($_FILES) {
foreach ($_FILES ['InpFile']['name'] as $Key => $Name) {
move_uploaded_file(
$_FILES['InpFile']['tmp_name'][$Key],
$_FILES['InpFile']['name'][$Key]
) or die("Move from Temp area Failed");
$EFileName = $_FILES['InpFile']['name'][$Key];
echo "<P>$EFileName: Uploaded";
}
}
?>
You need to change the value of the name attribute in the HTML side to file[] and then in PHP just iterate through $_FILES['files'] and process each element as you normally would with a single file.
Post Updated: After commentors advice.
Index.php
<?php
$id = uniqid("");
?>
</head>
<body>
<form method="post" action="frame.php" target="upload_iframe" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo $id; ?>"/>
<br />
<input type="submit" name="submit" value="Submit" />
</form>
<iframe name="upload_iframe" style="width: 400px; height: 100px;">
</iframe>
frame.php
<?php
if(isset($_POST['progress_key'])) {
echo "hey1";
$status = apc_fetch('upload_'.$_POST['progress_key']);
echo $status['current']/$status['total']*100;
}
echo "hey2";
?>
Still doesnt work :(, I dont even get POST form data in frame. Where am i going so wrong?
Regards.
Whenever you use the APC file upload mechanism, you need to add an additional parameter to your form that identifies the file that's being uploaded, and is the key for your apc_fetch.
<?php $id = uniqid(time()); ?>
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="myUniProgressKey" value="<?php echo $id; ?>"/>
As the file is uploaded the value in the key upload . $id will contain the info you need to display the progress bar. Easiest way to get to is to ajax poll the server, using the apc_fetch call you have. This dictates that your upload page needs to not refresh the current page the user is on. I've used an iframe in the past that kicks off an interval to poll the server. Once the upload is complete, you're able to show a nice complete message in the same iframe.