File not uploading into database. Validation ok? - php

I have a site where users can upload photos from mobile, but all the photos that are uploaded from mobiles, show 90 degrees to the left when upload. I fixed this problem but now, after the file is validated, its not going into the db. please any help..
Share script code is:
<?php
require('help.php');
if(isset($_POST['submit'])){
$title = $_POST['title'];
$content = $_POST['content'];
$posted = $_POST['posted'];
$date = date("Y-m-d H:i:s");
$ip = $_SERVER["REMOTE_ADDR"];
$rand = rand(1,1000000);
if(empty($title)){
echo "Titulli eshte bosh.";
}else if(empty($content)){
echo "Permbajtja eshte bosh.";
}else if(empty($_FILES['file']['name'])){
echo "Imazhi eshte bosh.";
}else if($_FILES['file']['name']){
$name = htmlspecialchars($_FILES['file']['name']);
$ext = end((explode(".", $name)));
$ext = strtolower($ext);
//if no errors...
if(!$_FILES['file']['error']){
//now is the time to modify the future file name and validate the file
$new_file_name = date('ymdHisu'). ".". $ext;
if($_FILES['file']['size'] > (6144000)){
$valid_file = false;
echo 'Oops! Your file\'s size is to large.';
}
elseif($ext !== "jpg" && $ext !== "png" && $ext !== "jpeg" && $ext != "gif" && $ext !== "bmp") {
$valid_file = false;
echo "Your file must be in jpg, jpeg, png, gif, or bmp formats.";
}else{
$valid_file = true;
}
//if the file has passed the test
if($valid_file){
//move it to where we want it to be
move_uploaded_file($_FILES['file']['tmp_name'], 'images/'.$new_file_name);
$exif_read = exif_read_data("images/".$new_file_name);
if(!empty($exif_read['Orientation'])){
$orientation_data = exif_read_data("images/".$new_file_name)['Orientation'];
}
if(isset($orientation_data) && $orientation_data !== 1){
$path = "images/". $new_file_name;
$buffer = ImageCreateFromJPEG($path);
$exif = exif_read_data($path);
if(!empty($exif['Orientation'])){
switch($exif['Orientation']){
case 8:
$buffer = imagerotate($buffer,90,0);
break;
case 3:
$buffer = imagerotate($buffer,180,0);
break;
case 6:
$buffer = imagerotate($buffer,-90,0);
break;
}
$image = imagejpeg($buffer, $path, 90);
}
}
if(empty($posted)){
$posted = 'Anonim';
}
$sql = "INSERT INTO problems(title, content, date, image, posted, ip) VALUES (:title, :content, :date, :image, :posted, :ip)";
$query = $db->prepare($sql);
$results = $query->execute(array(
':title' => htmlentities ($title),
':content' => htmlentities ($content),
':date' => $date,
':image' => $path,
':posted' => htmlentities ($posted),
':ip' => $ip
));
echo "<div id='ok'>Lajmi u raportua me sukses. Kontrollojeni <a href='index.php'>ketu</a> .</div>";
}
}else{
//set that to be the returned message
echo 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
}
?>

Problem:
after the file is validated, its not going into the db.
Solution
That's because your $path is undefined when you try to insert record into the database. Move the $path variable outside of the if(isset($orientation_data) && $orientation_data !== 1){ ... } block, like this:
// your code
$path = "images/". $new_file_name; // moved this outside of the if block
if(isset($orientation_data) && $orientation_data !== 1){
$buffer = ImageCreateFromJPEG($path);
$exif = exif_read_data($path);
if(!empty($exif['Orientation'])){
switch($exif['Orientation']){
case 8:
$buffer = imagerotate($buffer,90,0);
break;
case 3:
$buffer = imagerotate($buffer,180,0);
break;
case 6:
$buffer = imagerotate($buffer,-90,0);
break;
}
$image = imagejpeg($buffer, $path, 90);
}
}
// your code

Related

How to move a object(GdImage) to a specific folder?

I'm working on a image converter that convert jpg and png to webp and webp to jpg and png and i've been trying to make that the converted files go to a specific folder instead of my working folder but it doesn't go on my convert forlder
here's my code
<?php
require "db.php";
$pdo = new \PDO(DSN, USER, PASS);
if (!empty($_FILES['files']['name'][0])) {
$files = $_FILES['files'];
$fileName = $_POST['name'];
$fileTag = $_POST['tag'];
$fileDescription = $_POST['description'];
$convert = $_POST['convert'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'jpeg', 'png', 'webp');
foreach ($files['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext, $allowed)) {
if ($file_error === 0) {
if ($file_size <= 2097152) /* 2mb */ {
$file_name_new = uniqid('IMG-', true) . '.' . $file_ext;
$file_destination = 'uploads/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
$query = "INSERT INTO images(name, tag, description, images) VALUES (:name, :tag, :description,:images)";
$statement = $pdo->prepare($query);
$statement->bindValue(':name', $fileName, \PDO::PARAM_STR);
$statement->bindValue(':tag', $fileTag, \PDO::PARAM_STR);
$statement->bindValue(':description', $fileDescription, \PDO::PARAM_STR);
$statement->bindValue(':images', $file_name_new, \PDO::PARAM_STR);
$statement->execute();
$upload = $statement->fetchAll();
} else {
$failed[$position] = "[{$file_name}] failed to upload.";
}
} else {
$failed[$position] = "[{$file_name}] is too large.";
}
} else {
$failed[$position] = "[{$file_name}] failed to upload {$file_error}.";
}
} else {
$failed[$position] = "[{$file_name}] file extension '{$file_ext}' is not allowed.";
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
} else {
echo 'no files';
}
if (exif_imagetype($file_destination) == IMAGETYPE_PNG && $convert ==='webp') {
$image = imagecreatefrompng($file_destination);
imagewebp($image, str_replace('png', 'webp', $file_name_new));
move_uploaded_file($file_destination, 'convert/');
} elseif (exif_imagetype($file_destination) == IMAGETYPE_JPEG && $convert ==='webp') {
$image = imagecreatefromjpeg($file_destination);
imagewebp($image, str_replace('jpg', 'webp', $file_name_new));
move_uploaded_file($file_tmp, 'convert/');
} elseif (exif_imagetype($file_destination) == IMAGETYPE_WEBP && $convert ==='png') {
$image = imagecreatefromwebp($file_destination);
imagepng($image, str_replace('webp', 'png', $file_name_new));
move_uploaded_file($file_tmp, 'convert/');
}elseif (exif_imagetype($file_destination) == IMAGETYPE_WEBP && $convert ==='jpg') {
$image = imagecreatefromwebp($file_destination);
imagepng($image, str_replace('webp', 'jpg', $file_name_new));
move_uploaded_file($file_tmp, 'convert/');
}else {
echo "can't convert it";
}var_dump($image);
I tried changing the variable in the move_uploaded_file but still won't let me

File name too long while uploading image in database

I have written a line of codes to upload an image in the database, however, trying to upload image gives me this error
File name too long
Following is my code to upload an image to database:
if($_SERVER['REQUEST_METHOD']=="POST")
{
$pid = rand(1000,9000);
$title = $_POST['title'];
$descpt = $_POST['description'];
$push = isset($_POST['send_push']) ? $_POST['send_push'] : "";
$feature_image = array();
$fy = $_POST['fy'];
if(empty($title) || empty($descpt) || empty($fy))
{
array_push($this->errors, MEND_FIELD_ERROR);
return;
}
if(!empty($_FILES['feature_image']['name'][0]))
{
$image = $_FILES['feature_image'];
$allowed_ext = array('jpeg','jpg','png','pdf','docx');
$allowed_size = 20000000;
foreach($image['name'] as $pos=>$image_name)
{
$dir = "./cdn/uploads/notice/".$title;
$tmp = $image['tmp_name'][$pos];
$img_size = $image['size'][$pos];
$img_error = $image['error'][$pos];
$img_ext = explode('.', $image_name);
$img_name = $img_ext[0];
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed_ext))
{
if($img_size <= $allowed_size)
{
if(!file_exists($dir))
{
mkdir($dir);
}
$image_new_name = $img_name.'$$'.uniqid('', true).'.'.$img_ext;
$upload_destination = $dir.'/'.$image_new_name;
if(move_uploaded_file($tmp, $upload_destination))
{
array_push($feature_image, $image_new_name);
}
else
{
array_push($this->errors, $img_error);
return;
}
}
}
else
{
array_push($this->errors, $img_ext.' is not an allowed file extension.');
return;
}
}
}
$s_feature_image = json_encode($feature_image, JSON_UNESCAPED_UNICODE);
$statement = $this->db->prepare("INSERT INTO `notice` (`pid`,`title`,`descpt`,`date`,`photo`,`fy`)
VALUES (?,?,?,?,?,?)");
if($statement->execute([$pid,$title,$descpt,DAT, $s_feature_image, $fy]))
{
if($push == "checked")
{
$descpt = strip_tags($descpt);
$tek = array("message"=>$descpt,"title"=>$title);
$tokens = $this->getTokens();
$this->push_notification($tokens,$tek);
}
ExitThis::send_to(URL.'notice?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
}
Is it because of permission issue or something else? If so, what is causing me this problem and how do I fix this?
this is how I upload the file into the server and save the file name + extension into the database.
<?php
include 'connection.php';
$id = $_POST['id'];
$imgFile = $_FILES['photo']['name'];
$tmp_dir = $_FILES['photo']['tmp_name'];
$imgSize = $_FILES['photo']['size'];
$folder = 'images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$img = rand(1000, 1000000) . "." . $imgExt;
// allow valid image file formats
if (in_array($imgExt, $valid_extensions)) {
// Check file size '5MB'
if ($imgSize < 5000000) {
move_uploaded_file($tmp_dir, $folder . $img);
} else {
$errMSG = "Sorry, your file is too large.";
}
} else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
$query = mysqli_query($con, "UPDATE `profile` SET `photo` = '$img' WHERE `id` = '$id'");
if ($query) {
echo "<script>alert('Profile Updated'); window.location ='index.php?data=profile' </script>";
} else {
echo "<script>alert('Failed'); window.location ='index.php?data=profile' </script>";
}
?>
Hope this helps.
Cheers.

Insert multiple images in one column as a comma separated list

I am creating a real estate web application and now creating a form which i will allow the editor to input data concerning a certain property , among of those inputs is images, but i do not know how to input multiple values in one column in the database.
Here are my codes.
if(!empty($_FILES)){
$photo1 = $_FILES['photo1'];
$photo2 = $_FILES['photo2'];
$photo3 = $_FILES['photo3'];
$photo4 = $_FILES['photo4'];
$photo5 = $_FILES['photo5'];
$photo6 = $_FILES['photo6'];
$photo7 = $_FILES['photo7'];
$photo = [$photo1,$photo2,$photo3,$photo4,$photo5,$photo6,$photo7];
foreach ($photo as $photos) {
$name = $photos['name'];
$nameArray = explode('.',$name);
$filename = $nameArray[0];
$fileEXT = $nameArray[1];
$mime = explode('/', $photos['type']);
$mimeType = $mime[0];
$mimeEXT = $mime[1];
$temploc = $photos['tmp_name'];
$filesize = $photos['size'];
$allowed = array('png','jpg','jpeg','gif',);
$uploadname = md5(microtime()).'.'.$fileEXT;
$uploadpath = LINKURL.'/imgs/photos/'.$uploadname;
$dbpath = '/realeastate/imgs/photos/'.$uploadname;
if($mimeType != 'image'){
$errors[]= 'File must be an image';
}
if(!in_array(strtolower($fileEXT), $allowed)){
$errors[]= 'The photo extension must be jpg,png,jpeg or gif.';
}
if($filesize > 25000000){
$errors[]= 'The file size must be less than 25MB.';
}
if(strtolower($fileEXT) != $mimeEXT && $mimeEXT == 'jpeg' && strtolower($fileEXT) != 'jpg' ){
$errors[]= 'File extension does not match the file.';
}
if(!empty($errors)){
echo show_errors($errors);
} else {
//upload file and insert into database
if (!empty($_FILES)) {
move_uploaded_file($temploc,$uploadpath);
}
if(isset($_GET['edit'])){
$db->query("UPDATE property SET taken ='$taken' WHERE id ='$edit_id'");
}else{
$db->query("INSERT INTO property (category,status,purpose,cover,images,city,place,price,payment,garage,wideness,visit,takenhome,hospital,school,market,bank,church,mosque,government,datetostart,floor) VALUES ('$category','$status','$purpose','$dbpath','$city','$place','$price','$payment','$garage','$wide','$dprice','$adprice','$hospital','$school','$church','$mosque','$government','$opendate','$floor')");
}
}
}
$_SESSION['success'] = 'Property Added successful';
header('Location: house.php');
}

Image rotating 90 degrees when uploaded from mobile? PHP

I have a site where users can upload photos from mobile, but all the photos that are uploaded from mobiles, show 90 degrees to the left when upload. Live site is www.uneraportoj.com. I now the problem is the exeif but i tried using a plugin but is not working. Any help is recommended.
Share script code is:
<?php
include_once('help.php');
if(isset($_POST['submit'])){
$title = $_POST['title'];
$content = $_POST['content'];
$posted = $_POST['posted'];
$date = date("Y-m-d H:i:s");
$ip = $_SERVER["REMOTE_ADDR"];
$rand = rand(1,1000000);
if(empty($title)){
echo "Titulli eshte bosh.";
}else if(empty($content)){
echo "Permbajtja eshte bosh.";
}else if(empty($_FILES['image']['name'])){
echo "Imazhi eshte bosh.";
}else if (
($_FILES['image']['type'] == 'image/gif')
|| ($_FILES['image']['type'] == 'image/jpeg')
|| ($_FILES['image']['type'] == 'image/pjpeg')
|| ($_FILES['image']['type'] == 'image/png')
&& ($_FILES['image']['size'] < 200000)
){
$part = $rand.'_'.$_FILES['image']['name'];
if ($_FILES["image"]["error"] > 0) {
echo "return code" . $_FILES['image']['error'];
//Code from plugin start
if($_FILES['image']){
// If the image is jpg and has orientation data, make sure we orientate correctly before uploading
if($image->exif('Orientation'))
$image = orientate($image, $image->exif('Orientation'));
}
}else if(move_uploaded_file($_FILES['image']['tmp_name'],'images/'. $part.'')){
if(empty($posted)){
$posted = 'Anonim';
}
$sql = "INSERT INTO ***(title, content, date, image, posted, ip) VALUES (:title, :content, :date, :image, :posted, :ip)";
$query = $db->prepare($sql);
$results = $query->execute(array(
':title' => htmlentities ($title),
':content' => htmlentities ($content),
':date' => $date,
':image' => $part,
':posted' => htmlentities ($posted),
':ip' => $ip
));
echo "<div id='ok'>Lajmi u raportua me sukses. Kontrollojeni <a href='index.php'>ketu</a> .</div>";
}
}else{
echo "<div id='ok'>Imazhi nuk eshte i sakte. (Vetem jpg/png)</div>";
}
}
?>
Plugin code :
<?php /**
* Orientate an image, based on its exif rotation state
*
* #param Intervention\Image\Image $image
* #param integer $orientation Image exif orientation
* #return Intervention\Image\Image
*/
$image = $_FILES['image'];
function orientate($image, $orientation)
{
switch ($orientation) {
// 888888
// 88
// 8888
// 88
// 88
case 1:
return $image;
// 888888
// 88
// 8888
// 88
// 88
case 2:
return $image->flip('h');
// 88
// 88
// 8888
// 88
// 888888
case 3:
return $image->rotate(180);
// 88
// 88
// 8888
// 88
// 888888
case 4:
return $image->rotate(180)->flip('h');
// 8888888888
// 88 88
// 88
case 5:
return $image->rotate(-90)->flip('h');
// 88
// 88 88
// 8888888888
case 6:
return $image->rotate(-90);
// 88
// 88 88
// 8888888888
case 7:
return $image->rotate(-90)->flip('v');
// 8888888888
// 88 88
// 88
case 8:
return $image->rotate(90);
default:
return $image;
}
}
?>
I found this youtube video to be super helpful on image oriantaion with exif data
check it out
https://www.youtube.com/watch?v=HjHSgGFqAtE
print 'exif orientation';
$original_filename = 'car1.jpg';
$exif_data = exif_read_data($original_filename);
// displays exif data
// print '<pre>';
// print_r($exif_data);
// print '<pre>';
$orientation = orientation($exif_data);
$degrees = orientation_flag($orientation);
print '<pre>';
print_r($orientation);
print '</pre>';
print '<pre>';
print_r($degrees);
print '</pre>';
$image_data = imagecreatefromjpeg($original_filename);
$image_rotate = imagerotate($image_data, $degrees, 0);
$rotated_filename = 'rotated_' . $original_filename;
imagejpeg($image_rotate, $rotated_filename);
imagedestroy($image_data);
imagedestroy($image_rotate);
// finds orientation value in exif data
function orientation($exif_data) {
// search array for orientation
foreach($exif_data as $key => $val) {
// print '<pre>';
// print_r($key);
// print '<pre>';
if(strtolower($key) == 'orientation') {
return $val;
}
}
}
// gets orientation data and returns degrees needed for rotation
function orientation_flag($orientation) {
switch($orientation):
case 1:
return 0;
case 8:
return 90;
case 3:
return 180;
case 6:
return 270;
endswitch;
}
?>
<img src="car1.jpg" width="400"/>
<br>
<img src="rotated_car1.jpg" width="400"/>
You have your function call under the if(error) statement, meaning it will only rotate if there is an error. Place it after your image has passed the error checks and you have moved it to the final location.
if ($_FILES["image"]["error"] > 0) {
echo "return code" . $_FILES['image']['error'];
}else if(move_uploaded_file($_FILES['image']{'tmp_name'],'images/'. $part.'')){
if(file_exists('images/'. $part.'')){
/* read exif data (returns it as an array) */
$exif_read = exif_read_data('images/'. $part.'');
/* if exif contains orientation property (some images don't) */
if(!empty($exif_read['Orientation'])){
$orientation_data = $exif_read['Orientation'];
$image = orientate($image, $Orientation_data);
}
Edit:
I copied and pasted the exact code that I am using for image uploading. For what I'm doing, I only have to worry about orientations 3, 6, and 8, but you can add the rest if you think you'll need them. Use PHP's imageflip() function after imagerotate() (read how to use that here)
<?php
require("../db_credentials.php");
if($_FILES['file']['name']){
$name = htmlspecialchars($_FILES['file']['name']);
$ext = end((explode(".", $name)));
$ext = strtolower($ext);
//if no errors...
if(!$_FILES['file']['error']){
//now is the time to modify the future file name and validate the file
$new_file_name = date('ymdHisu'). ".". $ext;
if($_FILES['file']['size'] > (6144000)){
$valid_file = false;
echo 'Oops! Your file\'s size is to large.';
}
elseif($ext !== "jpg" && $ext !== "png" && $ext !== "jpeg" && $ext != "gif" && $ext !== "bmp") {
$valid_file = false;
echo "Your file must be in jpg, jpeg, png, gif, or bmp formats.";
}
else{
$valid_file = true;
}
//if the file has passed the test
if($valid_file){
//move it to where we want it to be
move_uploaded_file($_FILES['file']['tmp_name'], 'images/'.$new_file_name);
$exif_read = exif_read_data("images/".$new_file_name);
if(!empty($exif_read['Orientation'])){
$orientation_data = exif_read_data("images/".$new_file_name)['Orientation'];
}
if(isset($orientation_data) && $orientation_data !== 1){
$path = "../images/". $new_file_name;
$buffer = ImageCreateFromJPEG($path);
$exif = exif_read_data($path);
if(!empty($exif['Orientation'])){
switch($exif['Orientation']){
case 8:
$buffer = imagerotate($buffer,90,0);
break;
case 3:
$buffer = imagerotate($buffer,180,0);
break;
case 6:
$buffer = imagerotate($buffer,-90,0);
break;
}
imagejpeg($buffer, $path, 90);
}
}
}
}
//if there is an error...
else
{
//set that to be the returned message
echo 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
?>

loop for multi-image upload to sql DB

I've edited this code to go from 1 image upload to 2, but it's ugly--basically just duplicated the previous variables. I want to get up to 8 images, and imagine there's a way to create an array and put it through a loop instead of making an individual instance for each image.
Thanks for any insight..
This is my code so far:
<?PHP
include("inc/header.php");
$back = "<a href='sell.php'>Click Here To Go Back And Try Again</a>";
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0 || $_FILES['userfile2']['size'] > 0 )
{
$title = $_POST['title'];
$description = $_POST['description'];
$category = $_POST['category'];
$price = $_POST['price'];
$name = $_POST['name'];
$number = $_POST['number'];
$email = $_POST['email'];
$password = $_POST['password'];
// PICTURE UPLOAD SYSTEM
$imagename = basename($_FILES['userfile']['name']);
$imagename2 = basename($_FILES['userfile2']['name']);
if(empty($imagename) || empty($imagename2)) {
$error = 1;
echo"<h2 class='error'>The name of the image was not found.</h2>".$back;
}
if($error != 1 && $noimg != 1)
{
$filename = stripslashes($_FILES['userfile']['name']);
$extension = substr(strrchr($filename, '.'), 1);
$extension = strtolower($extension);
$filename2 = stripslashes($_FILES['userfile2']['name']);
$extension2 = substr(strrchr($filename2, '.'), 1);
$extension2 = strtolower($extension2);
//if it is not a known extension, we will suppose it is an error and will not upload the file,
//otherwise we will do more tests
}
if (($extension != "jpg") && ($extension2 != "jpg") && ($extension != "jpeg") && ($extension != "jpeg") && ($extension != "png") && ($extension2 != "png") && ($extension != "gif") && ($extension2 != "gif"))
{
//print error message
echo '<h2 class="error">Error. Images Must Be Jpg, Gif, or Png Format! Please Go Back And Try Another Image.</h2>'.$back.'';
$errors=1;
}
else
{
$time = time();
$newimage = "photos/" . $time . $imagename;
$newimage2 = "photos/" . $time . $imagename2;
$result = #move_uploaded_file($_FILES['userfile']['tmp_name'], $newimage);
$result2 = #move_uploaded_file($_FILES['userfile2']['tmp_name'], $newimage2);
if(empty($result)) {
$error = 1;
echo "<h2 class='error'>There was an error moving the uploaded file.</h2><br/>".$back."";
}
// insert to SQL
$date = date("Y-m-d G:i:s");
$query = "INSERT INTO classifieds (adid, title, description, cat, price, name, number, email, password, picture, picture2, date, views, authorized ) VALUES ('', '$title', '$description', '$category', '$price', '$name', '$number', '$email', '$password', '$newimage', '$newimage2', '$date', '0', '0')";
mysql_query($query) or die(mysql_error());
}
If you force the inputs into an array by using
<input type='file' name='file[]' />
<input type='file' name='file[]' />
<input type='file' name='file[]' />
then use the following function I found from file-upload.multiple.php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
You will be able to loop through the array very easily, hardly noticing you dealing with multiple files.
if (isset ($_POST['upload'])) {
extract ($_POST, EXTR_PREFIX_ALL, 'post');
$file_ary = reArrayFiles ($_FILES['file']);
$error = 0;
foreach ($file_ary as $file) {
// Test a file is uploaded for each input
if ($file['size'] == 0 || empty ($file['name'])) {
$error = 1;
break;
// Note: If not all input slots are required to be filled,
// replace the above with:
// continue;
// This will stop running this step of the loop here
// and start the next one.
}
// Test file format
if (!in_array ($file['type'], array (
'image/jpg', 'image/png',
'image/jpeg', 'image/gif')) {
$error = 2;
break;
}
}
if (!$error) { // True is returned if value is not 0;
$newpath = 'photos/'.time();
foreach ($file_ary as $file) {
$res = #move_uploaded_file($file['tmp_name'],
$newpath.'-'.$file['name']);
unlink ($file['tmp_name']);
if (!$res) {
$error = 3;
break;
}
}
}
if (!$error) {
$res = mysql_query(' ... insert query ... ');
if (!$res) {
$error = 4;
}
}
if ($error) {
// If you wanted to be super thorough, you could loop through
// and make sure that if any files did get moved that they
// were deleted.
$msg = "";
switch ($error) {
case 1: $msg = 'File not found.'; break;
case 2: $msg = 'Incorrect file format.'; break;
case 3: $msg = 'Error moving uploaded file.'; break;
case 4: $msg = 'Database query failed. '.mysql_error(); break;
default: $msg = 'Error';
}
echo "<h2 class='error'>$msg</h2><a href='sell.php'>Try Again.</a>";
}
}
check out: http://www.php.net/manual/en/features.file-upload.multiple.php
One hard-coded way I've done it in the past is:
<input type="file" name="file_1" />
<input type="file" name="file_2" />
<input type="file" name="file_3" />
and then when submitted:
foreach($_FILES as $file) {
// file actions
}

Categories