PHP-Jquery image upload not working - php

I'm trying to post form data through ajax
form1.php
I use request to get all URL parameter data
$_REQUEST["Ename"];
$_REQUEST["eImg"];
To upload the image,i use this code http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
In the above link,you can see the source code,in the place of $_FILES['photoimg']['name'];,i use $_FILES['image']['name']; but it is not uploading the file and giving success message.
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
I removed script that is marked with **
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
**if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{**
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) { // Image size max 1 Mb
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['image']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
} else {
echo "failed";
}
} else {
echo "Image file size max 1 MB";
}
} else {
echo "Invalid file format..";
}
} **else {
echo "Please select image..!";
exit();
}**

you simply can't upload files via $.ajax().
you'll have to use some trycky iframe-stuff or something like that to make this work. luckily, there are ready-to-go plugins for jquery to handle this for you (like $.ajaxForm() for example wich seems to be the one that's used in the tutorial you're reading).
EDIT:
the plugin also allows to add extra data thats not present in the form itself. to quote the documentation:
data
An object containing extra data that should be submitted along with the form.
data: { key1: 'value1', key2: 'value2' }

For upload image by ajax you should use an iframe and set its id to form target.
Please have a look at
http://www.coursesweb.net/ajax/upload-images
It is very simple code to upload image

That won't work!
Images are handled differently from the text data in Ajax so you would have to do more than just post it using the $.ajax({}) method.
You can however use the jquery.form.js plugin it works perfect http://jquery.malsup.com/form/#download there is a tutorial on how to use it
here
Any ways I have used it my self so let me elaborate for you.
The JavaScript code is here
$('.uploadForm').live('click', function(evt){
$('#feedback').html(' ');
$('#feedback').html('<img src="images/loader_image.gif" alt="Uploading...."/>');
$("#formID").ajaxForm({
target: '#feedback'
}).submit();
evt.preventDefault();
});
If your PHP code is fine this should work .....
Just post the rest of the form fields in the normal way way
This should work for you. If the PHP code is fine
For example if you had other form fields like firstname and lastname in form like this one
<div class="form">
<fieldset class="ui-corner-all">
<h3 class="ui-widget-header ui-corner-top" align="center">Client information</h3>
<form action="save_new_client.php" enctype="multipart/form-data" id="clientForm" method="POST">
<label>First Name</label>
<input name="firstname" type="text" id="firstname" class="required" minlength="3"/>
<label>Lastname</label>
<input name="date_added" type="text" id="date_added" class="dateEst" />
<label>Image</label>
<input name="photo" type="file" id="photo" />
<input type="submit" name="button" id="button" value="Save" class="uploadForm"/>
<input type="reset" name="reset" id="button" value="Cancel" /></td>
</form>
</fieldset>
<div id="feedback"></div>
</div>
Below it you'll just need to add a div or paragraph to hold your feedback message ....
then the rest will be just fine (like I said if your PHP code is okay)I have not looked through it alot

Related

Issue with uploading multiple files on a single html page using php

