$_FILES Uploads Only First File When Parsed - php

Ok guys this might seem like such a newbie issue but I've got looping issues that I just can't seem to work around. I'm simply trying to upload multiple images on my first project site.
When I posted this test php page up, it uploads all the files that I requested of it fine
; with all images that I wish to upload being uploaded at the directory intended.
<?php
$files = $_FILES['fileField'];
for ($x = 0; $x < count($files['name']); $x++)
{
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
move_uploaded_file($tmp_name, "property_images/$property_name/" . $name);
header("location: property_list.php");
exit();
}
?>
However when I tried including my parser, though it goes into the correct directory, only the first file gets uploaded
<?php
if(isset($_POST['property_name'])){
$property_name = mysql_real_escape_string($_POST['property_name']);
$district = mysql_real_escape_string($_POST['district']);
$address = mysql_real_escape_string($_POST['address']);
$property_type = mysql_real_escape_string($_POST['property_type']);
$sql = mysql_query("SELECT id FROM mydb WHERE property_name='$property_name' LIMIT 1");
$propertyMatch = mysql_num_rows($sql);
if($propertyMatch > 0)
{
echo 'Sorry, you tried to place a duplicate "Property Name" into the system, click here';
exit();
}
$sql = mysql_query("INSERT INTO mydb (property_name, district, address, property_type) VALUES ('$property_name','$ district','$address','$property_type')")or die (mysql_error());
if (!file_exists("property_images/$property_name"))
{
mkdir("property_images/$property_name");
}
$files = $_FILES['fileField'];
for ($x = 0; $x < count($files['name']); $x++)
{
$name = $files['name'][$x];
$tmp_name = $files['tmp_name'][$x];
move_uploaded_file($tmp_name, "property_images/$property_name/" . $name);
header("location: property_list.php");
exit();
}
}
?>
The count code works fine so I think its either these {} buggers or I need to get my eyes fixed. Any help would be uber appreciated.

you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at http://www.php.net/manual/en/features.file-upload.multiple.php
hope this will sure help you.

Related

Can we insert three images using three input type file in a single php form?

since i'm a newbie in PHP i'm asking this question. I can do a single insert image with a nice validation but i want to do this with 3 image. (leave the validation part). Just correct me if i'm wrong. Any help is appreciated.
Can i insert three images with the following format? It takes 7 days to ask next question, please help me out guys.
<?php
if (isset($_POST['upload']))
{
$fileName1 = $_FILES["uploaded_one"]["name"];
$fileTmp1 = $_FILES["uploaded_one"]["tmp_name"];
$fileType1 = $_FILES["uploaded_one"]["type"];
$fileSize1 = $_FILES["uploaded_one"]["size"];
$fileName2 = $_FILES["uploaded_two"]["name"];
$fileTmp2 = $_FILES["uploaded_two"]["tmp_name"];
$fileType2 = $_FILES["uploaded_two"]["type"];
$fileSize2 = $_FILES["uploaded_two"]["size"];
$fileName3 = $_FILES["uploaded_three"]["name"];
$fileTmp3 = $_FILES["uploaded_three"]["tmp_name"];
$fileType3 = $_FILES["uploaded_three"]["type"];
$fileSize3 = $_FILES["uploaded_three"]["size"];
if (!preg_match("/.(jpeg|jpg|png)$/i", $fileName1 || $fileName2 || $fileName3) )
$folder = "upload/";
$moveResult1 = move_uploaded_file($fileTmp1, "$folder/$fileName1");
$moveResult2 = move_uploaded_file($fileTmp2, "$folder/$fileName2");
$moveResult3 = move_uploaded_file($fileTmp3, "$folder/$fileName3");
$insert = "SQL INSERT QUERY TIRED TO TYPE";
$run = mysqli_query($db,$insert);
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="uploaded_one" />
<input type="file" name="uploaded_two" />
<input type="file" name="uploaded_three" />
<button name="upload">Submit</button>
</form>
And I think my preg_match() is giving error. is there a better way to do this?
You could create an array with the name suffix and loop through the array while you check each file separately.
foreach(['one', 'two', 'three'] as $item)
$name = $_FILES["uploaded_{$item}"]["name"];
$tmp = $_FILES["uploaded_{$item}"]["tmp_name"];
$type = $_FILES["uploaded_{$item}"]["type"];
$size = $_FILES["uploaded_{$item}"]["size"];
if (!preg_match("/.(jpeg|jpg|png)$/i", $name))
$folder = "upload/";
$result = move_uploaded_file($tmp, "$folder/$name");
}
Can you use just an input multiple for upload your 3 files un the same input ?

Insert image MYSQL based on radio button choice with PHP

