I can't upload multiple images using PHP [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP - Upload multiple images
I want to upload multiple images using PHP and I am stuck. I have the code but it uploads only 1 image.
<?php
if (isset($_POST['newuser'])) {
if ((!empty($_POST['year'])) AND (!empty($_POST['make'])) AND (!empty($_POST['model'])) AND (!empty($_POST['engine'])) AND (!empty($_POST['mileage'])) AND (!empty($_POST['exterior'])) AND (!empty($_POST['interior'])) AND (!empty($_POST['transmission'])) AND (!empty($_POST['body'])) AND (!empty($_POST['fuel'])) AND (!empty($_POST['drive'])) AND (!empty($_POST['doors'])) AND (!empty($_POST['description']))) {
$year = htmlspecialchars($_POST['year']);
$make = htmlspecialchars($_POST['make']);
$model = htmlspecialchars($_POST['model']);
$engine = htmlspecialchars($_POST['engine']);
$mileage = htmlspecialchars($_POST['mileage']);
$exterior = htmlspecialchars($_POST['exterior']);
$interior = htmlspecialchars($_POST['interior']);
$transmission = htmlspecialchars($_POST['transmission']);
$body = htmlspecialchars($_POST['body']);
$fuel = htmlspecialchars($_POST['fuel']);
$drive = htmlspecialchars($_POST['drive']);
$doors = htmlspecialchars($_POST['doors']);
$description = htmlspecialchars($_POST['description']);
$target = "images/default.jpg";
$msg = "";
if (!empty($_FILES['fisier']['name'])) {
$target = "images/";
$target = $target . basename($_FILES['fisier']['name']);
$file_size = $_FILES['fisier']['size'];
$file_type = $_FILES['fisier']['type'];
$ok = 1;
if ($file_size > 2048000) {
echo "Too large";
$ok = 0;
}
if ($file_type == "application/octet-stream") {
echo "no PHP";
$ok = 0;
}
if ($ok == 0) {
echo "No file saved";
} else {
if (!move_uploaded_file($_FILES['fisier']['tmp_name'],$target)) {
$target = "images/default.jpg";
$msg = "No file saved. ";
}
}
}
require_once("mysql_connect.php");
$sql = "INSERT INTO astonmartin VALUES('','$year','$make','$model','$engine','$mileage','$exterior','$interior','$transmission','$body','$fuel','$drive','$doors','$description','$target','$target2','$target3','$target4','$target5','$target6')";
mysql_query($sql) or die(mysql_error());
$msg .= "";
header("Location: add_user.php?msg=$msg");
} else {
$error = "Complete form";
}
}
?>

