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;
Related
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.');
}
}
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().
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
So I am using AJAX to upload an image with this image manager tool I am building... all of a sudden its not working... I didn't change any code or anything.
The .php runs and uploads the image, but the events I want to fire after the json is encoded and sent back arent happening. :/
The console logs Uncaught SyntaxError: Unexpected token <
The same things is happening on another AJAX request, but is fine on the third one...
In the past when I get this error, it is a PHP syntax error, but I have not updated the .php in a while.. soooo Im stumped.
Here is my Javascript:
$("#chosenfile").change(function(){
if($(this).attr('name')) {
var data;
data = new FormData();
data.append('uploadedfile', $( '#chosenfile' )[0].files[0]);
$('#loader').css('display','block');
$.ajax({
url: '/includes/uploadimage.php',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function ( data ) {
//console.log(data); //returns a string of the data.
var image = JSON.parse(data); //parses the string into an object.
console.log(image); //logs the object.
if (image.error) {
alert(image.error);
$('#remove').click();
$('#loader').css('display','none');
} else {
if (image.link) { //If the image is uploaded and returned a link.
$('#remove').click();
$('#loader').css('display','none');
$('#scrollwindow').append("<div class='you'><img imgid='" + image.id + "' src='" + image.link + "' alt=''><span class='delete'>x</span></div>").fadeIn(200);
addToSlider(1);
};
}
}
});
}
});
Here is my PHP:
<?php
include '../includes/global.php'; // General Vars and Functions I use sitewide.
/* ------------------------- */
/* -- Lets Get that file! -- */
/* ------------------------- */
$file = $_FILES["uploadedfile"];
$Return = array();
$status = "failure";
/* ------------------------- */
/* - Okay, lets upload it! - */
/* ------------------------- */
$Return["type"] = $file["type"];
$target_path = "../uploads/"; // Define a folder to upload to
$allowedExts = array("jpeg", "jpg", "JPG", "JPEG", "image/jpg"); // Array of allowed extensions.
$extension = end(explode("/", $file["type"])); // Find extension.
$maxsize = 2097152; // Get Max file size from hidden field in form.
if ($file) {
if (in_array($extension, $allowedExts)) // If the extension is allowed.
{
if(($file["size"] < $maxsize)) { // If size is less then max file size.
$uploadResponse = "The file is a good size - ";
$target_path = $target_path . basename($file['name']); //Add file name string to upload folder destination string.
$imageLink = "http://scoutsamerica.com/uploads/" . basename( $file['name']); // This is the full link
if (file_exists($target_path)) { // If that file already exists, add a random integer to the end of it after a "_".
$uploadResponse .= "This file exists: " . $target_path;
$randomNum = rand(1, 9999999);
$crudparts = explode(".", $file["name"]); //split filename and extension again.
$exceptExt = $crudparts[0]; //Filename
$extension = $crudparts[1]; //Extension
$target_path = "../uploads/" . $exceptExt . "_" . $randomNum . "." . $extension; //rename it with the random number.
$imageLink = "http://scoutsamerica.com/uploads/" . $exceptExt . "_" . $randomNum . "." . $extension;
$uploadResponse .= " Path changed to: " . $target_path;
}
if(move_uploaded_file($file['tmp_name'], $target_path)) {
$uploadResponse .= "The file ". basename( $file['name']) . " has been uploaded to " . $target_path . "</br></br>";
} else {
$uploadResponse .= "There was an error uploading the file, please try again! </br>";
$uploadResponse .= "File size: " . ($file["size"] / 1024) . "kb</br>";
$uploadResponse .= "Max size: " . ($maxsize / 1024) . "kb";
}
$status = "success";
$Return["link"] = $imageLink;
/* ---------------------------------- */
/* - Time to upload that image, yo. - */
/* ---------------------------------- */
$imageSql = "INSERT INTO images (id, link, model_id, addedon) VALUES (".
"null, " .
PrepSQL($imageLink) . ", " .
PrepSQL($myId) . ", " .
PrepSQL($date) . ")";
mysql_query($imageSql) or die("Images: " . mysql_error());
} else {
$uploadResponse = "The file must less then " . ($maxsize / 1024) . "kb.";
$status = "failure";
$Return["error"] = $uploadResponse;
}
} else {
$uploadResponse = "The file must be a .jpg file.";
$status = "failure";
$Return["error"] = $uploadResponse;
}
} else {
$uploadResponse = "No Image.";
$status = "failure";
$Return["error"] = $uploadResponse;
}
/* ------------------------- */
/* - Lets Send it back :) - */
/* ------------------------- */
$Return["status"] = $status;
$Return["id"] = mysql_insert_id();
$Return["traveler"] = $file;
str_replace('\\/', '/', json_encode($Return));
echo json_encode($Return);
?>
RAW Response:
<script>
function hairEyesFind(haireyes){
if (haireyes == "blonde") {
return "z";
};
if (haireyes == "dirty blonde") {
return "b";
};
if (haireyes == "auburn") {
return "c";
};
if (haireyes == "brown") {
return "d";
};
if (haireyes == "black") {
return "e";
};
if (haireyes == "red") {
return "f";
};
if (haireyes == "blue2") {
return "g";
};
if (haireyes == "green2") {
return "h";
};
if (haireyes == "hazel2") {
return "i";
};
if (haireyes == "brown2") {
return "j";
};
}
</script>{"type":"image\/jpeg","link":"http:\/\/scoutsamerica.com\/uploads\/485604_10201093620571706_1239548317_n_5119195.jpg","status":"success","id":281,"traveler":{"name":"485604_10201093620571706_1239548317_n.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpX1qywo","error":0,"size":60368}}
unexpected token probably means you've got a corrupted JSON response from the server. Most likely it's an html-formatted PHP error/warning, embedded before/after the json data, e.g.
<p>PHP Warning: blah blahblah</p>[...json text here ...]
Since html is not valid json, you get that error message. So check out the RAW response from the server for that particular ajax call, and see what's coming back from the server.
A few things:
Why are you using \/ instead of just /?
Shouldn't the first return statement in the response be "a" not "z"?
Why do you have a block of JSON at the end of the response?
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.