I am trying to build a web page where users can edit images portrayed on their public pages. There are 3 images that display on their public page and I've set up 3 HTML forms in order to handle the 3 separate files.
I only have 1 listed below because once I figure out the fix to 1 I'll be able to duplicate the fix to the other 2,
I have other upload pages on my website and they work fine, but for some reason this page is giving me trouble. I can select a file but when I want to upload it my php code doesn't read that there is anything being posted.
*I've commented out the function call (I know it works) I just need to know why my php code won't read that there is a file there.
If I had to guess it'd be something with how it's named or how it's being tossed to the php code.
The code looks like this:
<div class="academic" style="width:250px;">
<br>
<?php
if(isset($_FILES['aca']) === true)
{
echo 'please print'; //It doesn't
if(empty($_FILES['aca']['name']) === true)
{
echo 'Please choose a file! <br>';
}
else
{
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['aca']['name'];
$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $_FILES['aca']['tmp_name'];
echo '<br>';
echo '<br>';
print_r($_FILES['aca']['tmp_name']);
echo '<br>';
echo '<br>';
if(in_array($file_extn, $allowed) === true) {
//upload_image($file_temp,$file_extn);
echo 'You have uploaded a picture!';
echo '<b><h3>Press submit again to finish the upload</h3></b>';
//echo "<script>window.top.location='../hidden/viewPNM.php?id=$permi'</script>";
}
else
{
echo 'Incorrect File Type!! <br> Allowed: ';
echo implode(', ', $allowed);
}
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="aca" id="aca">
<input type="submit" value="Upload">
</form>
</div>
</span>
Okay...here is what you can try to do:
Move the whole PHP code UNDER the form code. I remember that sometimes wierd bugs with that were happening, and the code didnt run
If that doesnt work, do following:
Change <input type="file" name="aca" id="aca"> to <input multiple="true" type="file" name="aca[]" />
Add this code above the submit button: <input type="hidden" name="sendfiles" value="Send Files" />
Replace if(isset($_FILES['aca']) === true) with if(isset($_POST['sendfiles']))
If this doesn't work, I can offer you a way to allow multiple files being uploaded from one button. (Took the code from my website I made before)

uploading a file server side

Below is my code where the user can upload a file. What I want to know is that is there a way so that via server side is there a way to first of all restrict the file formats of the files to jpeg and png only and then when the user clicks on the submit button, if the file format is correct then display an alert on the same page stating "File is correct" else display an alert stating "File is incorrect".
Can somebody please provide coding if they know how to do this. Thank you and any help will be much appreciated :)
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
A code for a total check of file uploads, you'll have to change $allowedtypes though. (Copied instead of linking because it was from a non-English site)
<?php
if(isset($_POST["submit"])){
$allowedtypes=array("jpg"=>true,"png"=>true,"gif"=>true,"txt"=>true);
$filename = $_FILES['file1']['name'];
$source = $_FILES['file1']['tmp_name'];
$file_size=$_FILES['file1']['size'];
$saveloc = "uploads/" . $filename;
$maxfilesize=1024*1024*10;
$nameext=explode(".",$filename);
if(preg_match('/^[A-Za-z0-9\-\_]{1,}\.[a-zA-Z0-9]{0,4}$/',$filename)){
if(!empty($allowedtypes[strtolower($nameext[1])]) && $allowedtypes[strtolower($nameext[1])]===true){
if($file_size<=$maxfilesize){
if(!file_exists($saveloc)){
if(move_uploaded_file($source, $saveloc)) {
chmod($saveloc,644);
echo "Successful upload. <a href='".$saveloc."'>Fájl megtekintése</a>";
}
else echo "Cannot move";
}
else echo "Existing file";
}
else echo "Too big file";
}
else echo "Not allowed extension";
}
else echo "Only alphanumeric files allowed";
}
else echo "<form method='post' enctype='multipart/form-data' action='secureupload.php'> File: <input type='file' name='file1' /><br /><input
name='MAX_FILE_SIZE' type='hidden' value='10485760' /> <input type='submit' value='Upload' name='submit' /></form>";
?>
You are talking about server side handler and write 'alert'...khm...
If u want to do stuff via server-side, then use php handler
http://php.net/manual/en/features.file-upload.post-method.php
If u want to do stuff via client-side, use javascript events, e.g on change event
<script>
function check() {
var file = document.getElementById('file').value;
var temp = file.split(/\.+/).pop();
alert(temp);
}
</script>
<input type="file" name="file" id="file" onchange="check();" />
You have file extension in temp var.
There are PHP functions to do this. You want to look at mime_content_type and finfo_file. These are built-in PHP commands that allow you to interpret that actual file type of a file being uploaded. You can then filter the mime types to only .gif/.jpg/etc. You want to check the mime types over the file name because the file name can be changed to mask the actual file type. If you want code samples, there are plenty on those pages as well as some excellent user-provided alternatives.
Something like this at the top of your file should work:
<?php
foreach ($_FILES as $file)
{
$tmp = explode(".", $file["tmp_name"]);
if (!in_array($tmp[count($tmp)-1], array("jpeg", "png"), true))
die("<script>alert('File is incorrect');</script>");
}
echo "<script>alert('File is correct');</script>";
?>

uploading file to folder on website via PHP

I would like to have the user upload a pdf to a folder on my website. (note:this is for learning purposes, so security is not necessary) The code I have below does not do echo a response when submitted. The folder I would like to have the pdf uploaded to is in the same directory as the php script, is it possible I'm incorrectly referencing that folder? I appreciate it.
<form method = "POST" action = "<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
Email:<br /> <input type = "text" name="email" value=""/><br />
Resume:<br /><input type = "file" name="resume" value=""/><br />
<p><input type="submit" name ="submit" value="Submit Resume" /></p>
</form>
if(isset($_POST['submit']))
{
define ("FILEREPOSITORY","./resume/");
if (is_uploaded_file($_FILES['resume']['tmp_name'])) {
if ($_FILES['resume']['type'] != "application/pdf") {
echo "<p>Resume must be in PDF Format.</p>";
}
}else {
$name = $_POST['email'];
$result = move_uploaded_file($_FILES['resume']['tmp_name'], FILEREPOSITORY."/$name.pdf");
if ($result == 1) {
echo "<p>File successfully uploaded.</p>";
}
else {
echo "<p>There was a problem uploading the file.</p>";
}
}
}
You have a logical error. Your else statement should be part of the inner if statement -- not the outer one.
would suggest you check the permissions for the upload folder and the max size for file uploading in your php.ini... its happened to me many times uploading a file exceeding the limits and not getting an error message.. also the logic of your if else doesn't match as suggested by your previous post..
IT would be of great help to give the error you receive.
move_uploaded_file()
only works if you have the rights to write to the destination folder.

Image Upload & storing the link in the database

I'm using this form to add the title,link of the image and the text of the article to the database.
I'm using type="text" for the image link,now,it's getting borring to upload an image on a external image upload service and copy the link.
I want to upload the image with this for and store THE LINK of the image in the database.
The form:
<?php if (!$_POST["go"]){ ?>
<form method="post" action="">
<input name="article_title" type="text">
<input name="article_image_url" type="text"> <!-- i want here type="file" -->
<textarea name="article_text"></textarea>
<input type="submit" name="go" value="Submit">
</form>
<?php
} else {
$date=date("Y.m.d");
$title = $_POST["article_title"];
$image_url = $_POST["article_image_url"];
$text = $_POST["text"];
$sql="INSERT INTO articles (title,image_url,text,date) VALUES ('$title', '$image_url', '$text', '$date')";
if (mysql_query($sql)){
echo "done";}
else {echo "error<br>" . mysql_error();}}
?>
Please help me with this :)
ps:sorry for my English :$
The first thing you should do, and it seems you are clueless about SQL escaping, is add following before you access the first $_POST var:
$_POST = array_map("mysql_real_escape_string", $_POST);
Then you seemingly want to use a file upload for the image. If so change the url field to:
<input type=file name=image>
This uploaded file will show up in $_FILES. Use it like this, preferrably after you've read the other fields from $_POST:
if ($img = $_FILES["image"]["tmp_name"]) {
$image_url = md5_file($img) . ".jpeg";
move_uploaded_file($img, "./upload/$image_url");
$image_url = "http://www.example.org/where/$image_url";
}
There are lot's of security concerns with that. But that's out of scope here, so I hardwired it to .jpeg. There's lots of information in the manual and its comments: http://de2.php.net/manual/en/features.file-upload.php

