Why this code isn't uploading image? - php

Here is a code for uploading image using ajax. I have added jQuery library and jQuery form as well but this code neither gives me any error nor uploads image just uploading goes on and upload image starts running never to stop. Can't find whats wrong with this code.
upload.php
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').live('change', function() {
$("#preview").html('');
$("#preview").html('<img src="./img/loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image <input type="file" name="photoimg" id="photoimg" />
</form>
ajaximage.php
<?php
include("/inc/connect.php");
if(isset($_SESSION['username'])) {
$username = $_SESSION['username'];
}
else if(isset($_COOKIE['username'])){
$username = $_COOKIE['username'];
}
else
{
//invalid ---
}
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$sql=$db->prepare("UPDATE table SET profile_pic=:image_name WHERE username=:username");
$sql->execute(array(':image_name'=>$actual_image_name,':username'=>$username));
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;
}
?>

Related

Unable to upload mp3 file

I have already change php.in config where have set max_size = 256M but it still does not allow me to upload. I dont know where i am going wrong.....i am able to upload image file, pdf file ,documentary file but not mp3. php.in settings didnt work for me...please anybody can guide me. Below is my php code
Thanks in advance!
<?php
//Concept of file upload
if(isset($_POST['submit']))
{
$file = $_FILES['files']['name'];
$type = $_FILES['files']['type'];
$file_tmp = $_FILES['files']['tmp_name'];
$size = $_FILES['files']['size'];
$file_err = $_FILES['files']['error'];
if($size!=null)
{
if($_FILES['files']['size'] <= 10000000 && $_FILES['files']['type'] == "audio/mpeg")
{
$path = "D:/";
$path = $path.basename($file);
if(!is_uploaded_file($file))
{
$flag = move_uploaded_file($file_tmp, $path);
if($flag == true)
{
echo "Moved Success";
}
else
{
echo "Some problem";
}
}
else
{
echo "Already Uploaded";
}
}
else
{
echo "Not audio file";
}
}
else if($size > 10000000)
{
echo "Size exceeded";
}
else if($size == null)
{
echo "Please select a file";
}
else
{
echo "Error".$file_err;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="basic.php" method="post" enctype="multipart/form-data">
<input type="file" name="files"/>
<input type="submit" value="upload" name="submit"/>
</form>
</body>
</html>
If you are trying to upload an mp3 file, the type of the $_FILES must be
&& $_FILES["file"]["type"] == "audio/mp3"
not
&& $_FILES['files']['type'] == "audio/mpeg"

Jquery ajax form submit response getting alert automatically

I am trying to upload an image using ajax form. Image upload is success. But the ajax response getting alerted automatically with a blank popup saying 'The page at www.xxx.com says'.
Here is my jQuery code
$('#profileImg').die('click').live('change', function()
{
$("#profileform").ajaxForm({target: '#preview_profile',
beforeSubmit:function(){
$("#profileloadstatus").show();
$("#profileloadbutton").hide();
},
success:function(s){
$("#profileloadstatus").hide();
$("#profileloadbutton").show();
},
error:function(){
$("#profileloadstatus").hide();
$("#profileloadbutton").show();
$('#profileform').reset();
} }).submit();
if(!s)
{
$("#profileform")[0].reset();
}
});
HTML FORM
<div id="preview_profile"></div><form id="profileform" method="post" enctype="multipart/form-data" action='message_profile_ajax.php'>
<div id="preview_prof"></div>
<div id="profileloadstatus" style="display:none; text-align:center;">
<img src='images/wall_icons/ajaxloader.gif'/> Uploading....
</div>
<div id="profileloadbutton">
<input type="file" id="profileImg" name="profileImg">
</div>
<input type="hidden" id="profvalues" value="" />
</form>
Php code
<?php
include_once 'includes.php';
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
function getImangeName($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,0,$i-1);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['profileImg']['name'];
$size = $_FILES['profileImg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
$imageName = getImangeName($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = $imageName.time().$uid.".".$ext;
$tmp = $_FILES['profileImg']['tmp_name'];
if(move_uploaded_file($tmp, $profile_path.$actual_image_name))
{
$data=$Wall->Profile_Image_Upload($uid,$actual_image_name);
if($data)
{
echo '<img src="'.$profile_path.$actual_image_name.'" class="img-circle" alt="User Image" />';
}
}
else
{
echo '<b>Sorry, </b>Falied to upload your file!';
}
}
else
echo '<b>Sorry, </b>Image file size must be less than 1 MB!';
}
else
echo '<b>Sorry, </b>Invalid file format!';
}
else
echo '<b>Sorry, </b>Please select image..!';
exit;
}
?>
Please help,
Thank you
Check jquery.wallform.js
//return data;
// Modification www.9lessons.info
var exp = /<img[^>]+>/i;
expResult = data.match(exp);
if(expResult == null) {
alert(data);
} else {
$(options.target).prepend(data);
}
$("#photoimg").val('');
// Modification End www.9lessons.info