I have a website. In this website I can upload images that are then placed into my SQL database. From here I select the images from the database and show them as thumbnails in the photo gallery, when clicked on the image it shows a large version where you can vote/like and comments etc.
Now what I am trying to do is make 3 category pages, basically 3x the photo gallery that shows the thumbnails.
I have 3 different tables in my database where I insert the images in to.
So I copied the photo gallery 3x and the original upload table in the database 3x.
How ever I do not want to create 3 upload.php files for each photo gallery.php file.
What I'm trying to do is have 3 radio button choices on my upload page and with the choice made there, the image gets uploaded into the matching database table (photo1, 2 or 3).
I have been trying to do this with Functions etc. but I just can't get it to work, I am probably doing something really simple, really stupid.
This is the code i have for the radio button and getting the image:
$titel = "Image";
$query = "SELECT * FROM `i268296_studie`.`fotos` ORDER BY foto_ID DESC";
$result = mysqli_query($conn, $query) or die("query error " . mysqli_error($conn) );
$fotos = array();
//create array from images in database
while($data = mysqli_fetch_assoc($result))
{
$fotos[] = array('src' => $data['src'], 'id' => $data['foto_ID']);
}
?>
<section id="upload">
<form method="post" action="upload.php" enctype="multipart/form-data">
<label for="bestand">Upload image:</label><br><br>
<input type="file" name="bestand" id="file"><br><br>
<label for="categorie"> Categorie: </label>
<input type="radio" name="cat" value="cat1">Portrait
<input type="radio" name="cat" value="cat2">Landscape
<input type="radio" name="cat" value="cat3">Other
<input type="submit" name="submit" value="Upload">
</form>
</section>
<?php
}
?>
<section class="images">
<?php
//show image thumbnails in photogallery
foreach($fotos as $foto)
{
?>
<img class="image" src="<?php echo 'upload/thumb/t_'.$foto['src'];?>">
<?php
}
?>
</section>
The above code I have 3 times (surrounded by HTML etc. as the photo gallery pages).
This is my Upload file (i'll leave most of the thumbnail making code out of it since it's only about the upload part).
$titel = "Image";
$dir='upload/';
$allowedExts = array("jpg", "jpeg", "gif", "png");
$answer= $_POST['cat'];
//Properties of the to be uploaded file
$fileName = $_FILES["bestand"]["name"]; //file name
$fileType = $_FILES["bestand"]["type"]; //file format
$fileSize = $_FILES["bestand"]["size"]; //file size
$tmpName = $_FILES["bestand"]["tmp_name"]; //temporary save location for file
$error = $_FILES["bestand"]["error"]; //error check for file
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
//select image from database and check if it already exists
$sql = "SELECT * FROM `i268296_studie`.`fotos` WHERE src = '$fileName'";
$result = mysqli_query($conn, $sql) or die("query error " . mysqli_error($conn) );
$data = mysqli_fetch_assoc($result);
$num_rows=mysqli_num_rows($result);
if($num_rows > 0)
{
echo 'File already exists <br>';
echo '<a href="fotogallerij.php">Return to homepage/a>';
}
else
{
// if file doesn't exist move to database, create thumbnail path
if (move_uploaded_file( $tmpName,$dir.$fileName))
{
function category($cat, $titel, $filename)
{
global $conn;
$query = "INSERT INTO `i268296_studie`.`$cat` (`titel`, `src`) VALUES ('$titel', '$fileName')"; //INSERT file into database
$result = mysqli_query($conn, $query) or die("query error " . mysqli_error($conn) );
}
$tname = 't_'.$fileName;
$tpath = $dir.'thumb/';
$tnamestate = $tpath.$tname;
$tptype = substr($fileType,6);
$ttype = "imagecreatefrom$tptype";
$name = $fileName;
$path = $dir;
$namestate = $path.$name;
$width = 100;
$height = 100;
list($width_orig, $height_orig) = getimagesize("$namestate");
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig)
{
$width = $height*$ratio_orig;
}
else
{
$height = $width/$ratio_orig;
}
How ever I am staring myself blind on how to fix it or where to place it so it works.
I hope my explanation and question is clear to you guys trying to help me, if not please let me know what I can change or do to help :)
edit:
The errors I am getting are:
Undefined variable: titel
Undefined variable: fileName
Undefined variable: conn
mysqli_query() expects parameter 1 to be mysqli, null given
When I do not pick a radio button but just upload it directly i just get 1 error:
Undefined index: cat
And it uploads it into the 3rd category
Edit 2:
Changed the function with the global $conn in it.
1 function category($cat, $titel, $fileName) {
2 global $conn;
3 $query = "INSERT INTO `i268296_studie`.`$cat` (`titel`, `src`) VALUES ('$titel', '$fileName')";
4 $result = mysqli_query($conn, $query) or die("query error " . mysqli_error($conn) );
5 }
1: you need these variables from the context calling the function
2: you need the global $conn variable in the function context to be able to run the query
3: use a function parameter for the table to upate call
4: it would be better to return results instead of breaking inside the function
The calling code would be like the following:
if ($answer == "cat1") {
category("fotos", $titel, $fileName); // or "foto2", $titel, $fileName .....
}
Please mind the comments about injection vulnerabilities.
Also read this: http://php.net/manual/it/language.variables.scope.php