I think you need first this function assoc, here: multidimensional for loops in php
And continue;
<?php
$allowed_types = array(
'image/gif',
'image/jpeg',
// add your mime types more
);
if (isset($_POST['newuser'])) {
if ((!empty($_POST['year'])) AND ...
// that gives an associative array
// i think it's more handy in your case
$files = assoc($_FILES['fisier']);
// now you have a files like
// tmp_name => d:\tmp\abs123, name => cats.jpg, size => 128 ..
// tmp_name => d:\tmp\abs254, name => dogs.jpg, size => 211 ..
// ... more code here
// and here, remove this line
if (!empty($_FILES['fisier']['name'])) {
// put this. yes 6, cos you want 6 pics
if (count($files) == 6) {
// loop over files
foreach ($files as $i => $file) {
// create targets, securely
$targets[$i] =
'images/'. preg_replace('~[^\w\d\.]~i', '',
basename($file['name']));
// check some errors
if ($file['error'] == 0 && $file['size'] < 2048000
// check file type
&& in_array($file['type'], $allowed_types)) {
if (!move_uploaded_file(
$file['tmp_name'], 'images/'. $file['name'])) {
$targets[$i] = 'images/default.jpg';
// collect messages
$messages[] = $file['name'] . ' not saved!';
}
}
}
}
// and creating target 1 2 3 ...
$targets_string = '';
if (!empty($targets)) {
// this provides: '$target', '$target2', '$target3' ...
$targets_string = "'". join("', '", $targets) ."'";
}
// ... more code here
// and sql part
$sql = "INSERT INTO astonmartin VALUES('', '$year', '$make', ..."
// add target string
. "'$description', $targets_string";
// ... more code here
// msg part
$msg = empty($messages) ? '' : join('', $messages);
header("Location: add_user.php?msg=$msg");
?>

Related

PHP read lines not working on some computers but works on most

So im reading an CSV file and splitting it apart to get email,name,last name, however this outputs differently on different computers in my platform, let's say when I upload the same file it reads 38 lines and save them. However in 2 specific computers it reads only 1.
Before I was reading only TEMP file, but now im saving it to a directory and reading from there, however the problem is still here, I compared the file size and is the same even the content.
Is this a PHP bug ?
<?php
global $user;
if(isset($_POST['submit'])) {
if ($_FILES['file']['tmp_name']) {
$nome = $_POST['nome'];
$file = $_FILES['file']['tmp_name'];
$user->criarLista($nome, $file);
} else {
$user->mensagem(1, "Não existe nenhum ficheiro");
}
}
?>
public function criarLista($nome,$file){
// ADDED TO SAVE THE FILE IN THE SYSTEM AND READ FROM IT
if(file_exists("uploads/lista.txt")){ unlink("uploads/lista.txt"); }
move_uploaded_file($file, "uploads/lista.txt");
$file = file_get_contents("uploads/lista.txt");
$user = $this->user;
$get = $this->connect->query("SELECT * FROM users WHERE email = '$user'");
$fetch = $get->fetch_array(MYSQLI_ASSOC);
$user_id = $fetch['id'];
if($insert = $this->connect->prepare("INSERT INTO lista(user_id,nome) VALUES(?,?)")){
$insert->bind_param("is", $user_id,$nome);
$insert->execute();
$list_id = $insert->insert_id;
$file = preg_replace('#\\x1b[[][^A-Za-z]*[A-Za-z]#', '', $file);
$file = strip_tags($file);
$lines = file("uploads/lista.txt");
$emails = array();
$fnames = array();
$lnames = array();
$linha = 0;
foreach($lines as $line) {
if($linha == 0){
}else{
echo $Linha."</br>";
if (strpos($line, ',') !== false) {
$arr = explode(",", $line);
// Email \ FNAME | LAST
$emailx = trim($arr[0]);
$emailx = trim(preg_replace("/[\\n\\r]+/", "", $emailx));
array_push($emails,$emailx);
if(isset($arr[1])){
$fname = trim($arr[1]);
$fname = str_replace('"','',$fname);
array_push($fnames,$fname);
}
if(isset($arr[2])){
$lname = trim($arr[2]);
array_push($lnames,$lname);
}
}else{
array_push($emails,trim($line));
}
}
$linha++;
}
array_map('trim', $emails);
array_map('trim', $fnames);
array_map('trim', $lnames);
$emails = implode(",",$emails);
$fnames = implode(",",$fnames);
$lnames = implode(",",$lnames);
if($insert_list = $this->connect->prepare("INSERT INTO listas(lista_id,email,primeiro_nome,ultimo_nome) VALUES(?,?,?,?)")){
$insert_list->bind_param("isss", $list_id,$emails,$fnames,$lnames);
$insert_list->execute();
$this->mensagem(2,"Lista adicionada com sucesso");
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}
FIXED this adding this on top of the function :
ini_set('auto_detect_line_endings',true);
I am not sure this is an 'answer' to what is going on, though it is what I had to do to fix an issue with a Mac user sending files.
What I found was that, every time he did an upload, it would send a .zip file, not just the file (like the PCs did). I did not have other Mac users to test against, so, again, I can't say this is exactly the issue you have, but I trust it will at least help in your search.
Note that I had to chop a lot of code out of this (where I was doing various other functions with the database, etc.), so this may not run directly, but I think I closed all the 'ifs' and such - or you can figure it out (if not, let me know and I'll go through it again).
Hope this helps!
$save_file = basename($_FILES["fileToUpload"]["name"]);
$zipfile='maps/'.$save_file; // location of a temp location (stops double uploads)
$alert_upload_file_exists = "Uploaded file exists!";
$alert_upload_successful = "UPLOAD SUCCESSFUL";
$action_failed_text = "Action FAILED";
if(file_exists($zipfile) && (empty($_GET['overwrite']) || $_GET['overwrite'] == 'false'))
die($alert_upload_file_exists);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $zipfile))
{
// I found this mac to be sending a .zip file, not a standard one..... :(
$uploadOk = 0;
$mac_file = 0;
if($basename = basename($_FILES["fileToUpload"]["name"],".zip"))
{
$zip = new ZipArchive;
if($zip->open($zipfile) === true){
// echo "basename is $basename<BR>";
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
// look for the file we really want (in our case, any sort of img file)
if($fileinfo['basename'] == $basename . '.png' || $fileinfo['basename'] == $basename . '.jpg' || $fileinfo['basename'] == $basename . '.gif') {
$imgfile = $_GET['loc_data_id'].".".$fileinfo['extension'];
$files[]=$fileinfo['basename'];
// echo "file added to the list <BR>";
}
// echo "filename is $filename, basename is ->".$fileinfo['basename']."<- fileinfo = ";print_r($fileinfo);
// CHECK TO SEE IF THIS WAS THE 'WEIRD' MAC FILE
if($fileinfo['basename'] == "__MACOSX")
$mac_file = 1;
// echo "mac_file is $mac_file ";
}
if(($imglist = array_keys(array_flip(preg_grep('/^.*\.(jpg|jpeg|png|gif)$/i',$files))))
{
// echo "imglist = ";print_r($imglist);
// echo "files = ";print_r($files);
foreach($files as $key => $value)
{
if ($imglist[0]==$value) {$file = $imgfile;}
$upgrade += file_exists('maps/'.$file);
// echo "imgfile is $imgfile, file is $file upgrade is $upgrade and value is ".$basename."/".$value." ............";
// more 'FUNNY BUSINESS' to work the Mac file....
if($mac_file){
$extracted = $zip->extractTo('maps/',$basename."/".$value);
rename("maps/$basename/$value","maps/$file");
}
else {
$extracted = $zip->extractTo('maps/',$value);
rename("maps/$value","maps/$file");
}
}
// AND A BIT MORE.....
if($mac_file){
rmdir ("maps/$basename");
}
$zip->close();
$imgcount=0;$mapcount=0;$uploadOk=1;
$html = file_get_html('maps/'.$mapfile);
$imgck = strpos($html,'<img ');
if(($imgck===false) || $imgck<>0) {
$uploadOk += 2;
}
// echo "uploadOk is $uploadOk<br>";
if($uploadOk==1)
{
$mapname = pathinfo('maps/'.$mapfile);
// echo "mapfile is $mapfile, mapname = ";print_r($mapname);
}
}
else $uploadOk += 20;
}
}
if($uploadOk==1) echo basename($_FILES["fileToUpload"]["name"])." ".$alert_upload_successful;
else echo $action_failed_text . " ".$uploadOk;
// delete the original .zip file (and any that are in the 'maps/' folder)
array_map('unlink', glob("maps/*.zip"));
}
else
{
echo "Sorry, there was an error uploading your file.";
echo "temp name is " . $_FILES["fileToUpload"]["tmp_name"]. " save file is ". $save_file."<br>";
}

PHP/MySQL - Data entered twice when doing single upload

I am trying to upload image to database MySQL. But I have a problem, when I am trying to upload one image, the image inserted twice.
For example:
I have "A.jpg" if I try to upload it
the inserted data will be like "A.jpg,A.jpg"
What I want in database "A.jpg"
and if I try to upload multiple images like "A.jpg,B.jpg and C.jpg"
the inserted data will be like "B.jpg,B.jpg,C.jpg,C.jpg"
What I want in database "A.jpg,B.jpg,C.jpg"
I've tried to search on google but no results, anyone can help me to resolve this problem ? Thanks
Here is my code :
include('koneksi.php');
date_default_timezone_set('Asia/Jakarta');
$id_user = $_POST['id_user'];
$caption = $_POST['caption'];
$files = [];
foreach($_FILES['files']['name'] as $i => $name) {
$name = $_FILES['files']['name'][$i];
$size = $_FILES['files']['size'][$i];
$type = $_FILES['files']['type'][$i];
$tmp = $_FILES['files']['tmp_name'][$i];
$explode = explode('.', $name);
$ext = end($explode);
$updatdName = $explode[0] . time() .'.'. $ext;
$path = 'gallery/';
$path = $path . basename( $updatdName );
if(empty($_FILES['files']['tmp_name'][$i])) {
$errors[] = 'Please choose at least 1 file to be uploaded.';
}else {
$allowed = array('jpg','JPG','jpeg','JPEG','gif','GIF','bmp','BMP','png','PNG');
$max_file_size = 1024*1024*2;; // 2MB
if(in_array($ext, $allowed) === false) {
$errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
}
if($size > $max_file_size) {
$errors[] = 'The file <b>'.$name.'</b> size is too hight.';
}
}
if(empty($errors)) {
// if there is no error then set values
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$errors = array();
if(!file_exists('gallery')) {
mkdir('gallery', 0777);
}
if(move_uploaded_file($tmp, $path)) {
echo '<script>window.history.back()</script>';
}else {
echo 'Something went wrong while uploading
<b>'.$name.'</b>';
}
}else {
foreach($errors as $error) {
echo '<p>'.$error.'<p>';
}
}
}
if(!empty($files)) {
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$names = implode(',', $files['file_name']);
$sizes = implode(',', $files['size']);
$types = implode(',', $files['type']);
$sql="INSERT into status VALUES(NULL, '$id_user', '$names','$caption','foto',NOW()); ";
mysqli_query($koneksi, $sql);
}
You're setting $files['file_name'][] in the while loop and also right before inserting into the DB. You just need to remove 2nd call to $files['file_name'][] = $updatdName;
Here is a simplified version of what you're doing.
<?php
$_FILES[] = ['name' => 'A'];
$_FILES[] = ['name' => 'B'];
$_FILES[] = ['name' => 'C'];
$files = [];
foreach ($_FILES as $file) {
$updatdName = $file['name'];
// You're setting it here
$files['file_name'][] = $updatdName;
}
if (!empty($files)) {
// And also here.
$files['file_name'][] = $updatdName;
$names = implode(',', $files['file_name']);
echo $names;
}

AWS S3 PhPdolphin integration

So my goal was it to implement Amazon S3 image uploads to the PhPDolphin script, unfortunately I've run into a few Issues, if I add the code in the script just doesn't load and since the script doesn't have an error log I'm clueless as to what went wrong, for licensing reasons I'm unable to publish the entire script here but I will post a snipped of the affected area.
/includes/classes.php [Default (Just a small snippet of the 4000 lines of code within this file)]
function validateMessage($message, $image, $type, $value, $privacy) {
// If message is longer than admitted
if(strlen($message) > $this->message_length) {
$error = array('message_too_long', $this->message_length);
}
// Define the switch variable
$x = 0;
if($image['name'][0]) {
// Set the variable value to 1 if at least one image name exists
$x = 1;
}
if($x == 1) {
// If the user selects more images than allowed
if(count($image['name']) > $this->max_images) {
$error = array('too_many_images', count($image['name']), $this->max_images);
} else {
// Define the array which holds the value names
$value = array();
$tmp_value = array();
foreach($image['error'] as $key => $err) {
$allowedExt = explode(',', $this->image_format);
$ext = pathinfo($image['name'][$key], PATHINFO_EXTENSION);
if(!empty($image['size'][$key]) && $image['size'][$key] > $this->max_size) {
$error = array('file_too_big', fsize($this->max_size), $image['name'][$key]); // Error Code #004
break;
} elseif(!empty($ext) && !in_array(strtolower($ext), $allowedExt)) {
$error = array('format_not_exist', $this->image_format, $image['name'][$key]); // Error Code #005
break;
} else {
if(isset($image['name'][$key]) && $image['name'][$key] !== '' && $image['size'][$key] > 0) {
$rand = mt_rand();
$tmp_name = $image['tmp_name'][$key];
$name = pathinfo($image['name'][$key], PATHINFO_FILENAME);
$fullname = $image['name'][$key];
$size = $image['size'][$key];
$ext = pathinfo($image['name'][$key], PATHINFO_EXTENSION);
// $finalName = str_replace(',', '', $rand.'.'.$this->db->real_escape_string($name).'.'.$this->db->real_escape_string($ext));
$finalName = mt_rand().'_'.mt_rand().'_'.mt_rand().'.'.$this->db->real_escape_string($ext);
// Define the type for picture
$type = 'picture';
// Store the values into arrays
$tmp_value[] = $tmp_name;
$value[] = $finalName;
// Fix the image orientation if possible
imageOrientation($tmp_name);
}
}
}
if(empty($error)) {
foreach($value as $key => $finalName) {
move_uploaded_file($tmp_value[$key], '../uploads/media/'.$finalName);
}
}
// Implode the values
$value = implode(',', $value);
}
And then my edited version that is supposed to upload the images automatically to Amazon S3.
/includes/classes.php [edited] (the s3 code is on the far bottom of the snippet)
function validateMessage($message, $image, $type, $value, $privacy) {
// If message is longer than admitted
if(strlen($message) > $this->message_length) {
$error = array('message_too_long', $this->message_length);
}
// Define the switch variable
$x = 0;
if($image['name'][0]) {
// Set the variable value to 1 if at least one image name exists
$x = 1;
}
if($x == 1) {
// If the user selects more images than allowed
if(count($image['name']) > $this->max_images) {
$error = array('too_many_images', count($image['name']), $this->max_images);
} else {
// Define the array which holds the value names
$value = array();
$tmp_value = array();
foreach($image['error'] as $key => $err) {
$allowedExt = explode(',', $this->image_format);
$ext = pathinfo($image['name'][$key], PATHINFO_EXTENSION);
if(!empty($image['size'][$key]) && $image['size'][$key] > $this->max_size) {
$error = array('file_too_big', fsize($this->max_size), $image['name'][$key]); // Error Code #004
break;
} elseif(!empty($ext) && !in_array(strtolower($ext), $allowedExt)) {
$error = array('format_not_exist', $this->image_format, $image['name'][$key]); // Error Code #005
break;
} else {
if(isset($image['name'][$key]) && $image['name'][$key] !== '' && $image['size'][$key] > 0) {
$rand = mt_rand();
$tmp_name = $image['tmp_name'][$key];
$name = pathinfo($image['name'][$key], PATHINFO_FILENAME);
$fullname = $image['name'][$key];
$size = $image['size'][$key];
$ext = pathinfo($image['name'][$key], PATHINFO_EXTENSION);
// $finalName = str_replace(',', '', $rand.'.'.$this->db->real_escape_string($name).'.'.$this->db->real_escape_string($ext));
$finalName = mt_rand().'_'.mt_rand().'_'.mt_rand().'.'.$this->db->real_escape_string($ext);
// Define the type for picture
$type = 'picture';
// Store the values into arrays
$tmp_value[] = $tmp_name;
$value[] = $finalName;
// Fix the image orientation if possible
imageOrientation($tmp_name);
}
}
}
if(empty($error)) {
foreach($value as $key => $finalName) {
if (!class_exists('S3'))require_once('S3.php');
//AWS access info
if (!defined('awsAccessKey')) define('awsAccessKey', 'myaccesskey');
if (!defined('awsSecretKey')) define('awsSecretKey', 'mysecretkey');
//instantiate the class
$s3 = new S3(awsAccessKey, awsSecretKey);
S3::outObject(
'$tmp_value[$key]',
'zepstrca',
'.$finalName);',
S3::ACL_PUBLIC_READ
array(),
array(),
S3::STORAGE_CLASS_STANDARD
);
}
// Implode the values
$value = implode(',', $value);
}
And yes I did add my own access and secret key :)
Any help would be greatly appreciated and will be credited!
Links to the products and API used in this:
[PhPDolphin] [S3.php API on Github]
This is how you can use the library i am using, i hope it will fix your problems (make sure the folder on the bucket actually exists otherwise just upload something to the root of the bucket)
require_once 'S3.php';
$s3 = new S3(awsAccessKey, awsSecretKey);
$s3->putObjectFile('/folderOnServer/picture.jpg', awsBucket, '/folderOnBucket/newName.jpg');

Stripping Filename in PHP

I'm building a version control system in PHP. I almost have a fully working system and am currently adding features. My code below renames a file as "filename_Ver 0.01" and increments by .01 if the user selects a minor revision from the html selectbox. If it's a major revision, the file gets renamed as filename_Ver 1 and increments by 1 for each major version. If I combine both, let's say a major and a minor revision I end up with a file named "filename_Ver 1.01.ext"
Displaying the filename in a PHP table is easy enough but I'd like to optionally just display the version number say in a seperate table field called "Version". How would I strip that from the filename so I can add that to the database? I know I'd have to do something within the while loop to get what I want out. $file = $dr.$fName.'_'.'Ver '.$i.$ext; I want it to display something like the following:
FileName | Version
test_Ver 0.1 | 0.1
test_Ver 0.2 | 0.2
test_Ver 1 | 1
test_Ver 1.1 | 1.1
function update_file_name_major($file)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = substr($file,0,($dir+1));
$arr = explode('/',$file);
$fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext));
$exist = FALSE;
$i = 1;
while(!$exist)
{
$file = $dr.$fName.'_'.'Ver '.$i.$ext;
if(!file_exists($file))
$exist = TRUE;
$i++;
}
return $file;
}
function get_file_name_major_latest($file)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = substr($file,0,($dir+1));
$arr = explode('/',$file);
$fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext));
$exist = FALSE;
$i = 1;
while(!$exist)
{
$file = $dr.$fName.'_'.'Ver '.$i.$ext;
if(!file_exists($file)){
$exist = TRUE;
return $i;
}
$i++;
}
return 0;
}
function update_file_name_minor($file, $latest_major = 0)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = str_replace(end(explode("/",$file)), '', $file);
$arr = explode('/',$file);
$fName = current(explode(".",end(explode("/",$file))));
$exist = FALSE;
$i = (float) $latest_major. '.01';
while(!$exist)
{
$file = $dr.$fName.'_'.'Ver '.$i.$ext;
if(!file_exists($file))
$exist = TRUE;
$i += 0.01;
}
return $file;
}
if ( isset( $_POST['addfile'] ) ) {
// variables
define('UPLOAD_DIR', 'repository/');
$fileName = $_FILES['file'];
$file_type = $_FILES['file']['type'];
$projectname=$_POST['projectname'];
$comments=$_POST['comments'];
if($_POST['rev_type'] == 'Minor') {
// check for which action should be taken if file already exist
if(file_exists(UPLOAD_DIR . $fileName['name']))
{
$latest_major = 0;
if(update_file_name_major(UPLOAD_DIR.$fileName['name']) != UPLOAD_DIR.$fileName['name']){
$latest_major = get_file_name_major_latest(UPLOAD_DIR.$fileName['name']);
--$latest_major;
}
$updatedFileName = update_file_name_minor(UPLOAD_DIR.$fileName['name'], $latest_major);
move_uploaded_file($fileName['tmp_name'], $updatedFileName);
include 'db.php';
$updatedFileName2 = update_file_name_minor($fileName['name'], $latest_major);
$add = mysql_query("INSERT INTO `myversions`(filename, filetype, projectname, comments, created)
VALUES ('$updatedFileName2', '$file_type','$projectname','$comments', NOW())");
echo "You have successfully uploaded and renamed the file as a minor revision.";
}
else
{
move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);
echo "You have successfully uploaded the file.";
}
}
elseif($_POST['rev_type'] == 'Major') {
// check for which action should be taken if file already exist
if(file_exists(UPLOAD_DIR . $fileName['name']))
{
$updatedFileName = update_file_name_major(UPLOAD_DIR.$fileName['name']);
move_uploaded_file($fileName['tmp_name'], $updatedFileName);
include 'db.php';
$updatedFileName2 = update_file_name_major($fileName['name']);
$add = mysql_query("INSERT INTO `myversions`(filename, filetype, projectname, comments, created)
VALUES ('$updatedFileName2', '$file_type','$projectname','$comments', NOW())");
echo "You have successfully uploaded and renamed the file as a major revision.";
}
else
{
move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);
echo "You have successfully uploaded the file.";
}
}
} //main if

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