Multiple Image insert taking extra one row after each insert - php

Here I am using this php code for insert multiple images in one field in database table but after insert a row is taking one extra row after each insert .......Help me to solve this issue..
Thank you Advance.
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
/*if(isset($_REQUEST['submit']))
{
$pname=$_FILES['image']['name'];
$tmp_name=$_FILES['image']['tmp_name'];
move_uploaded_file($tmp_name."photo/".$pname);
$fileext = pathinfo($pname, "photo/");
$fileext = strtolower($fileext);
}*/
$uploads_dir = 'photo/';
//$images_name ="";
foreach ($_FILES["image"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image"]["tmp_name"][$key];
$name = $_FILES["image"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$images_name =$images_name.$name.",";
}
}
$sql=mysql_query("INSERT INTO multiimg(image) values('".$images_name."')");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function addmore(num)
{
if(num==1)
{
document.getElementById('field2').style.display='block';
document.getElementById('ni1').style.display='block';
return false;
}
else if(num==2)
{
document.getElementById('field3').style.display='block';
return false;
}
}
</script>
</head>
<body>
<form enctype="multipart/form-data" name="" action="" method="post">
<div id="field1">Enter One Image :<input type="file" name="image[]" id="img1"/>addmore...</div>
<div id="field2" style="display:none;">Enter Two Image :<input type="file" name="image[]" id="img2"/>add more...</div>
<div id="field3" style="display:none;">Enter Three Image :<input type="file" name="image[]" id="img3"/>addmore...</div>
<div id="field4" style="display:none">Enter Forth Image :<input type="file" name="image[]" id="img4"/>addmore...</div>
<input type="submit" name="submit"/>
</form>
</body>
</html>

please check if the form is posted then do the insert ,else while loading the page a row will be inserted in table with empty data
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
if(isset($_POST['submit'])){
$uploads_dir = 'photo/';
//$images_name ="";
foreach ($_FILES["image"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image"]["tmp_name"][$key];
$name = $_FILES["image"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$images_name =$images_name.$name.",";
}
}
$sql=mysql_query("INSERT INTO multiimg(image) values('".$images_name."')");
}
?>

Related

uploading zip files with PHP, undefined index

I'm having issues uploading zip files and can't seem to find an answer.
Index.php
<form id="convertFile" action="convert.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input name="upload" type="file" id="inputFile">
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
</form>
convert.php:
if(isset($_FILES)){
echo $_FILES['upload']['name'];
}else{
echo json_encode(array('status'=>'error'));
}
When I upload a zip file, I get: Notice: Undefined index: upload in C:\wamp\www\xmlconverter\convert.php on line 3
This is what chrome shows in the post header:
------WebKitFormBoundaryuFNy5dZtFj7olmD5
Content-Disposition: form-data; name="zip_file"; filename="123.zip"
Content-Type: application/x-zip-compressed
------WebKitFormBoundaryuFNy5dZtFj7olmD5--
This works on any other major file format, but can't get it to read the zip file. If I var_dump $_FILES or $_POST they are empty.
What am I missing? Why does all other files work but zip does not.
Thank you
using wamp and php 5.5.12
Where is your zip file type definition?
Anyways, let say this was the html form to upload zip files you'd have the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
On the server-side script which handles the post you'd have:
<?php
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = "/home/var/yoursite/httpdocs/".$filename; // change this to the correct site path
if(move_uploaded_file($source, $target_path)) {
//if you also wanted to extract the file after upload
//you can do the following
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("/home/var/yoursite/httpdocs/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
?>
I used a script very similar to one posted by #unixmiah without issue on my cPanel based server. Worked great (and has for year now) but ran into issue of error "PHP, undefined index" when using locally with wamp.
Here is the mod that worked for me:
<?php
function rmdir_recursive($dir) {
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
rmdir($dir);
}
if(!empty($_FILES)){
//added above to script and closing } at bottom
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "<b>The file you are trying to upload is not a .zip file! Please try again...</b>";
}
$target_path = "somedir/somesubdir/".$filename; // change this to the correct site path
if(move_uploaded_file($source, $target_path)) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("somedir/somesubdir/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "<h2>ZIP file was uploaded and content was replaced!</h2>";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>QikSoft ZIP Upper</title>
</head>
<body>
<?php if(!empty($message)) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label><h3>Upload Your ZIP:</h3> <input type="file" name="zip_file" /></label>
<br /><br />
<input type="submit" name="submit" value="START UPLOAD" />
</form>
</body>
</html>
Also note that the echo message has been changed:
<?php if(!empty($message)) echo "<p>$message</p>"; ?>
One thing that does not work is file restriction. Currently allows other types besides ZIP. Anyone with fix, be greatly appreciated.
It's echo $_FILES['upload']['tmp_name'];
Try checking and adjusting the post_max_size value in your php.ini file, this worked for me as the default is 3M, raised the value to 128M and everything was peachy

Multiple file uploads issue

I have a simple code to upload multiple images that uploads the image to a folder and saves the path to the database. The problem is I have 3 browse buttons. The script only uploads the files and saves the path to the database when all the three browse buttons are selected with images. But when I select only 1 image to upload the script does not works. What is the matter?
Here is my current script.
<?php
include'includes/db.php';
if(isset($_POST['submit'])){
$extension = substr($_FILES['photo1']['name'],
strrpos($_FILES['photo1']['name'], '.'));
$extension = substr($_FILES['photo2']['name'],
strrpos($_FILES['photo2']['name'], '.'));
$extension = substr($_FILES['photo3']['name'],
strrpos($_FILES['photo3']['name'], '.'));
$extension = strtolower($extension);
echo $extension;
if( $extension == ".jpg" || $extension == ".jpeg" || $extension == ".gif" || $extension == ".png" )
{
$img1=$_FILES['photo1']['name'];
$img2=$_FILES['photo2']['name'];
$img3=$_FILES['photo3']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp1=$_FILES['photo1']['tmp_name'];
$temp2=$_FILES['photo2']['tmp_name'];
$temp3=$_FILES['photo3']['tmp_name'];
$limit_size = 1024000;
$size_in_kb = 1024;
$max_size = $limit_size/$size_in_kb;
if($size > $limit_size)
{
echo "<script>location.replace('test.php?err=File size exceeds $max_size KB')</script>";
}
else
{
move_uploaded_file($temp1,"images/".$img1);
move_uploaded_file($temp2,"images/".$img2);
move_uploaded_file($temp3,"images/".$img3);
$sql2="INSERT INTO ad_images(image1, image2, image3)VALUES('$img1', '$img2', '$img3')";
$res2=mysql_query($sql2);
if($res2){
echo "<script>location.replace('test.php?success=Product added successfuly')</script>";
}else{
echo "<script>location.replace('test.php?vlx=Error. Try Again...')</script>";
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Script Testing</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<p> Upload Image<br />
<input type="file" name="photo1" id="photo"><br />
<input type="file" name="photo2" id="photo"><br />
<input type="file" name="photo3" id="photo"><br />
<input type="submit" name="submit" id="submit" value="Add Product" style="margin-top: 25px; margin-left: 335px;"/>
</p>
</body>
</html>
I don't get whats wrong in my code everything seems to be fine. Please help.
************ SOLVED ***************
I was using the same variable extension. Now solved.
Here is my new code.
<?php
include'includes/db.php';
if(isset($_POST['submit'])){
$extension1 = substr($_FILES['photo1']['name'],
strrpos($_FILES['photo1']['name'], '.'));
$extension2 = substr($_FILES['photo2']['name'],
strrpos($_FILES['photo2']['name'], '.'));
$extension3 = substr($_FILES['photo3']['name'],
strrpos($_FILES['photo3']['name'], '.'));
$extension1 = strtolower($extension1);
echo $extension1;
$extension2 = strtolower($extension2);
echo $extension2;
$extension3 = strtolower($extension3);
echo $extension3;
if( $extension1 == ".jpg" || $extension1 == ".jpeg" || $extension1 == ".gif" || $extension1 == ".png" ||
$extension2 == ".jpg" || $extension2 == ".jpeg" || $extension2 == ".gif" || $extension2 == ".png" ||
$extension3 == ".jpg" || $extension3 == ".jpeg" || $extension3 == ".gif" || $extension3 == ".png" )
{
$img1=$_FILES['photo1']['name'];
$img2=$_FILES['photo2']['name'];
$img3=$_FILES['photo3']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp1=$_FILES['photo1']['tmp_name'];
$temp2=$_FILES['photo2']['tmp_name'];
$temp3=$_FILES['photo3']['tmp_name'];
$limit_size = 1024000;
$size_in_kb = 1024;
$max_size = $limit_size/$size_in_kb;
if($size > $limit_size)
{
echo "<script>location.replace('test.php?err=File size exceeds $max_size KB')</script>";
}
else
{
move_uploaded_file($temp1,"images/".$img1);
move_uploaded_file($temp2,"images/".$img2);
move_uploaded_file($temp3,"images/".$img3);
$sql2="INSERT INTO ad_images(image1, image2, image3)VALUES('$img1', '$img2', '$img3')";
$res2=mysql_query($sql2);
if($res2){
echo "<script>location.replace('test.php?success=Product added successfuly')</script>";
}else{
echo "<script>location.replace('test.php?vlx=Error. Try Again...')</script>";
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Script Testing</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<p> Upload Image<br />
<input type="file" name="photo1" id="photo"><br />
<input type="file" name="photo2" id="photo"><br />
<input type="file" name="photo3" id="photo"><br />
<input type="submit" name="submit" id="submit" value="Add Product" style="margin-top: 25px; margin-left: 335px;"/>
</p>
</body>
</html>
because u take the same variable $extension and if the third browse field will not be choosen , after submit it will be blank and it will not entered into the upload if condition. If u will browse only from third browse button then that single file will be uploaded.
You can use multiple attribute to upload multiple files throw a single browse button eg
<input type="file" name="img" multiple>
You can use ctrl to select multiple images

Uploaded images not in image folder

I just made a file upload code and I was wondering why the file upload wasn't working? I checked the permission of my image folder in localhost and that seems to be ok. I don't know where the problem exactly is. Any ideas?
<?php
require "config.php";
require "functions.php";
require "database.php";
if(isset($_FILES['fupload'])){
$filename = addslashes($_FILES['fupload']['name']);
$source = $_FILES['fupload']['tmp_name'];
$target = $path_to_image_directory . $filename;
$description = addslashes($_POST['description']);
$src = $path_to_image_directory . $filename;
$tn_src = $path_to_thumbs_directory . $filename;
if (strlen($_POST['description'])<4)
$error['description'] = '<p class="alert">Please enter a description for your photo</p>';
if($filename == '' || !preg_match('/[.](jpg)|(gif)|(png)|(jpeg)$/', $filename))
$error['no_file'] = '<p class="alert">Please select an image, dummy! </p>';
if (!isset($error)){
move_uploaded_file($source, $target);
$q = "INSERT into photo(description, src, tn_src)VALUES('$description', '$src','$tn_src')";
$result = $mysqli->query($q) or die (mysqli_error($myqli));
if ($result) {
echo "Succes! Your file has been uploaded";
}
createThumbnail($filename);
}
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Upload</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1>My photos</h1>
<ul><?php getPhotos(); ?></ul>
<h2>Upload a photo</h2>
<form enctype="multipart/form-data" action="index.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="fupload" /><br/>
<textarea name="description" id="description" cols="50" rows="6"></textarea><br/>
<input type="submit" value="Upload photo" name="submit" />
</form>
<?php
if (isset($error["description"])) {
echo $error["description"];
}
if (isset($error["no_file"])) {
echo $error["no_file"];
}
?>
</body>
</html>
Please make sure that you appended directory separator in $path_to_thumbs_directory.
And you don't need to use addslashes to $filename.

Mysqli 2 records being created with one insert

I am using the following form to create a photo album, it submits the data to a processing script which then deals with the files and enters data into the database.
THIS IS THE SUBMIT FORM :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create New Album</title>
</head>
<body>
<p>Create New Album</p>
<form action="createnewalbumsubmit.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<input type="hidden" value="<?php echo substr(md5(time() * rand()),0,10); ?>" name="albumid" id="albumid" />
<input type="hidden" value="<?php echo date("Y-m-d"); ?>" name="datecreated" id="datecreated" />
<input type="hidden" value="yes" name="isalbum" id="isalbum" />
<p>
<label for="albumname">Album Name</label>
<input type="text" name="albumname" id="albumname" />
</p>
<p>
<label for="albumthumbnail">Album Thumbnail Image</label>
<input type="file" name="albumthumbnail" id="albumthumbnail" />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Submit" />
</p>
</form>
</body>
</html>
THIS IS THE DATA PROCESSING SCRIPT, IT IS USING THE VEROT UPLOAD CLASS FOR DEALING WITH THE UPLOADED FILE AND THEN MYSQLI TO ADD DETAILS TO THE DATABASE :
<?php include("connect.php"); ?>
<?php
// Posted Data
if(isset($_POST['albumid'])){
$albumid = $_POST['albumid'];};
if(isset($_POST['datecreated'])){
$datecreated = $_POST['datecreated'];};
if(isset($_POST['isalbum'])){
$isalbum = $_POST['isalbum'];};
if(isset($_POST['albumname'])){
$albumname = $_POST['albumname'];};
//
require_once 'uploadclass/class.upload.php';
$file = new Upload($_FILES['albumthumbnail']);
if ($file->uploaded) {
// save uploaded image with a new name,
// resized to 100px wide
$albumthumbnail = substr(md5(time() * rand()),0,10);
$file->file_new_name_body = $albumthumbnail;
$file->image_resize = true;
$file->image_convert = 'jpg';
$file->image_x = 100;
$file->image_ratio_y = true;
$file->Process('albums/'.$albumid.'/thumbnail/');
$filename = $file->file_dst_name;
if ($file->processed) {
echo 'image renamed, resized x=100
and converted to jpg';
$file->Clean();
} else {
echo 'error : ' . $file->error;
}
}
mysqli_query($db,"INSERT INTO albums (`albumid`,`datecreated`,`isalbum`,`albumname`,`albumthumbnail`) VALUES ('$albumid','$datecreated','$isalbum','$albumname','$filename')");
?>
The problem I am having is that when I create a new record TWO records are being created in the database, one blank record with nothing at all in it and one valid record with all of the details of the added album in it.
It's because you're not checking if the form is being posted. Each time you land on the page it will run:
mysqli_query($db, "INSERT INTO albums (`albumid`,`datecreated`,`isalbum`,`albumname`,`albumthumbnail`) VALUES ('$albumid','$datecreated','$isalbum','$albumname','$filename')");
This is why you're getting a blank record. You need to surround your submit code with if (!empty($_POST)) { } as such:
<?php
include ("connect.php");
if (!empty($_POST)) {
// Posted Data
if (isset($_POST['albumid'])) {
$albumid = $_POST['albumid'];
};
if (isset($_POST['datecreated'])) {
$datecreated = $_POST['datecreated'];
};
if (isset($_POST['isalbum'])) {
$isalbum = $_POST['isalbum'];
};
if (isset($_POST['albumname'])) {
$albumname = $_POST['albumname'];
};
//
require_once 'uploadclass/class.upload.php';
$file = new Upload($_FILES['albumthumbnail']);
if ($file -> uploaded) {
// save uploaded image with a new name,
// resized to 100px wide
$albumthumbnail = substr(md5(time() * rand()), 0, 10);
$file -> file_new_name_body = $albumthumbnail;
$file -> image_resize = true;
$file -> image_convert = 'jpg';
$file -> image_x = 100;
$file -> image_ratio_y = true;
$file -> Process('albums/' . $albumid . '/thumbnail/');
$filename = $file -> file_dst_name;
if ($file -> processed) {
echo 'image renamed, resized x=100
and converted to jpg';
$file -> Clean();
} else {
echo 'error : ' . $file -> error;
}
}
mysqli_query($db, "INSERT INTO albums (`albumid`,`datecreated`,`isalbum`,`albumname`,`albumthumbnail`) VALUES ('$albumid','$datecreated','$isalbum','$albumname','$filename')");
}
?>

import .csv in mysql script php

i got a PHP script to import a file into my mysql database.
but when i try to use it i get this error:
File not found. Make sure you specified the correct path
but i did not even select a file this is my script:
<?php
include ('db_connect.php');
//connect to the database
//
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO test (nummer, branche) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
)
");
}
} while ($data = fgetcsv($handle,10000,",","'"));
//
//redirect
header('Location: import.php?success=1'); die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
any1 who can hlp me with this problem?
Re comment about do/while loop: no, I mean like this
$handle = fopen($file,"r");
if ($handle !== FALSE) {
while (!feof($handle)) {
$data = fgetcsv($handle,10000,",","'");
if ($data[0]) {
mysql_query("INSERT INTO test (nummer, branche) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."'
)
");
}
}
fclose($handle);
}

Categories