PHP image upload and assignment of unique file name

Thank you in advance. I've checked similar questions and they are not helping because the work flow is set up differently.
Trying to get working:
1.user uploads image via form field
2.(SCRIPT 1) on other page script assigns unique name (SCRIPT 2), saves image file to server and image URL is uploaded to SQL. Goes to new page at end of script.
Problem is I'm not getting errors, the script runs and the new page opens but there is no file saved on the server and no data inserted into the SQL table (the entry date adds but not the image URL). My PHP.ini instructions far exceeds the size of the images I've been testing with. The folder location is chamode 0777. I'm posting the whole script because with getting errors it's hard to see where problem lies.
Image processing
<?php
require_once 'unique_gen.php';
$page_path = $_POST['page_path'];
$imgloc = "/avatars/";
//up one directory level
$store_loc = "..".$imgloc;
$link_loc = "http://www.webapge.com".$imgloc;
//Upload and characterize image file
if(isset($_FILES['image'])){
//File
$upload['image'] = $_FILES['image'];
//Verify
if ($upload['image']["error"] > 0){
die ("File Upload Error: " . $upload['image']["error"]);
}else{
//Upload
$img_ext = end(explode('.', $upload['image']['name']));
//Unique code generator
$image_name = implode('.', array(unique_generator(),$img_ext));
while(file_exists($store_loc.$image_name)){
$image_name = implode('.', array(unique_generator(),$img_ext));
}
$image_name = $upload['image']['name'];
//Move file to another location
move_uploaded_file($upload['image']["tmp_name"],$store_loc.$image_name) or exit("<br>Error, IMAGE file not moved!");
//Save location as link
$link_to_img = $link_loc.$image_name;
}
}else{
$image_name = "";
}
//connect to db
$con=mysqli_connect("localhost","usernm","pssword","dbName");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert to SQL
$sql="INSERT INTO comments (avatar, entry_date)
VALUES
('$_POST[link_to_image]', now())";
//verify insert
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
//direct to new page using variable
header('Location: http://www.weBsite.com/' . $page_path);
//close session
mysqli_close($con);
?>
Unique generator
<?php
function unique_generator($lot_size = 15){
$alpha_s = range('a', 'z');
$alpha_l = range('A', 'Z');
$numbers = range(0, 9);
$char = array_merge($alpha_l,$alpha_s,$numbers);
$code = "";
for($i = 0; $i < $lot_size; $i++){
$key = rand(0,count($char)-1);
$code .= $char[$key];
}
return $code;
}
?>
Try putting this at the top of your script:
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');
?>
This at the bottom:
<?php
print_r(array_keys(get_defined_vars()));
print_r(array_values(get_defined_vars()));
?>

Renaming multiple files when uploaded

I have a form that uploads multiple file. The php code that I am using works fine but I would like to rename the files also and don't know how to go about this. I think adding a time stamp to the name would be the best answer. Here is the working code so far:
/* FILE UPLOAD CODE */
{
$number_of_file_fields = 0;
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/uploads/'; //set upload directory
/**
* we get a $_FILES['file'] array ,
* we procee this array while iterating with simple for loop
* you can check this array by print_r($_FILES['file']);
*/
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
$number_of_file_fields++;
if ($_FILES['file']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['file']['name'][$i];
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $upload_directory . $_FILES['file']['name'][$i])) {
$number_of_moved_files++;
}
}
}
}
/* END FILE UPLOAD CODE */
Any help on what to add and where to accomplish this would be greatly appreciated.
If you want to give the same name to all the uploaded files, then you can get the name by using $_GET.
For example:
<form action="upload.php" method="post"> \\ this would send it to your page
<input type='text' size='30' name='filename'/>
<input type='submit' />
</form>
simply get the name using $_GET like this
$name = $_GET['filename'];
and now run your code but move the file with this name like this
move_uploaded_file($_FILES['file']['tmp_name'][$i], $upload_directory . $name[$i])
You can specify the new file name as the second parameter in move_uploaded_file()
For example:
move_uploaded_file($_FILES['file']['tmp_name'][$i], $upload_directory . "new_file_name");

Arrays from multiple upload form, Upload images then insert to database (PHP, MySQL)

