I am working on a script that uploads multiple images and saves the path to database to fetch the images in each record separately. The images are uploaded well but the image name in the database are stored in the following format uploads/image_name.png which should be actually just image_name.png. Moreover when I upload multiple images a separate record is created in the database for each image. I want to display them in the same field. Here is the code I am using to upload the file to the database using php.
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$img = implode('',$_FILES['file']['name']);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];
$title = (!empty($_POST['ad_title']))?$_POST['ad_title']:null;
$cat = (!empty($_POST['ad_cat']))?$_POST['ad_cat']:null;
$des = (!empty($_POST['ad_des']))?$_POST['ad_des']:null;
$name = (!empty($_POST['ad_name']))?$_POST['ad_name']:null;
$email = (!empty($_POST['ad_email']))?$_POST['ad_email']:null;
$phone = (!empty($_POST['ad_phone']))?$_POST['ad_phone']:null;
$state = (!empty($_POST['ad_state']))?$_POST['ad_state']:null;
//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 1024000) //Approx. 1mb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
$sql = "INSERT INTO ad_posting(img_name, ad_title, ad_cat, ad_des, ad_name, ad_email, ad_phone, ad_state)VALUES('$target_path', '$title','$cat','$des','$name','$email','$phone','$state')";
$frc = mysql_query($sql);
if ($frc){
echo "Success";
}else{
echo "Not Successful";
}
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
This is the javascript code i m using.
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
What is the error I am making? Please help me out solve the query.
from uploads/image_name.png to image_name.png.
$filename = 'uploads/image_name.png';
basename($filename);
in your sql
$sql = "INSERT INTO ad_posting(img_name, ad_title, ad_cat, ad_des, ad_name, ad_email, ad_phone, ad_state)VALUES('$target_path', '$title','$cat','$des','$name','$email','$phone','$state')";
if $target_path have the vale uploads/image_name.png then
$target_path = basename($target_path);
if you want the name of all images in the same field you can use implode().
Related
I just finished designing a basic site to upload some files to the server, and store the file names in a database for searching functions. I designed the site using the following tutorial: www.formget.com.
My problem is when I go to upload more than one file at a time, it appends the filenames together for a single file.
Example:
Filename Example
Here is my code for uploading the files:
$error = '';
if(isset($_POST['submit']))
{
$j = 0; // Variable for indexing uploaded image.
$target_path = 'uploads/'; // Declare path for uploaded images.
for($i = 0; $i < count($_FILES['file']['name']);$i++) // Loop to get individual element from the array.
{
$valid_ext = array('jpeg','jpg','png','gif'); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
$file_ext = end($ext); // Store extensions in the variable.
$filename = md5(uniqid());
$target_path = $target_path . $filename . '.' . $ext[count($ext) - 1]; // Set the target path with a new name of image.
if(($_FILES['file']['size'][$i] < 5000000) // Approx. 5MB files can be uploaded.
&& in_array($file_ext,$valid_ext))
{
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path))
{
// If file moved to uploads folder.
$success .= '<p class="success">('.$j.') Image uploaded successfully.</p>';
$date = date('Y-m-d H:i:s');
$stmt = $db->prepare('INSERT INTO uploads (filename,postdate,userid) VALUES (?,?,?)');
if($stmt)
{
$image = $filename . '.' . $ext[count($ext) - 1];
$stmt->bind_param('sss',$image,$date,$_SESSION['id']);
if($stmt->execute())
{
$success .= '<p class="success">('.$j.') Image added to database successfully.</p>';
}
else
{
$error .= '<p class="error">Error 34. Please contact the Site Administrator.</p>';
}
}
else
{
$error .= '<p class="error">Error 30. Please contact the Site Administrator.</p>';
}
}
else
{
$error .= '<p class="error">('.$j.') Please Try Again!</p>';
}
}
else
{
$error .= '<p class="error">('.$j.') Invalid file size or type.</p>';
}
$j = $j + 1; // Increment the number of uploaded images according to the files in the array.
}
}
Here is the jQuery:
var abc = 0; // Declare and define global increment value.
$(document).ready(function()
{
// To add new input file field dynamically, on click of "Add More Files" button, below function will be executed.
$('#add_more').click(function()
{
$(this).before($("<div/>",
{
id: 'filediv'
}).fadeIn('slow').append($("<input/>",
{
name: 'file[]',
type: 'file',
id: 'file'
}), $("<br/><br/>")));
});
// Following function will execute on change event of file input to select different file.
$('body').on('change', '#file', function()
{
if(this.files && this.files[0])
{
abc += 1; // Increment global variable by 1.
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("abcd" + abc).append($("<img/>",
{
id: 'img',
src: 'x.png',
alt: 'delete'
}).click(function()
{
$(this).parent().parent().remove();
}));
}
});
// To Preview Image
function imageIsLoaded(e)
{
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e)
{
var name = $(":file").val();
if(!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
Any input as to why it keeps appending the filenames together would be appreciated. Please note that in the database, the filenames are correct, just not on the server itself in the uploads directory.
You are not resetting $target_path inside your for loop and therefore string concatenating it while looping. Results will be like A, AB, ABC, ... This is the issue:
$target_path = $target_path . $filename . '.' . $ext[count($ext) - 1];
You could create two variables.
$target_path = 'uploads/';
outside of your for-loop and use something like
$move_to_target = $target_path . $filename . '.' . $ext[count($ext) - 1];
inside your for-loop and update your call of move_uploaded_file to pass $move_to_target instead of $target_path. Your database entries are not affected because you build up the filename again in $image - this however seems bad practice (redundant code), if you want to enhance your code define $image first and then create $move_to_target like this:
$move_to_target = $target_path . $image;
Im currently prepairing a web page and i need to make a form to upload image. It must be possible user to,
1 upload image by url ,
2 upload image by computer ,
3 upload image by drag and dropping.
I found those code separately from the internet.
But problem is how to combine all of those.
Html Form has 2 input box.
1 image name.
2 image url, upload image button
When user upload image it must be save to folder as name in 1st input box.also it name need to save in sql with the extention.
Can any one help me!
--------------html------------------
<input name="file_name" placeholder="File Name" class="form-control" type="text">
--------------php----------------
if (isset($_POST['add'])){
$softname=$_POST['file_name'];
}
require_once('ImageManipulator.php');
if ($_FILES['fileToUpload']['error'] > 0) {
echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
}
else {
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png','.bmp');
$fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
$newNamePrefix = 'ddownload_';
$manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
$newImage = $manipulator->resample(250, 250);
if(isset($_POST['img_url'])){
$url=$_POST['img_url'];
if (!empty($url)) {
$data = file_get_contents($url);
$manipulator = new ImageManipulator( $data);
// resizing to 200x200 image from url
$newImage = $manipulator->resample(250, 250);
}
// saving file to uploads folder
$manipulator->save('uploads/img/' . $newNamePrefix . $softname);
echo 'Thank you! ...';
} else {
echo 'You must upload an image...';
}
}
$source=$_POST['directlink'];
$u_image=$softname;
$filesize=$_POST['size'];
$type=$_POST['type'];
$description =$_POST['description'];
$insert_data="INSERT INTO `softwarelist`(`sid`, `softname`, `image`, `type`, `source`,`description`,`rating`,`filesize`,`user`) VALUES ('','$softname','$u_image','$type','$source','$description','','$filesize','');";
-------------end php----------
------------script for drag AND drop image-------
<script>
var files = evt.target.files;
var files = evt.dataTransfer.files;
var result = '';
var file;
for (var i = 0; file = files[i]; i++) {
// if the file is not an image, continue
if (!file.type.match('image.*')) {
continue;
}
reader = new FileReader();
reader.onload = (function (tFile) {
return function (evt) {
var div = document.createElement('div');
div.innerHTML = '<img style="width: 200px;" src="' + evt.target.result + '" />';
document.getElementById('filesInfo').appendChild(div);
};
}(file));
reader.readAsDataURL(file);
}
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
Here is the code I am using for multiple image upload for every entry in the database; id, image, name, date. By using this code, the image name is inserting correctly but I have a problem with the name field. I want to insert the name using $product_name= $_POST['pro_name']; but it only inserts 'array' in name field.
<?php
include('../config.php');
if (isset($_POST['submit'])) {
$product_name = $_POST['pro_name'];
$j = 0; // Variable for indexing uploaded image.
$target_path = "uploads/"; // Declaring Path for uploaded images.
for ($i = 0; $i < count($_FILES['file']['name']) && $product_name < count($product_name); $i++) {
// Loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
$file_extension = end($ext); // Store extensions in the variable.
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1]; // Set the target path with a new name of image.
$j = $j + 1; // Increment the number of uploaded images according to the files in array.
if (($_FILES["file"]["size"][$i] < 100000000) // Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
$finel_name = explode('/', $target_path);
$image_name_final = $finel_name[1];
$jajsj = "insert into spec_product set image='$image_name_final', name='$product_name'";
$janson = mysql_query($jajsj) or die(mysql_error());
// If file moved to uploads folder.
echo $j . ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else { // If File Was Not Moved.
echo $j . ').<span id="error">please try again!.</span><br/><br/>';
}
} else { // If File Size And File Type Was Incorrect.
echo $j . ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
The value is inserting as array because the variable $product_name is not a string but an array. Whenever an array is used where a string was expected e.g.: concatenation of a string or in your case the query statment: insert into spec_product set image='$image_name_final', name='$product_name'"; PHP will automatically convert the array into its default string value "Array".
Make sure that $product_name is not an array but a string which contains name of the product you want to insert in the table.
Regards,
Nitin Thakur
replace in your code
for ($i = 0; $i < count($_FILES['file']['name']); $i++)
{
and add this before your query execute
$product_name_final= $product_name[$i];
I have a form, upon submission, it will create a new directory, all images submitted along with the form will be upload in the said directory.
this is the shortened code.
mkdir('uploads/'.$name, 0777, true); //create directory
$count = count($_FILES['images']['tmp_name']); //count all uploaded files
for ($i=0; $i<$count; $i++)
{
//formatting
$file = $_FILES['images']['name'][$i];
$filename = strtolower($file);
$random = rand(0, 999); //Random number to be added to name.
$newfile = $random.$filename; //new file name
//upload
if (move_uploaded_file($newfile, "uploads/".$name."/".$newfile))
{
echo "uploaded";
} else {
echo " failed";
}
}
if i echo the directory echo "upload to =" . $teamdir."/".$newfile;
it shows the correct path /uploads/john/567banner_0.jpg
but the image aren't being uploaded.
bool move_uploaded_file ( string $filename , string $destination )
Your first parameter has to be the source so you have to give it the temp name assigned
by php.
In your case : $_FILES['images']['tmp_name'][$i]
I feel you should add
$_SERVER['DOCUMENT_ROOT'].'/path/to/uploads/
in image destination path
I have a script working to upload images without refreshing the page using jquery.form.js
Below is the PHP file that it kicks off the processes the file and when finished PHP creates an tag to show the image.
I now need a method to let JQUERY know the PHP file processing has completed. Is there a good way to connect these two?
I thought I could write something hidden to the page and have JQUERY look for this but I'm not sure if this is a B-Grade solution.
Any ideas? I can explain better if needed. thx
<?php
$type = $_POST['mimetype'];
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
foreach($_FILES as $file) {
$filename = $file['name'];
$filesize = $file['size'];
$filetmp = $file['tmp_name'];
}
// Script Variables
$errors=0;
$notAllowedFileType=0;
$exceededMaxFileSize=0;
$maxsize='10485760'; // 10MB Maximum Upload
$folder = 'images/';
$configWidth = 500;
$newFileName = 'success_story'.time().'.jpg';
// Process if No Errors
if(!$errors) {
// Variables
$uploadedFile = $filetmp;
$filename = basename( $filename);
$extension = strtolower(getExtension($filename));
// Convert the Specific Type of File into an Image
if($extension=='jpg' || $extension=='jpeg' ) {
$uploadedfile = $fullfilepath;
$src = imagecreatefromjpeg($uploadedFile);
}elseif($extension=='png') {
$uploadedfile = $fullfilepath;
$src = imagecreatefrompng($uploadedFile);
}else{
$uploadedfile = $fullfilepath;
$src = imagecreatefromgif($uploadedFile);
}
// Configure Width & Height
list($origWidth, $origHeight) = getimagesize($uploadedFile);
$configHeight = ($origHeight/$origWidth)* $configWidth;
// Create Empty File
$tmp = imagecreatetruecolor($configWidth, $configHeight);
imagecopyresampled($tmp, $src, 0,0,0,0,$configWidth,$configHeight,$origWidth,$origHeight);
imagejpeg($tmp, $_SERVER['DOCUMENT_ROOT'].$folder.$newFileName,90);
echo "<img src=".$folder.$newFileName." id=\"cropMeNowImage\">";
}
// Get Extension from Uploaded File
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) {return "";}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script>
(function() {
$(document).on('change','img#cropMeNowImage', function() {
alert('Ready to Crop');
});
})();
</script>
You need to use a callback function. Something like:
$(document).on('change','img#cropMeNowImage', function() {
$.post(url, {
vars_to_server : vars
}, function(process_done){
if (process_done)
alert("ready");
})
});
php must echo something recognizable by jquery in the var process_done
Instead:
echo "<img src=".$folder.$newFileName." id=\"cropMeNowImage\">";
you can echo 1 for success
This is the idea. It's totally possible. Specially for the common task of upload files via AJAX...
I recommend you: 5 Ways to Make Ajax Calls with jQuery
Take a look to http://github.com/valums/file-uploader I always use it to upload files.