PHP AJAX UPLOAD?

I am having problem uplaoding file,
here are my codes:
Any help? Thanks!
test.html
function insertPhoto()
{
var description = document.getElementById('description').value;
var image = document.getElementById('photo').value;
var url = "ajax_insert.php?action=add&image="+image+"&description="+description;
var ajaxRequest = ajax_obj();
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4){
document.getElementById("msgbox").innerHTML=ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
return false;
}
<div align="center">
<div class="top" >
<div>
Decription <input name="description" type="text" id="description" value="" maxlength="20" />
</div>
<div style="margin-top:5px" >
Image
<input name="photo" type="file" id="photo" value="" maxlength="20" />
</div>
<div class="buttondiv">
<input name="button" type="button" value="Upload" onclick="return insertPhoto()" style="margin-left:-10px; height:23px" />
<span id="msgbox" style="display:none"></span>
</div>
</div>
</div>
ajax_insert.php
<?php
mysql_connect('localhost','root','');
mysql_select_db('priceless');
define('DIR_IMAGE','images/');
$image = $_GET['image'];
$description = $_GET['description'];
$dbtable = 'photos';
$action = $_GET['action'];
if($action == 'add'){
$photo = '';
if ($_FILES[$image]['name']) {
$aray = explode(".",$_FILES[$image]['name']);
$ext = $aray[count($aray)-1];
$photo = date('Ymdhis').'.'.$ext;
move_uploaded_file($_FILES[$image]['tmp_name'],DIR_IMAGE.$photo);
}
$data = array(
'image'=> $photo,
'description'=> $description
);
$values = array();
foreach($data as $show){
$values[] = $show;
}
$query = "INSERT INTO ".$dbtable." (`".implode("`,`",array_keys($data))."`) values ('".implode("','",array_values($values))."')";
if ($result= mysql_query($query) or die(mysql_error())) {
echo "You have Sucessfully Upload Photo!";
}
}
?>
Personally I use this Ajax upload http://valums.com/ajax-upload/ and I'm satisfied with results.
You can't upload files using pure AJAX, because you can't access the file's contents programmatically due to security issues.
You can use an iframe and specify it as the target of the upload form.
You can see an example of it here: http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html
You can't upload files using pure AJAX, because you can't access the file's contents programmatically.
You would have to use a different technique, e.g. submitting the form the normal way into a hidden iframe element. That's the way the jQuery form plugin does it.
If you want some AJAXy upload, look at Uploadify - http://www.uploadify.com/
It can handle multiple uploads at once, and has a real time progress bar. It then has JS parameters to allow you to handle the upload etc.
If you need a full tutorial give me a shout and I will show you some examples!
Hope this helps.
Because of security issues, many browsers do not let you pass data from a file select field through javascript/ajax. It is better to use a page that calls itself, with a normal submit button. (I've tried AJAX uploads on my own website, so believe me).
Try -
<?php
if ($_FILE['file'] != ''){
$dest = 'folder/';
list($name, $ext) = explode('.', $_FILES['file']['name']);
if(is_uploaded_file($_FILES['file']['tmp_name'])){
#move_uploaded_file($_FILES['file']['tmp_name'], $dest.$name.'.'.$ext);
};
};
?>

Categories