PHP Image Upload Via JQUERY - php

I'm trying to pass form data (Avatar & User ID) through a jQuery POST command, but it won't upload the file. Can someone please point me in the right direction as to what I might be doing wrong? Here is the form and script:
<form id="avatar">
<script>
$(document).ready(function()
{
var ok = true;
$('#avatarButton').click(function()
{
var id=$("#id").val();
var avatar = $("#avatar").val();
if(ok == true)
{
$('.avatarValidation').html("Uploading Avatar").removeClass("error").addClass("success");
jQuery.post("php/<?php echo $usertype; ?>/avatar.php", {
id:id,
avatar:avatar
}, function(data, textStatus){
if(data == 1){
$('.avatarValidation').html("Profile Updated").removeClass("error").addClass("success");
}
else if(data == 2){
$('.avatarValidation').html("Error").removeClass("success").addClass("error");
}
});
}
else
{
$('.avatarValidation').html("No").removeClass("success").addClass("error");
}
return false;
});
});
</script>
<table>
<tr>
<td class="textColumn profileColumn">Add Avatar:</td>
<td class="profileInput inputColumn"><input type="file" id="avatar" name="avatar" value="<?php echo $yourname; ?>"/></td>
</tr>
<tr>
<td colspan="2"><input type="hidden" name="id" id="id" value="<?php echo $yourid; ?>"></td>
</tr>
<tr class="buttonSpacer"></tr>
<tr>
<td colspan="2">
<input type="submit" class="submitButton" id="avatarButton" value="Upload Avatar" />
<span class="submitValidation avatarValidation"></span>
</td>
</tr>
</table>
</form>
And here is the PHP to which the form data is passed to:
<?php
$id= mysqli_real_escape_string($con, $_REQUEST["id"]);
$avatar= mysqli_real_escape_string($con, $_REQUEST["avatar"]);
if ($_FILES['$avatar']['error'] > 0) {
echo "2"; //Echo Error
} else {
// array of valid extensions
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
// get extension of the uploaded file
$fileExtension = strrchr($_FILES['$avatar']['name'], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
$newName = time() . '_' . $_FILES['$avatar']['name'];
$destination = 'avatar/' . $newName;
if (move_uploaded_file($_FILES['$avatar']['tmp_name'], $destination)) {
echo "1"; //Echo Success
}
} else {
echo "2"; //Echo Error
}
}
?>

You can try this plugin, it will take care of most of background work for you. They have PHP samples as well:
http://blueimp.github.io/jQuery-File-Upload/

Related

PHP using for or statement giving error

I am trying to write validation code when user upload file.
Condition : file size maximum 500kb and only doc and docx file
I use this code but not working properly.
I want to give visitor permission to upload cv in my website, with server side validation (PHP).
<html>
<head>
<title>Validation</title>
</head>
<body>
<?php
$msg = "";
$msgsize = "";
if(isset($_POST['add']))
{
$filename=$_FILES['resume']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
$uname = $_POST['uname'];
$uemail = $_POST['uemail'];
$uphone = $_POST['uphone'];
$resume = $_FILES['resume']['name'];
if($uname=="" || $uemail=="" || $uphone=="" || $resume=="")
{
$msg = "Please fill in all required fields!";
}
else if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$uemail))
{
$msg = "Invalid email format";
}
//echo $ext;
else if($ext != '.doc' or $ext != '.docx')
{
$msg = "Type Error";
}
else if($_FILES["resume"]["size"]>500000)
{
$msg = "Size error". $_FILES["resume"]["size"] . "Only 500KB Resume Allowed";
}
else
{
$msg = "GOOD";
}
}
?>
<div style="background:#FF6600; padding:10px;"><?php echo $msg . $msgsize; ?></div>
<form id="form1" enctype="multipart/form-data" name="form1" method="post" action="<?php $_PHP_SELF ?>">
<table width="700" border="1">
<tr>
<td width="178">Name</td>
<td width="506"><input name="uname" type="text" /></td>
</tr>
<tr>
<td>Email</td>
<td><input name="uemail" type="text" /></td>
</tr>
<tr>
<td>Phone</td>
<td><input name="uphone" type="text" /></td>
</tr>
<tr>
<td>Resume</td>
<td><input name="resume" value="60000000" id="resume" type="file" /></td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="add" id="add" value="Add">
</td>
</tr>
</table>
</form>
</body>
</html>
here you need to change
else if($ext != '.doc' AND $ext != '.docx') { //use AND instead of OR
$msg = "Type Error";
}
try this
$filename=$_FILES['resume']['name'];
if(substr($filename,-3)=='doc' || substr($filename,-4)=='docx'){
echo 'OK';
}
else{
echo "Upload Only DOC or Docx File";
}
I hope this should work
strpos() find the first occurance of string inside another string , so if a file name is like this :-
"blahfile-2.2-1.docx" you will get "2-1.docx" not "docx"
so it will not match, you should find occurance of string by method :-
strrpos() (case-sensitive) strripos() (case-insensitive)
it will give you correct ".docx"
some other problems seems :-
using $_FILES['resume'] without checking is that set or not
so should be something like this :-
if(!isset($_FILES['resume'])){
$msg = "File not selected !";
}
Second
$uname = $_POST['uname'];
$uemail = $_POST['uemail'];
$uphone = $_POST['uphone'];
$resume = $_FILES['resume']['name'];
shold be something like this :-
$uname = (isset($_POST['uname']) ? $_POST['uname'] : "";
$uemail = ...
$uphone = ...
$resume = ...
Thanks :)

