I have the following code to upload a file to the server. For some weird reason, it does not work in IE and Mozilla Firefox but works perfect in Chrome. What is the problem?
PHP:
// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
$POST_MAX_SIZE = ini_get('post_max_size');
$unit = strtoupper(substr($POST_MAX_SIZE, -1));
$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE)
HandleError('File exceeded maximum allowed size. Your file size <b>MUST NOT</b> be more than 100kb.');
// Settings
$save_path = 'uploads/'; //getcwd() . '/uploads/';The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
$upload_name = 'userfile'; // change this accordingly
$max_file_size_in_bytes = 102400; // 100k in bytes
$whitelist = array('jpg', 'png', 'gif', 'jpeg'); // Allowed file extensions
$blacklist = array('php', 'php3', 'php4', 'phtml','exe','txt','scr','cgi','pl','shtml'); // Restrict file extensions
$valid_chars_regex = 'A-Za-z0-9_-\s ';// Characters allowed in the file name (in a Regular Expression format)
// Other variables
$MAX_FILENAME_LENGTH = 260;
$file_name = $_FILES[$upload_name]['name'];
//echo "testing-".$file_name."<br>";
//$file_name = strtolower($file_name);
////////$file_extension = end(explode('.', $file_name));
$parts = explode('.', $file_name);
$file_extension = end($parts);
$uploadErrors = array(
0=>'There is no error, the file uploaded with success',
1=>'The uploaded file exceeds the upload max filesize allowed.',
2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3=>'The uploaded file was only partially uploaded',
4=>'No file was uploaded',
6=>'Missing a temporary folder'
);
// Validate the upload
if (!isset($_FILES[$upload_name]))
**HandleError('No upload found for ' . $upload_name);**//THROWS UP ERROR HERE in IE and Firefox
else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)
HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
else if (!isset($_FILES[$upload_name]['tmp_name']) || !#is_uploaded_file($_FILES[$upload_name]['tmp_name']))
HandleError('Upload failed.');
else if (!isset($_FILES[$upload_name]['name']))
HandleError('File has no name.');
HTML:
<form name="upload" action="/upload" method="POST" ENCTYPE="multipart/formdata">
<table border="0" cellpadding="3" cellspacing="3" class="forms">
<tr>
<tr>
<td style="height: 26px" align="center">
<font class="font_upload_picture">'.MSG142.': <input class="font_upload_picture" type="file" name="userfile">
<input type=hidden name=MAX_FILE_SIZE value=102400 />
</td>
</tr>
<tr>
<td colspan="2">
<p align="center">
<input type="image" name="upload" value="upload" src="/img/layout/btnupload.gif" border="0" />
</p>
<p> </p>
<td><img src="/img/layout/takepicture.gif" border="0" /><br> '.MSG143.'</td>
</tr>
</table>
</form>
The enctype of the form should be multipart/form-data
You have errors in your html. You're missing closing tags for a tr and td tag. Also, close off your file upload input tag />.
Some of your logic is off:
if (!isset($_FILES[$upload_name]))
will always pass. For every <input type="file"> in your form, there'll be a matching $_FILES entry, whether a file was actually uploaded or not. If no file was uploaded to being with, then you'll get error code 4.
else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)
You don't have to check if the error parameter is set. as long as $upload_name has a valid file field name in it, the error section will be there. You can check for $_FILES[$upload_name], though. in case your variable's set wrong.
You've commented it out, but you're checking for valid upload types by checking the user-provided filename. Remember that the ['type'] and ['name'] parameters in $_FILES are user-supplied and can be subverted. Nothing says a malicious user can't rename bad_virus.exe to cute_puppies.jpg and get through your 'validation' check. Always determine MIME type on the server, by using something like Fileinfo. That inspects the file's actual contents, not just the filename.
So, your upload validation should look something like:
if (isset($_FILES[$upload_name]) && ($_FILES[$upload_name]['error'] === UPLOAD_ERR_OK)) {
$fi = finfo_open(FILE_INFO_MIME_TYPE);
$mime = finfo_file($fi, $_FILES[$upload_name]['tmp_name']);
if (!in_array($valid_mime_type, $mime)) {
HandleError("Invalid file type $mime");
}
etc...
} else {
HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
}
Related
Sorry I know there's a lot of posts about that but I can't find a solution in those.
Here's my form :
<form id="form1" action="upload.php" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Name : </td>
<td><input type="text" id="name" name="name"/></td>
</tr>
<tr>
<td>Image :</td>
<td><input type="file" name="image"/></td>
</tr>
<tr><td id='submitAdd' colspan='2'><input type="submit"
value= " Add " /></td></tr>
</table>
</form>
And here upload.php :
<?php
$ext = strtolower(substr(strrchr($_FILES['image']['name'], '.'),1));
$ret = move_uploaded_file($_FILES['image']['tmp_name'], 'item_images/'.$_POST['name'].'.'.$ext);
if ($ret) {
echo 'works';
}
else {
echo 'doesnt work'."</br>";
echo $_FILES['image']['error'];
}
?>
The directory's permission are ok, no uploading error, but still it won't move the file.
Am I missing something ?
Thanks in advance
I think you need to be specifying the absolute save path rather than the relative path it looks like you have now.
Ex. dirname(__FILE__).'/item_images/'.$_POST['name'].'.'.$ext
I would move the file under the uploaded file name, and then rename it. Also, some file type checking and security should be added to this.. Sanitize the post ect.. Here is how I would do it.
upload.php
<?php
$fileName = $_FILES["image"]["name"]; // The file name
$fileTmpLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 for false... and 1 for true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
$fname = $kaboom[0];
$exten = strtolower($fileExt);
//now we do some security checks
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than xxx Megabytes in size.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
//give it the new name
$userstring= $_POST['name'];
$string = $fname.$userstring.'.'.$exten;
$image_name = preg_replace('/\s+/', '', $string);
//now we move it.
$moveResult = move_uploaded_file($fileTmpLoc, "item_images/$image_name");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
$imageFile = "item_images/$image_name";
//$imageFile is the variable to use in the rest of your script.
?>
I just how to fix this problem. This worked for me you can give it a try:
Just change
item_images/'.$_POST['name'].'.'.$ext);
to
'item_images/'basename($_FILES["image"]["name"])
Is it possible to have something like the following
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
<p>Upload File 1</p>
<input type="file" name="profile"/>
<p>Upload File 2</p>
<input type="file" name="cover"/>
<input type="submit" value="Submit" />
</form>
I then have some php script looking like:
if (empty($_POST['save']) === false) {
// FOR PROFIL CHANGE
if (isset($_FILES['profile']) === true){
$allowed= array('jpg', 'jpeg', 'png', 'bmp');
$file_name = $_FILES['profile']['name']; //name of the file
$file_exts = explode('.', $file_name); // extension of the file
$file_extn = strtolower(end($file_exts)); //inlowercase
$file_temp = $_FILES['profile']['tmp_name'];
$id = $user_data['id'];
change_image2($id, $file_temp, $file_extn);
}
// FOR COVER CHANGE
if (isset($_FILES['cover']) === true){
$allowed= array('jpg', 'jpeg', 'png', 'bmp');
$file_name = $_FILES['cover']['name']; //name of the file
$file_exts = explode('.', $file_name); // extension of the file
$file_extn = strtolower(end($file_exts)); //inlowercase
$file_temp = $_FILES['cover']['tmp_name'];
$id = $user_data['id'];
change_image3($id, $file_temp, $file_extn);
}
But if I upload just one file ( cover for example ); it is saved also in profile for some reason ...
If find this weird because i gave different names to the inputs.
Can anybody explain the problem please?
Use print_r($_FILES) to check what data you receive when only one file is uploaded.
I think $_FILES['profile'] is always set, no matter if a file is uploaded using the corresponding <INPUT> element or not. You should check if $_FILES['profile']['name'] contains the file name or is empty.
You must also use is_uploaded_file() (and move_uploaded_file()) with $_FILES['profile']['tmp_name'] to handle the file.
is_uploaded_file() is the only authoritative answer to the question: "did the user uploaded a file using this <input> control?"
// FOR PROFIL CHANGE
if (! empty($_FILES['profile']['name'])
&& is_uploaded_file($_FILES['profile']['tmp_name'])){
// ... process the file ...
Change your condition from if (isset($_FILES['profile']) === true){ into if (strlen($_FILES['profile']['tmp_name']) > 0){.
There will be always $_FILES['profile'], but $_FILES['profile']['tmp_name'] contains some data only if there is some file transfer.
I have an HTML form as the following:
<form id="addTrack" action="/worship/script/upload.php" method="post" enctype="multipart/form-data">
<label>File:</label>
<input type="file" name="uploaded" id="addTrackFile"/>
<label>Key Title: </label>
<input type="text" name="title" id="addTrackTitle"/>
<input type="hidden" name="id" id="addTrackId"/><br>
</form>
<button onclick="uploadAddTrack()">Upload</button>
<button onclick="closeAddTrack()">Close</button>
When I submit the form the file uploads to the server properly, but when it gets redirected to the PHP action script, it gets stopped at the first error catch. The script then dumps the $_FILES variable which it returns as an empty array. As you can see in the code below, I also have it echo the error, but it also echoes an empty string.
Why am I not getting a file in the $_FILES array?
My PHP Code:
$id=$_POST["id"];
$name=$_POST["title"];
$name = str_replace(" ","",$name);
$allowed_filetypes = array('.mp3','.m4a','.wav','.wma');
$filename = $_FILES['uploaded']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
$target = "../audio/";
$target = $target . $id. "_".$name.$ext;
$ok=1;
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
//------------This is where it gets stopped-----------------//
var_dump($_FILES);
echo $_FILES["uploaded"]["error"];
return;
}
if(!in_array($ext,$allowed_filetypes))
die("This file type is not allowed");
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
include("updateDB.php");
header("Location:/worship/cpanel/?autoload=$id");
}
The size of the file I am uploading is 9mb.
My php.ini relevant info
file_uploads: On
upload_max_filesize: 25M
upload_tmp_dir: no value
max_post_size: 8M
check you PHP.ini file. make sure the POST size is larger the 8M. because that is the default and you're sending info that is 9MB.
`; Maximum size of POST data that PHP will accept.
post_max_size = 8M`
Alright I have way to much time invested in this. I am new to PHP programming and trying to grasp the basics, but I am a little lost as of last night I was able to get a PHP form to upload basic data like a name address and stuff to my (MySQL) server.
But today I said let's do the next step which would be an image to the server.
I have watched 3 videos on YouTube probably a 100 times just recoping code and trying it in so many different ways.
http://www.youtube.com/watch?v=CxY3FR9doHI
http://www.youtube.com/watch?v=vFZfJZ_WNC4&feature=relmfu
and still haven't been able to get it.
But long story short: I have a config.php file that connects to the server and here is the the code I'm running on the upload form page:
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<form action="UploadContent.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="Upload">
</form>
<?php
// connect to database
include"config.php";
// file properties
$file = $_FILES['image']['tmp_name'];
if (!isset($file))
echo "Please select a profile pic";
else
{
$image = addslashes(file_get_content($_FILES['image']['tmp_name']));
$image_name = addslashes($FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if ($image_size==FALSE)
echo "That isn't a image.";
else
{
$insert = mysql_query("INSERT INTO content VALUES ('','','','','','','','','','$image_name','$image',)");
}
}
?>
</body>
</html>
The reason for all the '', '', '', '' on the insert line is because I have the name in the 10th field and the image blob in the 11th and all the ones leading up to that are first name, last name and random stuff like that. How can I fix this? It is returning the error:
Fatal error: Call to undefined function file_get_content() in /home/content/34/9587634/html/WEBPAGE/UploadContent.php on line 22
I don't know what to do.
The code overlooks calling the function move_uploaded_file() which would check whether the indicated file is valid for uploading.
You may wish to review a simple example at:
http://www.w3schools.com/php/php_file_upload.asp
You need to add two new file one is index.html, copy and paste the below code and other is imageup.php which will upload your image
<form action="imageup.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner" >
<input type="submit" value="submit">
</form>
imageup.php
<?php
$banner=$_FILES['banner']['name'];
$expbanner=explode('.',$banner);
$bannerexptype=$expbanner[1];
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Yh:i:sa', time());
$rand=rand(10000,99999);
$encname=$date.$rand;
$bannername=md5($encname).'.'.$bannerexptype;
$bannerpath="uploads/banners/".$bannername;
move_uploaded_file($_FILES["banner"]["tmp_name"],$bannerpath);
?>
The above code will upload your image with encrypted name
Change function file_get_content() in your code to file_get_contents() . You are missing 's' at the end of function name. That is why it is giving undefined function error.
file_get_contents()
Remove last unnecessary comma after $image filed in line
"INSERT INTO content VALUES ('','','','','','','','','','$image_name','$image',)
I would recommend you to save the image in the server, and then save the URL in MYSQL database.
First of all, you should do more validation on your image, before non-validated files can lead to huge security risks.
Check the image
if (empty($_FILES['image']))
throw new Exception('Image file is missing');
Save the image in a variable
$image = $_FILES['image'];
Check the upload time errors
if ($image['error'] !== 0) {
if ($image['error'] === 1)
throw new Exception('Max upload size exceeded');
throw new Exception('Image uploading error: INI Error');
}
Check whether the uploaded file exists in the server
if (!file_exists($image['tmp_name']))
throw new Exception('Image file is missing in the server');
Validate the file size (Change it according to your needs)
$maxFileSize = 2 * 10e6; // = 2 000 000 bytes = 2MB
if ($image['size'] > $maxFileSize)
throw new Exception('Max size limit exceeded');
Validate the image (Check whether the file is an image)
$imageData = getimagesize($image['tmp_name']);
if (!$imageData)
throw new Exception('Invalid image');
Validate the image mime type (Do this according to your needs)
$mimeType = $imageData['mime'];
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($mimeType, $allowedMimeTypes))
throw new Exception('Only JPEG, PNG and GIFs are allowed');
This might help you to create a secure image uploading script with PHP.
Code source: https://developer.hyvor.com/php/image-upload-ajax-php-mysql
Additionally, I suggest you use MYSQLI prepared statements for queries to improve security.
Thank you.
Simple PHP file/image upload code on same page.
<form action="" method="post" enctype="multipart/form-data">
<table border="1px">
<tr><td><input type="file" name="image" ></td></tr>
<tr><td> <input type="submit" value="upload" name="btn"></td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$image=$_FILES['image']['name'];
$imageArr=explode('.',$image); //first index is file name and second index file type
$rand=rand(10000,99999);
$newImageName=$imageArr[0].$rand.'.'.$imageArr[1];
$uploadPath="uploads/".$newImageName;
$isUploaded=move_uploaded_file($_FILES["image"]["tmp_name"],$uploadPath);
if($isUploaded)
echo 'successfully file uploaded';
else
echo 'something went wrong';
}
?>
Here is a basic example of how an image file with certain restrictions (listed below) can be uploaded to the server.
Existence of the image.
Image extension validation
Checks for image size.
<?php
$newfilename = "newfilename";
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png");
if(file_exists($file_name)) {
echo "Sorry, file already exists.";
}
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$newfilename.".".$file_ext);
echo "Success";
echo "<script>window.close();</script>";
}
else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>
Credit to this page.
<?php
$filename=$_FILES['file']['name'];
$filetype=$_FILES['file']['type'];
if($filetype=='image/jpeg' or $filetype=='image/png' or $filetype=='image/gif')
{
move_uploaded_file($_FILES['file']['tmp_name'],'dir_name/'.$filename);
$filepath="dir_name`enter code here`/".$filename;
}
?>
<?php
$target_dir = "images/";
echo $target_file = $target_dir . basename($_FILES["image"]["name"]);
$post_tmp_img = $_FILES["image"]["tmp_name"];
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$post_imag = $_FILES["image"]["name"];
move_uploaded_file($post_tmp_img,"../images/$post_imag");
?>
This code is very easy to upload file by php. In this code I am performing uploading task in same page that mean our html and php both code resides in the same file. This code generates new name of image name.
first of all see the html code
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner_image" >
<input type="submit" value="submit">
</form>
now see the php code
<?php
$image_name=$_FILES['banner_image']['name'];
$temp = explode(".", $image_name);
$newfilename = round(microtime(true)) . '.' . end($temp);
$imagepath="uploads/".$newfilename;
move_uploaded_file($_FILES["banner_image"]["tmp_name"],$imagepath);
?>
I wonder whether someone may be able to help me please.
Using some excellent online tutorials I've put together the code below which allows a user to upload image files to a server folder and the filename and other details to a mySQL database.
PHP Script
<?php
//define a maxim size for the uploaded images
//define ("MAX_SIZE","100");
// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","150");
define ("HEIGHT","100");
// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and height defined, but without deforming the image
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);
if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);
//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
// next we will calculate the new dimmensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimmensions with the new ones
// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
// and the height will be calculated so the image ratio will not change
// 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimmensions will be from the fixed ones
$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if($ratio1>$ratio2) {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}
// we create a new image with the new dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
// resize the big image to the new created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename);
else
imagejpeg($dst_img,$filename);
//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}
// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$title = ($_POST['title']);
if ($title == '') // if title is not set
$title = '(No Title Provided)';// use (empty title) string
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
if ($image)
{
// get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
// get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
// if it is not a known extension, we will suppose it is an error, print an error message
//and will not upload the file, otherwise we continue
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))
{
echo '<b> Error! </b> - The image that you attempted to upload is not in the correct format. The file format <b> must </b> be one of the following: <b> "jpg", "jpeg" </b> or <b> "png" </b>. Please try again.';
$errors=1;
}
else
{
// get the size of the image in bytes
// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=getimagesize($_FILES['image']['tmp_name']);
$sizekb=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > 1150000)
{
echo '<b> Error! </b> - The file that you are attempting to upload is greater than the prescribed <b> 1MB </b> limit. Please try again.';
$errors=1;
}
//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$title.'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
//echo '<b> Error! </b> Your file has not been loaded';
//$errors=1;
}
else
{
// the new thumbnail image will be placed in images/thumbs/ folder
$thumb_name='images/thumbs/'.$image_name;
// call the function that will create the thumbnail. The function will get as parameters
//the image name, the thumbnail name and the width and height desired for the thumbnail
$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
} }}
//If no errors registred, print the success message and show the thumbnail image created
if(isset($_POST['Submit']) && !$errors)
{
//echo '<br><b> Success! </b> - Your image has been uploaded</br>';
//echo '<img src="'.$thumb_name.'">';
}
require("mapmyfindsdbinfo.php");
// Gets data from form
$userid = $_POST["userid"];
$locationid = $_POST["locationid"];
$findosgb36lat = $_POST["findosgb36lat"];
$findosgb36lon = $_POST["findosgb36lon"];
$dateoftrip = $_POST["dateoftrip"];
$findcategory = $_POST["findcategory"];
$findname = $_POST["findname"];
$finddescription = $_POST["finddescription"];
$detectorid= $_POST["detectorname"];
$searchheadid = $_POST["searchheadname"];
if( empty($_POST["detectorsettings"]) ) {
$detectorsettings = 'No details provided.'; } else {
$detectorsettings = $_POST["detectorsettings"]; }
if( empty($_POST["pasref"]) ) {
$pasref = 'No PAS Ref. number provided.'; } else {
$pasref = $_POST["pasref"]; }
if( empty($_POST["additionalcomments"]) ) {
$additionalcomments = 'No additional comments made.'; } else {
$additionalcomments = $_POST["additionalcomments"]; }
$makepublic = $_POST["makepublic"];
// Opens a connection to a MySQL server
$conn = mysql_connect ("hostname", $username, $password);
if (!$conn) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $conn);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$sql = "INSERT INTO finds (userid, locationid, findosgb36lat, findosgb36lon, dateoftrip, findcategory, findname, finddescription, detectorid, searchheadid, detectorsettings, pasref, additionalcomments, makepublic) VALUES ('$userid', '$locationid', '$findosgb36lat', '$findosgb36lon', '$dateoftrip', '$findcategory', '$findname', '$finddescription', '$detectorid', '$searchheadid', '$detectorsettings', '$pasref', '$additionalcomments', '$makepublic')";
$result = mysql_query($sql, $conn);
$findid = mysql_insert_id($conn);
$sql = "INSERT INTO testimages (title, imagename, findid) VALUES ('$title', '$image_name', '$findid')";
$result = mysql_query($sql, $conn);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
HTML Form
<form name="savemyfindstolocation" method="post" enctype="multipart/form-data" action="savemyfindstolocation.php">
<p align="left">Do You Wish To Add Find Images<label></label>
<label></label>
</p>
<div align="left">
<table id="addfiletable" border="1" style="table-layout:auto">
<tr>
<td> </td>
<td><div align="center">Title</div></td>
<td><div align="center">File Location </div></td>
</tr>
<tr>
<td width="20"><input name="select" type="radio" id="select" title=""/></td>
<td width="144"><input name="title" type="text" id="title"/></td>
<td width="314"><input name="image" type="file" id="image" onchange="addRow();" size="40"/></td>
</tr>
</table>
<div align="justify">
<input type="submit" name="deleterow" value="Delete Row" />
</div>
</div>
<input name="submit" type="submit" value="Submit" />
</form>
It all works well, but I'd now like to extend the functionality of allowing a user to upload more than 1 file at a time. I've done a fair bit of research to look at how to upload multiple files, but I'm fairly new to PHP and a little unsure as to which is the best way to progress this.
I just wondered whether someone could perhaps have a look at what I've put together and offer some guidance on how I can change this to upload mutiple files upon the form submit.
Many thanks
PHP
foreach($_FILES['image']['name'] as $i => $name)
{
// now $name holds the original file name
$tmp_name = $_FILES['image']['tmp_name'][$i];
$error = $_FILES['image']['error'][$i];
$size = $_FILES['image']['size'][$i];
$type = $_FILES['image']['type'][$i];
if($error === UPLOAD_ERR_OK)
{
$extension = getExtension($name);
if( ! in_array(strtolower($extension, array('jpg', 'jpeg', 'png') )
{
// Error, invalid extension detected
}
else if ($size > $maxAllowedFileSize /* needs to be defined elsewhere */)
{
// Error, file too large
}
else
{
// No errors
$newFileName = 'foo'; // You'll probably want something unique for each file.
if(move_uploaded_file($tmp_file, $newFileName))
{
// Uploaded file successfully moved to new location
$thumbName = 'thumb_image_name';
$thumb = make_thumb($newFileName, $thumbName, WIDTH, HEIGHT);
}
}
}
}
HTML
<form method="post" enctype="multipart/form-data">
<input name="image[]" type="file" class="image-upload" />
<input name="image[]" type="file" class="image-upload" />
<input name="image[]" type="file" class="image-upload" />
<input name="image[]" type="file" class="image-upload" />
<input name="image[]" type="file" class="image-upload" />
<!-- You need to add more, including a submit button -->
</form>
Note the name of the input elements. The [] at the end cause PHP to create an array and add the items to the array.
If you don't bother paying for it, you may have a look at PHP File Uploader, it's a very nifty and useful tool, that I already used for a couple of sites.
Not that cheap, but definitely worth the cost.