I can't get $_FILE['file']['name'] value with ajax request

I've html form. Now i'm trying to upload file using php with ajax request. But I'm getting following error message when I upload the file by php with ajax request. is it my ajax request problem or anything ?
Notice: Undefined index: file in D:\Software Installed\xampp\htdocs\wix\users\insert_galary.php on line 16
html form:
<p>Add more</p>
<div id="dialog-modal2" title="Upload your galary image" style="display: none;">
<form method="post" action="insert_galary.php" id="myForm2" enctype="multipart/form-data" >
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Upload image</td>
<td><input type="file" name="file" class="tr"/></td>
</tr>
</table>
</form>
<span id="result2"></span>
<script type="text/javascript">
$("#sub2").click( function() {
$.post( $("#myForm2").attr("action"),
$("#myForm2 :input").serializeArray(),
function(info){ $("#result2").html(info);
});
clearInput();
});
$("#myForm2").submit( function() {
return false;
});
</script>
</div>
function showDialog2()
{
$("#dialog-modal2").dialog(
{
width: 610,
height: 350,
open: function(event, ui)
{
var textarea = $('<textarea style="height: 276px;">');
$(textarea).redactor({
focus: true,
autoresize: false,
initCallback: function()
{
this.set('<p>Lorem...</p>');
}
});
}
});
}
Php form:
$gid = mt_rand(100000, 999999);
$file = $_FILES["file"]["name"];
$type = $_FILES["file"]["type"];
$size = ($_FILES["file"]["size"] / 1024);
$temp = $_FILES["file"]["tmp_name"];
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$galary_pic = $gid.".".$extension;
$galary_directory = "../galary_images/";
$err = array();
if(isset($file))
{
if(empty($file))
$err[] = "Upload your picture";
elseif(!in_array($extension, $allowedExts))
$err[] = "Uploaded file must be gif, jpeg, jpg, png format";
elseif($size > 500)
$err[] = "Uploaded file must be within 500kb";
}
if(!empty($err))
{
echo "<div class='error'>";
foreach($err as $er)
{
echo "<font color=red>$er.</font><br/>";
}
echo "</div>";
echo "<br/>";
}
else
{
echo "sql query";
}
Note: I already submit this question last day but I can't get any proper answer. Sorry about it
You're not uploading a file but just making a POST request without any file attached. If you're looking for an ajax file uploader, try jquery file upload here
http://blueimp.github.io/jQuery-File-Upload

ajax image upload and preview form

Im using a script to out put uploaded image preview. It works fine. i just like to show the image in one div and error or success massage in another div. is there any chance to do this? Here is the code.
Java script
<script type="text/javascript">
$(document).ready(function(){
$('#photoimg').live('change', function(){
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
});
});
</script>
HTML Code
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id="output"></div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>
</div>
PHP Code
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['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['photoimg']['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'>";
echo "<span class=ok-msg">Image has been uploaded..!</span>";
}
else
echo "<span class=error-msg">failed<span>";
}
else
echo "<span class=error-msg">Image file size max 1 MB</span>";
}
else
echo "<span class=error-msg">Invalid file format..</span>";
}
else
echo "<span class=error-msg">Please select image..!</span>";
exit;
}
I like to show all the massages (error-msg, ok-msg) and in the div output and image in the same place div preview. can anyone tell me how to do this. thanks in advance.
Use json dataType and success callback function like,
$("#imageform").ajaxForm(
{
dataType:'json',
success:function(json){
$('#output').html(json.img);
$('#preview').html(json.msg);
}
}).submit();
In PHP
Return data like
echo json_encode(array('img'=>"<img src='...' />",'msg'=>"Message goes here"));
return;
you can use the -success: and the error: eventListner
$("#imageform").ajaxForm(
{
dataType:'json',
success:function(json){
write the success msg
}
error: function() {
write the error msg
}
}).submit();

Multiple File Upload PHP

I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php

Categories