unable to insert image into database

Unable to upload image into database. After submitting the form, I am getting this error:
There was an error uploading the data, please try again!
My code is given below please help me regarding this.
<?php
extract($_POST);
extract($_GET);
error_reporting(0);
?>
<html>
<head>
<!-- Date Picker Starts -->
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="js/script.js"></script>
<script>
$(document).ready(function() {
$(function() {
$(".datepicker").datepicker({ dateFormat: 'dd-mm-yy' });
});
});
</script>
<!-- Date Picker Ends -->
<script>
function getccname(val)
{
if(val == 'company')
{
document.getElementById("colname").disabled= true;
document.getElementById("course").disabled = true;
document.getElementById("year").disabled = true;
}
else if(val == 'college')
{
document.getElementById("comname").disabled = true;
document.getElementsByName("doj")[0].disabled= true;
document.getElementById("colname").disabled = false;
document.getElementById("course").disabled = false;
document.getElementById("year").disabled = false;
}
else
{
document.getElementById("comname").disabled = false;
document.getElementsByName("doj")[0].disabled= false;
document.getElementById("colname").disabled = false;
document.getElementById("course").disabled = false;
document.getElementById("year").disabled = false;
}
}
</script>
<!-- nice editor -->
<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
<script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script>
<!-- nice editor end -->
</head>
<body>
<?php
include("menu.php");
?><br>
<?php
include("database.php");
if(isset($_POST['submit']))
{
$uploadpath= 'upload/'; // directory to store the uploaded files
$max_size = 2000; // maximum file size, in KiloBytes
$alwidth = 900; // maximum allowed width, in pixels
$alheight = 800; // maximum allowed height, in pixels
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'jpeg', 'png'); // allowed extensions
if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1)
{
$timestamp = time();
$uploadpath = $uploadpath . $timestamp . basename( $_FILES['fileup']['name']); // gets the file name
$sepext = explode('.', strtolower($_FILES['fileup']['name']));
$type = end($sepext); // gets extension
list($width, $height)= getimagesize($_FILES['fileup']['tmp_name']); // gets image width and height
$err = ''; // to store the errors
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*1000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB.';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x '. $alheight;
// If no errors, upload the image, else, output the errors
if(is_uploaded_file($_FILES['fileup']['name']))
{
move_uploaded_file( $_FILES['fileup']['tmp_name'], $uploadpath) ;
$file =$uploadpath;
$name =$_POST["name"];
$fname =$_POST["fname"];
$gender =$_POST["gender"];
$email =$_POST["email"];
$date =$_POST["date"];
$mn =$_POST["mn"];
$pn =$_POST["pn"];
$address=$_POST["address"];
$idnum =$_POST["idnum"];
$ccname =$_POST["ccname"];
$colname=$_POST["colname"];
$course =$_POST["course"];
$year =$_POST["year"];
$comname=$_POST["comname"];
$doj =$_POST["doj"];
$result=mysql_query("insert into registration(file,name,fname,gender,email,date,mn,pn,address,idnum,ccname,colname,course,year,comname,doj)
values('$uploadpath','$name','$fname','$gender','$email','$date','$mn','$pn','$address','$idnum','$ccname','$colname','$course','$year','$comname','$doj')");
print_r($result);
echo "Inserted Successfully";
}
}
else
{
echo "There was an error uploading the data, please try again!";
}
}
?>
<form name="form" method="post" action="" onSubmit="submit;">
<center><table border="1" cellspacing="0" style="width:500px">
<tr>
<td><b>Image</td> <td><input type="file" name="fileup" id="fileup" size="25" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td></tr>
<tr>
<td>Father Name</td>
<td><input type="text" name="fname"></td></tr>
<tr><td>Gender</td>
<td><select name="gender">
<option value ="na">Select</option>
<option value ="Male">Male</option>
<option value ="Female">Female</option>
</td></tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td></tr>
<tr>
<td>Date Of Birth</td>
<td><input type="text" name="date" class="datepicker" required></td></tr>
<tr>
<td>Mobile Number</td>
<td><input type="text" name="mn"></td></tr>
<tr>
<td>Parent Number</td>
<td><input type="text" name="pn"></td></tr>
<tr>
<td>Address</td> <td><textarea name="address" rows="3" cols="50"></textarea></td>
</tr>
<tr>
<td>Coll/Comp ID Num</td>
<td><input type="text" name="idnum"></td></tr>
<tr><td>Company/College</td>
<td><select name="ccname" onchange="getccname(this.value);">
<option value ="na">Select</option>
<option value ="company">Company</option>
<option value ="college">College</option>
</td></tr>
<tr>
<td>College Name</td>
<td><input type="text" name="colname" id="colname"></td></tr>
<tr>
<td>Course</td>
<td><input type="text" name="course" id="course"></td></tr>
<tr>
<td>Year</td>
<td><input type="text" name="year" id="year"></td></tr>
<tr>
<td>Company Name</td>
<td><input type="text" name="comname" id="comname"></td></tr>
<tr>
<td>Date Of Join</td>
<td><input type="text" name="doj" class="datepicker"></td></tr>
<tr>
<td colspan="2" align="center"><input class="button" type="submit" name="submit" value="submit"/>
<input class="button" type="reset" name="Reset" value="Reset " /> </td>
</tr></center>
</table>
</form>
</body>
</html>
try this,Then include your insert query it will work enctype="multipart/form-data"
<form name="form" method="post" action="" onSubmit="submit;" enctype="multipart/form-data">
</form>
<?php
if(isset($_FILES['image']))
{
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$value = explode(".", $file_name);
$file_ext = strtolower(array_pop($value));
//$file_ext=strtolower(end(explode(".",$file_name))); -->this line wnt work bcoz only variable should be passed inside explode
$expensions= array("jpeg","jpg","png","csv");
if(in_array($file_ext,$expensions)== false)
{
$errors="Extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152)
{
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true)
{
move_uploaded_file($file_tmp,"upload/".$file_name);
**//include here insert query**
echo "Success";
}else
{
print_r($errors);
}
}
?>
1st. do not use mysql_* functions, use mysqli_* instead.
2nd. This is a very big security hole, if accept any data.
3rd. Whay do you create variables like this? $name=$_POST["name"];
So, when you want to insert the $_POST["name"] do something like this:
EDIT:
Try this. It will die, and will print out the query string for you. Try to copy that directly into the mysql, and comment the result.
function dbEscape($str) {
return mysql_real_escape_string($str);
}
$sql = "INSERT INTO registration(file,name,fname,gender,email,date,mn,pn,address,idnum,ccname,colname,course,year,comname,doj)
VALUES ('".dbEscape($uploadpath)."','". dbEscape($_POST["name"])."','". dbEscape($_POST['fname'])."','". dbEscape($_POST['genred'])."','". dbEscape($_POST['email'])."','". dbEscape($_POST['date'])."','". dbEscape($_POST['mn'])."','". dbEscape($_POST['pn'])."','". dbEscape($_POST['address'])."','". dbEscape($_POST['idnum'])."','". dbEscape($_POST['ccname'])."','". dbEscape($_POST['colname'])."','". dbEscape($_POST['course'])."','". dbEscape($_POST['year'])."','". dbEscape($_POST['comname'])."','". dbEscape($_POST['doj'])."')";
die($sql);
$result = mysql_query($sql);
Your form does not contain enctype="multipart/form-data" and is an essential part of uploading files.
Modify your form to read as:
<form name="form" method="post" enctype="multipart/form-data" action="" onSubmit="submit;">
that is the reason why your upload does not work.

File upload using jquery form plugin failure

I am trying to upload an image along with other form data to my database. I now have the following form:
<form method="post" action="newproduct.php" id="newproduct" enctype="multipart/form-data" >
<table>
<tr>
<td><label for="productName">Product Name:</label></td>
<td>
<input type="text" name='productName' id='productName' />
</td>
</tr>
<tr>
<td><label for="productNumber">Product Number:</label></td>
<td>
<input type="text" name='productNumber' id='productNumber' />
</td>
</tr>
<tr>
<td><label for="sflf"> SF / LF: </label></td>
<td>
<input type="text" name="sflf" id="sflf" />
</td>
</tr>
<tr>
<td><label for="file" >Image:</label></td>
<td>
<input type="file" name="file" id="file" />
</td>
</tr>
</table>
</form>
I am using the following jquery script to send the data to my newproduct.php file:
var options = {
target: '#message',
url:'newproduct.php',
beforeSubmit: function() {$('#uploader').html('<img src="loader.gif" border="0" />');},
success: function() {$('#uploader').html('New Product Was Successfully Added');}
};
var newProductDialog = $("#addProductDiv").dialog({
autoOpen: false,
title: "Add New Product",
modal: true,
width: 500,
show: { effect: 'drop',direction:"up",duration:1000 },
hide: { effect: 'drop',direction:"down",duration:1000 },
buttons: {
'Add':function() {
//submitNewProduct($("#newproduct"));
$("#newproduct").ajaxSubmit(options);
return false;
},
'Cancel':function() {
$(this).dialog('close');
$("#container").fadeTo('slow',1);
}
}
});
$("#loadNewProduct").click(function() {
newProductDialog.dialog('open');
$("#container").fadeTo('slow',.4);
return false;
});
And here is how my newproduct.php looks like:
include("../includes/database.php");
$path = "../images/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST))
{
$productNo = isset($_POST['productNumber']) ? $_POST['productNumber'] : "";
$productName = isset($_POST['productName']) ? $_POST['productName'] : "";
$sflf = isset($_POST['sflf']) ? $_POST['sflf'] : "";
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(2048*2048))
{
$tmp = $_FILES['file']['tmp_name'];
if(move_uploaded_file($tmp, $path.$name))
{
$sql= "insert into inventory (productName,sfLf,image,time,productNo) values
('{$productName}','{$sflf}','{$name}',now(),'{$productNo}')";
$database->query($sql) or die(mysql_error()."Database Failed")
}
else echo "There Was A Problem Adding Your Product. Please Try Again"
}
else echo "Size Cannot Exceed 2 MB";
}
else echo "Invalid File Format";
}
}
However, I keep getting a 500 Internal Server Error, so I know that my newproduct.php has some issues that I cannot work around.
EDIT:
After debugging my newproduct.php, I figured out that move_uploaded_file() function causes this error and it is unable too upload the file for some reason. What could be wrong now?

