Hi,
Is it possible to get the file information such as file name and type of file of an uploaded file? If so what is the code to do this?
Thanks,
Nightwalker
Printable View
Hi,
Is it possible to get the file information such as file name and type of file of an uploaded file? If so what is the code to do this?
Thanks,
Nightwalker
If you Google file upload, you should find plenty. But here is some basic code for when the file was posted.
etc. W3Schools has a good tutorial http://www.w3schools.com/PHP/php_file_upload.aspPHP Code://type
$_FILES["file"]["type"]
//name
$_FILES["file"]["name"])
//size
$_FILES["file"]["size"]
the "type" stored in $_FILES is not exactly reliable, so you should try to parse the extension yourself rather than using it.
At the moment I manually type the file in to a text form and submit it the form but it does not work. Is a textbox the best way to do this?
What do you mean manually type the file? Could you post your code?
Typically this is done using a file upload control.
he's not using a file <input>. he's just using a text <input>.
however, you should be using a file <input> -- I don't even know if you could upload a file using just a regular text <input> -- so, like kfcSmitty, I've no real idea what you're trying to say. but, your form should look similar to this:
note that the bold, red parts are important.Code:<form enctype="multipart/form-data" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
when this form is submitted, you can access the file that has been uploaded with the $_FILES array -- $_FILES['userfile'] would be the thing we are specifically interested in here.
read more about $_FILES and how to handle file uploads here.
Sorry, what I was referring to was flash when I used the php code with flash I used the upload control but I don't where to find or use it with html.
Thanks! I'll see if it works for me.
Edit:
For some reason the upload code isn't working with my current configuration! This is the code I am using:
PHP Code:<?php
$pName= "";
$pPrice= "";
$pImagePath= "";
$pImageType= "";
// Database connection variables
$dbDatabase = "BazaarCeramics";
//connect to server or exit
if (!($conn = mysql_connect("localhost", "admin", "") )){
echo 'result=connection+failed';
exit;
}
//select database
if (mysql_select_db($dbDatabase, $conn)) {
}else {
die;
}
$query = "CREATE TABLE IF NOT EXISTS products
(productid varchar(20) not null primary key,
pPrice decimal (8,2), pImagePath varchar(100), pImageType varchar(100))";
if (mysql_query($query, $conn)) {
}else {
die;
}
if (isset($_POST['pName'], $_POST['pPrice'], $_POST['pImagePath'], $_POST['pImageType'])){
$pName= mysql_real_escape_string($_POST['pName']);
$pPrice= mysql_real_escape_string($_POST['pPrice']);
$pImagePath= mysql_real_escape_string($_POST['pImagePath']);
$pImageType= mysql_real_escape_string($_POST['pImageType']);
if (!(mysql_select_db($dbDatabase, $conn))){
echo '&result=db+selection+failed&';
exit;
}
if (!($result = mysql_query("SELECT * FROM products where productid= '$pName'"))){
echo '&result=query+failed&';
exit;
}
$num_results = mysql_num_rows($result);
if($num_results == 0) {//product does not exist so insert
$insert = "insert into products (productid, pPrice, pImagePath, pImageType)
values('$pName','$pPrice', '$pImagePath', '$pImageType')";
if (mysql_query($insert, $conn))
echo "&result=the+product+'$pName'+has+been+successfully+added&";
else
echo '&result=the+insert+was+not+successful&';
}else {//update product
$update = "update products set pPrice='$pPrice', pImagePath='$pImagePath', pImageType='$pImageType' where productid='$pName'";
if (mysql_query($update, $conn)){
}else{
echo '&result=the+update+was+not+successful&';
}
}
/*if (isset($_POST['pImagePath'])){
$MAXIMUM_FILESIZE = 1024 * 200; // 200KB
$MAXIMUM_FILE_COUNT = 10; // keep maximum 10 files on server
//echo exif_imagetype($_FILES['Filedata']);
if ($_FILES['pImagePath']['size'] <= $MAXIMUM_FILESIZE) {
move_uploaded_file($_FILES['pImagePath']['tmp_name'], "./temporary/".$_FILES['pImagePath']['name']);
//if ($type == 1 || $type == 2 || $type == 3) {
rename("./temporary/".$_FILES['pImagePath']['name'], "./images/".$_FILES['pImagePath']['name']);
}
}*/
}
?>
The code above works but if I don't comment out the upload code it stops working. I think the "type =file" code is causing the code to stop working because the pImageType field submits text to the database as well! Do I need to included a separate field to handle the upload to prevent problem from occurring?HTML Code:<form action="<?php $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data" name="products" target="_self">
<!--<input type="hidden" name="MAX_FILE_SIZE" value="30000" />-->
<label class="login-label" for="product">Product Name:</label><br /><input name="pName" type="text" id="pName"/>
<br /><label class="login-label" for="pPrice">Product Price:</label> <br />
<input name="pPrice" type="text" id="pPrice" />
<br />
<label class="login-label" for="pImagePath">Image Path:</label><br /><input name="pImagePath" type="type" id="pImagePath"/>
<br /><label class="login-label" for="pImageType">Image Type:</label> <br />
<input name="pImageType" type="text" id="pImageType" />
<br />
<input name="submit" type="submit" value="Submit" />
<input name="reset" type="reset" value="Reset" />
</form>
instead of bumping your posts, just stop editing them after like, 30 minutes have passed. post a reply instead so that people are aware you have another question.
in your form, you have pImagePath's type attribute set as "type," which is invalid. it should be "file."
and you don't need to comment out the MAX_FILE_SIZE field. it's there so that if a user uploads a file bigger than the size displayed there, the browser can reject the upload outright because it knows there would be an error. it's not 100% reliable though (because it's technically user input), but it helps. you should always also check filesizes in your upload script though.
Yeah, I know! The code that I posted above is the original code before I added the file upload code. I comment out the file upload code so you could tell the difference between the original code and the code that was added later. If I apply the file upload code and change the type from text to file the whole code stops working.
if it stops working completely, then there has to be some kind of error. turn on error reporting and post what that error is.
There are no errors! The code just stops working I will add a separate field for the file upload see if it makes a difference.
Edit:
I tried putting this code:
Above the code for the database plus using:PHP Code:$MAXIMUM_FILESIZE = 1024 * 200; // 200KB
$MAXIMUM_FILE_COUNT = 10; // keep maximum 10 files on server
//echo exif_imagetype($_FILES['Filedata']);
if ($_FILES['sendfile']['size'] <= $MAXIMUM_FILESIZE) {
move_uploaded_file($_FILES['sendfile']['tmp_name'], "./temporary/".$_FILES['sendfile']['name']);
//if ($type == 1 || $type == 2 || $type == 3) {
rename("./temporary/".$_FILES['sendfile']['name'], "./images/".$_FILES['sendfile']['name']);
}
However, the file sending doesn't work while the database input mysteriously works. I think part of the problem in the caching in Firefox.HTML Code:<form action="<?php $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data" name="products" target="_self">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<label class="login-label" for="product">Product Name:</label><br /><input name="pName" type="text" id="pName"/>
<br /><label class="login-label" for="pPrice">Product Price:</label> <br />
<input name="pPrice" type="text" id="pPrice" />
<br />
<label class="login-label" for="pImagePath">Image Path:</label><br /><input name="pImagePath" type="type" id="pImagePath"/>
<br /><label class="login-label" for="pImageType">Image Type:</label> <br />
<input name="pImageType" type="text" id="pImageType" />
<br /><label class="login-label" for="pImageType">Upload File:</label> <br />
<input name="sendfile" type="file" id="sendfile" />
<br />
<input name="submit" type="submit" value="Submit" />
<input name="reset" type="reset" value="Reset" />
</form>
If I change the path in the php script:
I receive the following errors:PHP Code:$MAXIMUM_FILESIZE = 1024 * 200; // 200KB
$MAXIMUM_FILE_COUNT = 10; // keep maximum 10 files on server
//echo exif_imagetype($_FILES['Filedata']);
if ($_FILES['sendfile']['size'] <= $MAXIMUM_FILESIZE) {
move_uploaded_file($_FILES['sendfile']['tmp_name'], "../temporary/".$_FILES['sendfile']['name']);
//if ($type == 1 || $type == 2 || $type == 3) {
rename("../temporary/".$_FILES['sendfile']['name'], "../images/".$_FILES['sendfile']['name']);
}
Quote:
Warning: move_uploaded_file(../temporary/image1.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in C:\wamp\www\Bazaar Ceramics\php\processProducts.php on line 48
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\wamp\tmp\php128.tmp' to '../temporary/image1.jpg' in C:\wamp\www\Bazaar Ceramics\php\processProducts.php on line 48
Warning: rename(../temporary/image1.jpg,../images/image1.jpg) [function.rename]: No such file or directory in C:\wamp\www\Bazaar Ceramics\php\processProducts.php on line 50
does the folder "temporary" exist in the parent directory from where ever you're running the script? if not, then that's the problem. if it does, try using an absolute path instead to see if it works.
The structure for the website is:
Bazaar Ceramics
-> php
-->images
-->temporary
processProducts.php (where the upload form/code is)
Edit:
If I use absolute paths I get:
Warning: move_uploaded_file(http://localhost/BazaarCeramics/php/...ary/image1.jpg) [function.move-uploaded-file]: failed to open stream: HTTP wrapper does not support writeable connections in C:\wamp\www\Bazaar Ceramics\php\processProducts.php on line 48
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\wamp\tmp\php124.tmp' to 'http://localhost/Bazaar Ceramics/php/temporary/image1.jpg' in C:\wamp\www\Bazaar Ceramics\php\processProducts.php on line 48
Warning: rename() [function.rename]: http wrapper does not support renaming in C:\wamp\www\Bazaar Ceramics\php\processProducts.php on line 50
Edit:
The code here uploads the file correctly!
PHP Code:/*
This is the PHP code for the Uploading PHP Files Using PHP Tutorial
You may use this code in your own projects as long as this
copyright is left in place. All code is provided AS-IS.
This code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
For the rest of the code visit http://www.WebCheatSheet.com
Copyright 2007 WebCheatSheet.com
*/
<?php
//Сheck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") &&
($_FILES["uploaded_file"]["size"] < 350000)) {
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'/upload/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
echo "It's done! The file has been saved as: ".$newname;
} else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
}
} else {
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
?>
Instead of using the code I posted above I modified my original code:
changed to:PHP Code:<?php
$MAXIMUM_FILESIZE = 1024 * 200; // 200KB
$MAXIMUM_FILE_COUNT = 10; // keep maximum 10 files on server
//echo exif_imagetype($_FILES['Filedata']);
if ($_FILES['Filedata']['size'] <= $MAXIMUM_FILESIZE) {
move_uploaded_file($_FILES['Filedata']['tmp_name'], "./temporary/".$_FILES['Filedata']['name']);
//if ($type == 1 || $type == 2 || $type == 3) {
rename("./temporary/".$_FILES['Filedata']['name'], "./images/".$_FILES['Filedata']['name']);
}
?>
For some strange reason the rename function doesn't work with html although, the original code works fine with flash.PHP Code:$MAXIMUM_FILESIZE = 1024 * 200; // 200KB
$MAXIMUM_FILE_COUNT = 10; // keep maximum 10 files on server
//echo exif_imagetype($_FILES['Filedata']);
if ($_FILES['sendfile']['size'] <= $MAXIMUM_FILESIZE) {
if (move_uploaded_file($_FILES['sendfile']['tmp_name'], "./temporary/".$_FILES['sendfile']['name'])){
echo "The file has been saved as: " .$_FILES['sendfile']['name'];
}else{
echo "Error! Could not upload file.";
}
}
move_uploaded_file() basically renames it anyway. having a call to rename() there is ... pretty much useless. you could just figure out the path and filename before you called move_uploaded_file(), if you needed to change it depending on $type.
anyway -- absolute path, when thinking about files on a system, is not an HTTP address. you can't use "localhost/whatever" as an absolute path! you must use the path to the folder on your system. eg: "c:/httpd/www/whatever/"
glad you got it working I guess.