loop for multi-image upload to sql DB - php

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
}

Related

Just Inserting Blank array() inside in mysql error

I want to store image name only inside mysql table but issue is that it's uploading blank array and giving error
array to string conversion.
if(isset($_POST['prd_submit']) && isset($_FILES['prd_image'])){
// Define Input Variables
$name = user_input($_POST['prd_name']);
$detail = user_input($_POST['prd_detail']);
$image = $_FILES['prd_image'];
$buy_link = user_input($_POST['prd_link']);
$price = user_input($_POST['prd_price']);
$category = $_POST['prd_category'];
$country = $_POST['prd_country'];
// Control Error Inputs
if(empty($name)){
$name_err = "Name is missing";
}
if(empty($detail)){
$detail_err = "Detail is missing";
}
if(empty($price)){
$price_err = "Price is missing";
}
if(empty($buy_link)){
$buy_link_err = "Link is missing";
}
// File Upload Function
$OutFiles = array();
foreach($image as $Index=>$Items){
foreach($Items as $Key=>$Item){
$OutFiles[$Key][$Index] = $Item;
}
}
if($OutFiles[0]['error']){
$image_err = $Errors[$OutFiles[0]['error']];
}else{
foreach($OutFiles as $Index=>$File){
$UploadDir = $DocRoot.'/upload/';
$imageName = $File['name'];
//GETTING FILE EXTENTION
$file_ext = explode('.',$imageName);
$file_ext = $file_ext[count($file_ext)-1];
//FILE NAME
$filename = (rand()).'-'.(time()).'.'.$file_ext;
//FILE EXTENTION ERROR
if($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg" && $file_ext != "gif"){
$error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}elseif(move_uploaded_file($File['tmp_name'],$UploadDir.$filename)){
$OutFiles[$Index]['name'] = $filename;
$uploadok++;
}elseif($uploadok == 0){
$error = "Sorry File is Not Upload";
}else{
$uploadok--;
$error = "Sorry File is Not Upload";
}
}
}
// Insert DB
if($name_err == '' && $detail_err == '' && $image_err == '' && $price_err == '' && $buy_link_err == ''){
$Code = 0;
try{
$insert_data = ("INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$image','$price','$buy_link','$category','$date')");
$insert_data = $conn->query($insert_data);
}catch(PDOException $E){
$Code = $E->getCode();
}
if($Code == 0){
$error = "<div class='alert alert-success'>Your Product Registration Request Has Submitted!</div>";
}elseif($Code == 23000){
$error = "<div class='alert alert-info'>Duplicate Entry</div>";
}else{
$error = "Unabel to enter data";
}
}
To much confuse what thing i'm doing wrong in it and if implode array but how i can implode i just need name only.
Change $image To $filename in your INSERT query.
Because, $image = $_FILES['prd_image']; is an array and you wanted to store the file name which is just uploaded to upload folder. So, use $filename which is uploaded using elseif(move_uploaded_file($File['tmp_name'],$UploadDir.$filename)){
Query
$insert_data = "INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$filename','$price','$buy_link','$category','$date')";
Uploading Multiple File : Move your INSERT Query inside foreach. It will insert into table on every successful upload.
foreach ($OutFiles as $Index => $File) {
$UploadDir = $DocRoot . '/upload/';
$imageName = $File['name'];
//GETTING FILE EXTENTION
$file_ext = explode('.', $imageName);
$file_ext = $file_ext[count($file_ext) - 1];
//FILE NAME
$filename = (rand()) . '-' . (time()) . '.' . $file_ext;
//FILE EXTENTION ERROR
if ($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg" && $file_ext != "gif") {
$error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
} elseif (move_uploaded_file($File['tmp_name'], $UploadDir . $filename)) {
$OutFiles[$Index]['name'] = $filename;
$insert_data = "INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$filename','$price','$buy_link','$category','$date')";
$insert_data = $conn->query($insert_data);
$uploadok++;
} elseif ($uploadok == 0) {
$error = "Sorry File is Not Upload";
} else {
$uploadok--;
$error = "Sorry File is Not Upload";
}
}
And, remove try/catch from below as now it's INSERTING on every UPLOAD.

File not uploading into database. Validation ok?

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

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

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");
?>

error handling and image type cat get it to work

I been working on this image script for too long now, and I still can't seem to get two things to work - the image type and error handling (if the fields are empty). I have the code for this, but every place I try to add it, it doesn't work.
my code:
$error_message="";
$MaxSize = "600000";
if (isset($_POST['btn_update'])){
function createRandomPassword() {
$chars = "abcde!##%^fghijkmnoABCDEFGHIJKpqrstuvwxyz023456789ABCDEFGHIJKLMNOPQRSTUVWZ!##%^&";
srand((double)microtime()*10000000);
$i = 0;
$pass = '' ;
while ($i <= 19) {
$num = rand() % 60;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
if ($_FILES['aMyUploads0']['size'] > $MaxSize || $_FILES['aMyUploads1']['size'] > $MaxSize || $_FILES['aMyUploads2']['size'] > $MaxSize)
{
$error_message = "ERROR: File too big!";
}
$aMyUploads = array();
$password = createRandomPassword();
foreach($_FILES as $aFile)
{
$newLocation = 'uploads/'.$password .$aFile["name"];
if(0 === $aFile['error'] && (false !== move_uploaded_file($aFile['tmp_name'], $newLocation)))
{
$aMyUploads[] = $newLocation;
}
else
{
$aMyUploads[] = '';
}
}
$error_message="Journal successfully saved.";
$connection = mysql_connect("localhost", "????", "???");
mysql_select_db("????", $connection);
$insert = "INSERT INTO photos (image1, image2, image3) VALUES
(
' ".$aMyUploads[0]." ',
' ".$aMyUploads[1]." ',
' ".$aMyUploads[2]." '
)";
$add_member = mysql_query($insert) or die(mysql_error());
}
code im trying to add with no luck:
//ERROR HANDLING CODE:
if(empty($aMyUploads[0]) || empty($aMyUploads[1]) || empty($aMyUploads[2]))
{
$error_message="Please fill in all fields.";
}
else
{
$error_message="Journal successfully saved.";
//IMAGE TYPE CODE:
$allowed_filetypes = array(".jpg", ".gif", ".jpeg", ".png");
$ext = substr($newLocation, strpos($newLocation,'.'), strlen($newLocation)-1);
if(!in_array($ext,$allowed_filetypes))
{
die('The file you attempted to upload is not allowed.');
}
Try this for checking required fields, inserted before the code that checks the file sizes.
// ERROR HANDLING CODE:
if (empty($_FILES) || empty($_FILES['aMyUploads0']) || empty($_FILES['aMyUploads1']) || empty($_FILES['aMyUploads2']))
{
// Handle error
}
And this for validating file types, inserted into your foreach.
// IMAGE TYPE CODE:
$allowed_filetypes = array("jpg", "gif", "jpeg", "png");
$ext = pathinfo($aFile['name'], PATHINFO_EXTENSION);
if (!in_array($ext, $allowed_filetypes))
{
// Handle error
}

PHP: Image uploader error

Im making an image uploader, but i get the error: Only JPG, JPEG and PNG are allowed image types.
The uploader doesn't get the extension right. What do i do wrong?
The function to get the extension is at line 33. Ad from line 59 is where im trying to get the extension.
<?php session_start(); if ($_SESSION['username']) {} else { header("location:index.php"); exit(); } ?>
<?php
include 'db_connect.php';
$uploadSubmit = mysql_real_escape_string($_POST['imageSubmit']);
if ($uploadSubmit)
{
if ($_FILES['image'])
{
$contents = file_get_contents($_FILES['image']['tmp_name']);
if (stristr($contents, "<?php") || stristr($contents, "system(") || stristr($contents, "exec(") ||
stristr($contents, "mysql") || stristr($contents, "include(") || stristr($contents, "require(") ||
stristr($contents, "include_once(") || stristr($contents, "require_once(") || stristr($contents, "echo'") || stristr($contents, 'echo"'))
{
echo 'Are you really trying to hack this site? Enjoy your upload b&.';
$sql = "INSERT INTO banned (ip) VALUES ('".$_SERVER['REMOTE_ADDR']."')";
$result = mysql_query($sql) or trigger_error(mysql_error()."".$sql);
die();
}
}
else
{
$sql = "SELECT * FROM banned WHERE ip='".$_SERVER['REMOTE_ADDR']."'";
$result = mysql_query($sql) or trigger_error(mysql_error()."".$sql);
$num_rows = mysql_fetch_row($result);
if ($num_rows[0] == 0)
{
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i)
{
return "";
}
$I = strlen($str) - $i;
$ext = substr($str,$i+1,$I);
return $ext;
}
define ("MAX_SIZE","5000");
$error = 0;
$file = $_FILES['image']['name'];
if ($file = '')
{
echo 'You didn\'t select an image to upload.';
$error = 1;
}
else
{
$filename = stripslashes($file);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))
{
echo 'Only JPG, JPEG and PNG are allowed image types.';
$error = 1;
}
else
{
$size = filesize($_FILES['image']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
echo 'The max allowed filesize is 5MB.';
$error = 1;
}
$time = time();
$newImageName = 'wally-'.$time.'.'.$extension.'';
$imageFullPath = 'images/'.$newImageName.'';
if (!$errors)
{
if (!move_uploaded_file($_FILES['image']['tmp_name'], $imageFullPath))
{
$error = 1;
}
}
if ($uploadSubmit && !$error)
{
include 'class.imageResizer.php';
$work = new ImgResizer($imageFullPath);
$work -> resize(125, "thumbs/".$newImageName."");
$uploader = $_SESSION['username'];
$sql = "INSERT INTO images (image, uploader, validated) VALUES ('$newImageName','$uploader','0')";
$result = mysql_query($sql) or trigger_error(mysql_error()."".$sql);
echo 'Your image has been uploaded and awaiting validation.';
echo 'The page will redirect in 2 seconds.';
echo '<meta http-equiv="Refresh" content="2;url=http://www.wallpapers.puffys.net">';
}
}
}
}
else
{
die("You are banned from uploading.");
}
}
}
?>
$i = strrpos($str,".");
if (!$i)
isn't a good way to test if the strrpos function returns a positive value.
You should use the === operator, like this :
$i = strrpos($str,".");
if ($pos === false)
Try using something like this:
$allowedExtensions = array("jpg","jpeg","png");
if (!in_array(end(explode(".",strtolower($file))),$allowedExtensions)) {
echo 'Only JPG, JPEG and PNG are allowed image types.';
$error = 1;
}

Categories