Can I use jquery post with image uploads?

I'm trying to use jquery to submit my form like so but it's not triggering anything in the functions.php file. Do I need to do anything special with a multipart/form-data? Am I missing something?
HTML:
<form id="process_image_form" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES); ?>" method="post" >
<input type="hidden" name="image_id1" id="image_id1" />
<table class="bordered-table">
<tbody>
<tr>
<td><input name="file" type="file" id="file"/></td>
</tr>
<tr>
<td><button type="submit" class="btn primary" data-loading-text="Uploading..." id="upload_profile_photo" name="upload_profile_photo">Upload</button></td>
</tr>
</tbody>
</table>
</form>
Jquery call:
$('#upload_profile_photo').click(function(e) {
e.preventDefault();
$.post('gallery/functions.php', $("#process_image_form").serialize(), function(status) {
if (status.st) {
alert("Photo Uploaded");
}
}, "json");
});
functions.php:
if (isset($_POST['upload_profile_photo'])) {
if (isset($_FILES['file']) && $_FILES['file']['size'] > 0) {
//handle file upload
$size = filesize($_FILES['file']['tmp_name']);
if ($size > $max_file_size * 1024 * 1024) {
$res->error = '<div class="alert-message error">Your image file is too large. Reduce its size and try uploading again.</div>';
echo json_encode($res);
exit();
}
if ($res->error == "") {
//process image
$res = uploadImage($_FILES['file']['tmp_name'], $user_id);
if ($res->st) {
unlink($_FILES['file']['tmp_name']);
$res->msg = '<div class="alert-message success">Your profile photo was uploaded successfully!</div>';
echo json_encode($res);
exit();
}
}
}
else {
$res->error = '<div class="alert-message error">Please select a photo to upload.</div>';
echo json_encode($res);
exit();
}
}
jquery serialize method will not work on file inputs. Look here please: How can I upload files asynchronously?
I have a great experience with jquery file upload plugin for this purpose.