Language: PHP / MySQL
I am going out of my mind, I really have to ask now... I have a multiple file upload form:
<input type="file" name="fileupload[]" multiple>
With the help of some Javascript, on each change made to this input, it appends a list of filenames, + a formatted string (grabbed from the filename) inside another input, so onchange we have a layout as shown below (assuming that we just added some images):
Almost similar to: http://jsfiddle.net/pxfunc/WWNnV/4/
// An HTML representation of such layout would be... (assuming that we added 3 images)
<input type="file" name="fileupload[]" multiple>
image-name-1.jpg <input type="text" value="Image Name 1" name="keyword[]">
justsome_file.png <input type="text" value="Justsome File" name="keyword[]">
some_Img-031.gif <input type="text" value="Some Img 031" name="keyword[]">
<input type="submit" value="Upload">
I have it this way because aside from uploading the files, I would also like to add them to my database, with a default title based on its filename (and the option to set/change this title for each image as I upload it). There is no problem with my form.
PROBLEM: My dilemma lies inside the PHP page where the form data/action is submitted.
I can only manage to either:
Upload correct images, but get same title for all
Insert correct titles, but get same image for all
Here is my PHP action page: (Currently uploading correct images, but having same title for all)
<?php
// CONNECT TO DATABASE...
// INCLUDE UPLOAD CLASS LIBRARY
include (dirname(__FILE__).'/lib/class.upload.php');
$files = array();
foreach ($_FILES['fileupload'] as $k => $l)
{
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
}
}
// create an array here to hold file names
$uploaded = array();
foreach ($files as $file)
{
$generate_name = rand(100,99999);
$generate_name_extra = rand(200,9999);
$filenamex = "COVER_PHOTO_".$generate_name.$generate_name_extra."_".time();
$filenamex_thumb = $filenamex."_thumb";
$handle = new upload($file);
if ($handle->uploaded) {
$this_upload = array();
///// 1 ////////////////////////////////////////////////////////////////////
$handle->file_new_name_body = $filenamex_thumb;
$handle->file_force_extension = true;
$handle->image_resize = true;
$handle->image_x = '300';
$handle->image_ratio_y = true;
$handle->jpeg_quality = '100';
// ABSOLUTE PATH BELOW
$handle->process($absoRoot.'covers/thumbs/');
////////////////////////////////////////////////////////////////////////////
if ($handle->processed) {
// store the image filename
$this_upload['image'] = $handle->file_dst_name; // Destination file name
$this_upload['body'] = $handle->file_dst_name_body; // Destination file name body
$this_upload['extension'] = $handle->file_dst_name_ext; // Destination file extension
$category_id = $_POST['cat'];
$hiddenvalues = explode ("|",$_POST["cat"]);
$category = $hiddenvalues[0];
$category_name = $hiddenvalues[1];
$sql = 'INSERT INTO cover (id, img, keyword, category_name, cat_id) VALUES ("", "'.$this_upload['image'].'", "'.$imagename.'", "'.$category_name.'", "'.$category.'")';
mysql_query($sql);
}
$handle->clean();
header("Location: ./upload.php");
$message = "";
} else {
echo ' file not uploaded to the wanted location';
echo ' Error: ' . $handle->error . '';
}
} ?>
(I use the Upload Class by Colin Verot to handle image uploads, and their FAQ tutorial to handle MULTIPLE image uploads on this page, under: What about multiple uploads?)
This would work perfect if I were just uploading images, however I added the functionality of adding each image data to my database. & This is where it gets confusing.
I'm sure the key is placing the SQL query inside the right foreach, or perhaps making another one, but I've tried that & it only gives me 1 good result for either the image upload or the title, never for both.
I need to upload the image to the site, then store its data (including image path) to my database.
Please look into my code and enlighten me how to solve this problem? A snippet clue would really be great for now as I am already very confused after having tried all I could think of. Thank you so much!
You aren't saving your $imagename variable to the $files array, you're just resetting it each time.
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
Should be something like:
$files[$i][$k] = array($v, $_POST['keyword'][$i]);
...
foreach ($files as $data) {
list($file, $imagename) = $data;
...
}
I do think one of your problems is your foreach:
$files = array();
foreach ($_FILES['fileupload'] as $k => $l)
{
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
}
}
So you are going through each of the fields assigning their value to the right file which fits this structure policy:
_FILES => array(
'name' => array(0 => 'file.txt'),
'size' => array(0 => 235)
)
Which is correct for multifiles but then you do:
$imagename = $_POST['keyword'][$i];
Which does not look right. You are overwriting the var each time with the last looked at which means you will only ever get one input vlaue.
When you're gathering the file information you're overwriting $imagename on every loop so it will be assigned to the last one. Try attaching it to the $files variable (hopefully this doesn't mess with the upload class you're using).
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$files[$i]['imagename'] = $_POST['keyword'][$i];
}
Then update your $sql string to reference that
$sql = 'INSERT INTO cover (id, img, keyword, category_name, cat_id)
VALUES ("", "'.$this_upload['image'].'", "'.$file['imagename'].'",
"'.$category_name.'", "'.$category.'")';

Categories