php form - onsubmit reset form

I have created a form and everything is working fine so far. The only thing I have left is to reset the fields when the form is submitted. This seems like an easy task but after looking around and trying some things nothing seems to do the trick :( What I have now was taken from another post but my submit event was different from theirs which is why I think its not working. Any help is much appreciated.
php part
/////////////////////////////////upload image
//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","500");
//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
if(isset($_POST['submit']))
{
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
//if it is not empty
if ($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
//print error message
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
$newname="storeImages/".$filename;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}}}}
//If no errors registred, print the success message
if(isset($_POST['submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully!</h1>";
}
//direct to same page but refresh
//header('Location: storeListForm.php');
?>
The form
<body>
<script type="text/javascript">
function onFormSubmit ()
{
document.storeList.reset();
return true; // allow form submission to continue
}
</script>
<div id="signUp">
<?php
//if the validation falls back to php, then print the validation error
if (isset($error_message)) echo $error_message;
?>
<form method="post" action="" id="storeList" name="storeList" enctype="multipart/form- data">
<table>
<tr>
<td><label for="name">Name</label></td>
<td><input type="text" name="name" id="name" value="<?php if (isset($_POST['name'])) echo $_POST['name'];?>"/></td>
</tr>
<tr>
<td> <label for="storeLocation">Location</label></td>
<td><input type="text" name="storeLocation" id="storeLocation" value="<?php if (isset($_POST['storeLocation'])) echo $_POST['storeLocation'];?>"/></td>
</tr>
<tr>
<td><label for="featured_items">Featured Items</label></td>
<td><input type="text" name="featured_items" id="featured_items" value="<?php if (isset($_POST['featured_items'])) echo $_POST['featured_items'];?>"/></td>
</tr>
<tr>
<td><label for="keywords">Keywords</label></td>
<td><input type="text" name="keywords" id="keywords" value="<?php if (isset($_POST['featured_items'])) echo $_POST['keywords'];?>"/></td>
</tr>
<tr>
<td><label for="fileImage">Image</lable></td>
<td><input type="file" name="image"></td>
</tr>
<td>Description</td>
<td> <textarea for="description"></textarea type="text area" name="description" id="description" value="><?php if (isset($_POST['description'])) echo $_POST['description'];?>"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" id="submit" value="Add Store" onsubmit="this.submit(); this.reset(); return false;"></td>
</tr>
</table>
</form>
</div>
</body>
Perhaps you're looking for this?
onClick="this.form.reset()"
(Yours is only this.reset()).

Categories