I use a php ajax script for uploading image in my site and it's don't has limit for upload image.
I want a user can upload only for example 3 image. how can add this limit in my code?
This is my php code for uploading image:
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$vpb_upload_image_directory = "uploads/";
$vpb_allowed_extensions = array("gif", "jpg", "jpeg", "png");
foreach($_FILES as $file)
{
/* Variables Declaration and Assignments */
$vpb_image_filename = basename($file['name']);
$vpb_image_tmp_name = $file['tmp_name'];;
$vpb_file_extensions = pathinfo(strtolower($vpb_image_filename), PATHINFO_EXTENSION);
//New file name
$random_name_generated = time().rand(1234,9876).'.'.$vpb_file_extensions;
if($vpb_image_filename == "")
{
//Browse for a photo that you wish to use
}
else
{
if (in_array($vpb_file_extensions, $vpb_allowed_extensions))
{
if(move_uploaded_file($vpb_image_tmp_name, $vpb_upload_image_directory.$random_name_generated))
{
//Display Uploaded Files
$image .= '
<div class="vpb_wrapper" style="padding:10px;">
<img src="'.$vpb_upload_image_directory.$random_name_generated.'" class="vpb_image_style" />
</div>';
//$image .= '<div class="vpb_wrapper" style="padding:10px; text-decoration:none;">'.$vpb_image_filename.' uploaded</div>';
}
}
else
{
// Do not upload files which are not in the allowed file array
}
}
}
//Display the files
if($image != "") echo $image;
}
?>
In javascript, you can do something like this,
$(document).ready(function(){
$('#photoUploader').click(function(){
$('#photoUI').toggle('slow');
});
var ctr = 1;
$('#add').click(function(){
if(ctr < 3)
{
$('#ulPhoto').append("<li><input type='file' name='file[]' onchange='loadPreview(this,"+ctr+")' id='photo"+ctr+"' /><br /><img id='img"+ctr+"' src='#' alt='' style='width:100px' /><input type='text' autocomplete='off' name='caption[]' id='caption"+ctr+"' placeholder='ID Number' /></li>");
ctr++;
}
else
{
alert('Only 3 Images Allowed at a time');
}
});
});
HTML
<div id="photoUI" style="display:none; height: auto">
<ul id="ulPhoto">
<li>
<input type="file" name="file[]" id="photo0" />
<br />
<img id="img0" src="#" alt="" style="width:100px" />
<input type="text" autocomplete="off" name="caption[]" onchange="loadPreview(this,0)" id="caption0" placeholder="Default ID Number" readonly disabled />
</li>
</ul>
<span id="add" style="cursor:pointer">Add More...</span>
</div>
Related
I am trying to upload multiple images to server by one click. I am not getting any error on JavaScript console but no images uploaded to the server. Can you please let me know what I am doing wrong?
Here is my HTML markup
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-xs-6 col-md-3 text-center">
<a href="#" class="thumbnail ">
<div class="img-box">
<input type="file" class="file" name="image" /> <img class="img img-responsive" />
</div>
</a>
</div>
<div class="col-xs-6 col-md-3 text-center">
<a href="#" class="thumbnail ">
<div class="img-box">
<input type="file" class="file" name="image" />
<img class="img img-responsive" />
</div>
</a>
</div>
</div>
<input type="submit" value="Upload" class="submit" />
</form>
js file as:
$("#uploadimage").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "loader.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
}
});
}));
and PHP (loader.php) as
<?php
if (isset($_FILES["file"]["type"])) {
$validextensions = array(
"jpeg",
"jpg",
"png"
);
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && ($_FILES["file"]["size"] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
} else {
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/" . $_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
}
}
} else {
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>\
Please refer this .
when you send multiple files, php accept it as an array of files but in your code you are accepting them as a single file.
Also, try to give array of name as
<input type="file" name="images[]" id="images" multiple >
In a form, the name is the identifier of the input. So you should do $_FILES["image"] to access your file.
When a form have multiple inputs with the same name, it must be name with [] at the end (at least in php). So rename your image[] in the html source.
first, your file array you are taking in controller is wrong,
$temporary = explode(".", $_FILES["file"]["name"]);
you need to take image instead of file because in form file input name you used is image so,
$temporary = explode(".", $_FILES["image"]["name"]);
then after in your html you can take like this as thisisme_22 suggests
<input type="file" name="images[]" id="images" multiple >
then after in you action php file you can take count of the files and the using for or foreach you can get single file and upload it, like this
$count = count($FILES['image']['name']);
for($i = 0 ; $i < $count ; $i++){
$file = $FILES['image']['name'][$i];
}
I hope it helps.
check this code and change it as you need
$arr = array();
$arr = $_FILES['image']['name'];
for($i = 0; $i < count($arr) ; $i++)
{
$file_name = $_FILES['image']['name'][$i];
$file_size = $_FILES['image']['size'][$i];
$file_tmp = $_FILES['image']['tmp_name'][$i];
$file_type = $_FILES['image']['type'][$i];
$responce = move_uploaded_file($file_tmp, "orders/".$file_name);
}
I have a form to upload photos. After uploading the picture is displayed in the UL LI. The problem, if I bring up another image, the previous image is deleted and the new image is displayed only.
Would appreciate help
index.php:
<form name="multiple_upload_form" id="multiple_upload_form" enctype="multipart/form-data" action="image_upload.php">
<input type="hidden" name="image_form_submit" value="1"/>
<label>Add new</label>
<input type="file" name="images[]" id="images" multiple >
<div class="uploading none">
<label> </label>
<img src="images/uploading.gif"/>
</div>
</form>
<div class="gallery" id="images_preview">
<ul class="reorder_ul reorder-photos-list">
</ul>
</div>
JS:
$(document).ready(function(){
$('#images').on('change',function(){
$('#multiple_upload_form').ajaxForm({
target:'#images_preview ul',
beforeSubmit:function(e){
$('.uploading').show();
},
success:function(html){
$('.uploading').hide();
},
error:function(e){
}
}).submit();
});
});
image_upload.php:
<?php
if($_POST['image_form_submit'] == 1)
{
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
$target_dir = "../uploads/";
$target_file = $target_dir.time().$_FILES['images']['name'][$key];
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$target_file)){
$images_arr[] = $target_file;
}
//$extra_info = getimagesize($_FILES['images']['tmp_name'][$key]);
//$images_arr[] = "data:" . $extra_info["mime"] . ";base64," . base64_encode(file_get_contents($_FILES['images']['tmp_name'][$key]));
}
//Generate images view
if(!empty($images_arr)){ $count=0;
foreach($images_arr as $image_src){ $count++?>
<li id="image_li_<?php echo $count; ?>" class="ui-sortable-handle">
<img src="<?php echo $image_src; ?>" alt="">
</li>
<?php }
}
}
?>
You could save the old content in a variable before it is replaced by the response:
`
var old;
$('#images').on('change',function(){
old = $('#images_preview ul').html();
$('#multiple_upload_form').ajaxForm({
[...]
success: function(){
$('.uploading').hide();
$('#images_preview ul').append(old);
`
I'm having an issue with a file upload where it's not uploading. When uploading a 7mb video the $_FILES['video']['tmp_name'] is empty and when I upload a 15mb file the form doesn't actually "submit", really just refreshes.
Here is my code to handle the submission:
if(isset($_POST['submit'])){
$blah = "".$_FILES['video']['size']."";
var_dump($blah);
if( empty($_FILES['video']) && empty($_POST['create_video']) ){
echo "<div class='alert alert-danger' role='alert'><center><strong>Missing Fields:</strong> Please choose a video or request the ##### team create a video.</center></div>";
} else {
if( empty($_FILES['video']['name']) && $_POST['create_video'] == "true" ){
$_SESSION['create_video'] = protect($_POST['create_video']);
?>
<script type="text/javascript">
window.location = "NEXT_PAGE";
</script>
<?
exit();
}else{
//if all were filled in continue
$allowedExts = array("mp4", "MP4", "m4a");
$extension = pathinfo($_FILES['video']['name'], PATHINFO_EXTENSION);
if ( ($_FILES["video"]["size"] <= 15728640) && (in_array($extension, $allowedExts)) ) {
if ($_FILES["video"]["error"] > 0){
echo "Return Code: " . $_FILES["video"]["error"] . "<br />";
}else{
//Get the height and width of our video
//$getID3 = new getID3;
//$file = $getID3->analyze($_FILES["video"]["tmp_name"]);
//$width =$file['video']['resolution_x'];
//$height = $file['video']['resolution_y'];
$img = getimagesize($_FILES['video']['tmp_name']);
$width = $img[0];
$height = $img[1];
var_dump($width); var_dump($height);
if( ($height < 719) || ($width < 1279)){
echo "<div class='alert alert-danger' role='alert'><center><strong>Invalid file dimensions</strong> Please ensure your image is the correct size.</center></div>";
} else {
$ext = findexts ($_FILES["video"]["name"]);
$ran = rand ();
$file_name = $_FILES["video"]["name"] = "".$_SESSION['uid'] ."".$ran.".".$ext."";
if (file_exists("uploads/video_ads/".$_SESSION['uid']."_" . $_FILES["video"]["name"])){
echo $_FILES["video"]["name"] . " already exists. ";
}else{
move_uploaded_file($_FILES["video"]["tmp_name"],
"uploads/video_ads/".$_SESSION['uid']."_" . $_FILES["video"]["name"]);
//Save the link of our ad
$_SESSION['video'] = "####/uploads/video_ads/".$_SESSION['uid']."_" . $_FILES["video"]["name"]."";
$_SESSION['create_video'] = protect($_POST['create_video']);
?>
<script type="text/javascript">
window.location = "NEXT_PAGE";
</script>
<?
exit();
}
}
}
} else {
echo "<div class='alert alert-danger' role='alert'><center><strong>Invalid file type</strong> Please upload a video in MP4 format.</center></div>";
}
}
}
}
Here is my actual form:
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post" class="form-signin" role="form" enctype="multipart/form-data">
<br />
<input type="file" name="video" id="video" /><br />
<br />
<div class="row">
<div class="col-md-12">
<strong class="ad-header"
style="font-size: 150%; font-weight: bold;">Quick Tips:</strong>
</div>
</div>
<hr>
<h3 class="ad-sub-header" style="color: #559fd3; font-size: 150%;">Need
help to create engaging artwork for your brand?</h3>
<strong class="ad-header" style="font-size: 100%;">####
has the creative team to get it done for you</strong><br /> Only ##/hr -
3 revisions - Artwork is yours to keep. <br />
<br /> <input type="checkbox" name="create_video" value="true" />
I don't have an ad. Please create one. <br />
<br /> <input class="btn btn-lg btn-primary btn-block"
type="submit" name="submit" value="Continue To Step 5" />
</form>
The odds are your server does not accept uploads greater than 2M in size. You need to check phpinfo() (or php.ini if you have access to it) to see what your current limit is. If it is only 2M, or smaller than your upload size, you need to edit it to allow for bigger uploads. If you're on shared hosting you may be out of luck.
Try adjusting your php.ini with this settings:
php_value memory_limit 96M
php_value post_max_size 96M
php_value upload_max_filesize 96M
and ensure that the file_uploads setting is in On
For anyone who has this issue. I had to increase my post_max_size which was defaultly set to 8M.
I'm preparing the script facebook style wall post. Using Php and Jquery. But I have a problem. I wrote a function to upload photos. Upload a picture from your computer picture is selected when the button is clicked. and passage of the picture preview image (image loading) part opens. Photos button after installing upload pictures come back again.
The problem is that (loading image) warning does not disappear. Also (loading image) warning not lost are not coming back button to upload pictures.
Thanks in advance for your help.
jQuery
$('#photoimg').die('click').live('change', function()
{
var values=$("#uploadvalues").val();
$("#previeww").html('<img src="wall_icons/loader.gif"/>');
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
} }).submit();
var X=$('.preview').attr('id');
var Z= X+','+values;
if(Z!='undefined,')
{
$("#uploadvalues").val(Z);
}
});
HTML
<div class="tb-content">
<div class="ct-tab1">
<textarea name="update" id="update" placeholder="Ne düşünüyorsun?" class="contenttextarea" ></textarea>
<div id="button_hide">
<div class="secretdiv">
<div id="webcam_container" class='border'>
<div id="webcam" >
</div>
<div id="webcam_preview">
</div>
<div id='webcam_status'></div>
<div id='webcam_takesnap'>
<input type="button" value=" Resimçek " onclick="return takeSnap();" class="camclick resimcekbutton"/>
<input type="hidden" id="webcam_count" />
</div>
</div>
<div id="imageupload" class="border">
<form id="imageform" method="post" enctype="multipart/form-data" action='message_image_ajax.php'>
<div id='preview'>
</div>
<div id='imageloadstatus'>
<img src='<?php echo $base_url;?>wall_icons/ajaxloader.gif'/> Resim yükleniyor lütfen bekleyin....
</div>
<div id='imageloadbutton'>
<input type="file" name="photoimg" id="photoimg" class="dosyasec" />
</div>
<input type='hidden' id='uploadvalues' />
</form>
</div>
</div>
<div class="videovecamerabutonlari">
<div class="imgbutonu"><img src="wall_icons/videobutonu.png" border="0" /></div>
<div class="videobutonu"><img src="wall_icons/camerabutton.png" border="0" /></div>
</div>
<div class="shr">
<input type="submit" id="update_button" class="update_button" value="Paylaş" />
<input type="submit" id="cancel" value="İptal" />
</div>
</div>
</div>
<div id='flashmessage'>
<div id="flash" align="left" ></div>
</div>
Php
<?php
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
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['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(10024*10024))
{
$actual_image_name = time().$uid.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$data=$Wall->Image_Upload($uid,$actual_image_name);
$newdata=$Wall->Get_Upload_Image($uid,$actual_image_name);
if($newdata)
{
echo '<img src="'.$path.$actual_image_name.'" class="preview" id="'.$newdata['id'].'"/>';
}
}
else
{
echo "Fail upload folder with read access.";
}
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format.";
}
else
echo "Please select image..!";
exit;
}
?>
I am using form action event to load image on server ,how can i identify return of method so that i can set backgound image of canvas element with that image???
<form id="imageform" class="form-horizontal" action="ajaximage.php" method="post" enctype="multipart/form-data" >
<div class="control-group">
<label class="control-label" for="InputImage">Upload Image for Liberary</label>
<div class="controls">
<span class="btn btn-file">
<input type="file" name="photoimg" id='fileImage' class="fileUpload" required />
<div id='preview' style=""></div> <!-- style="width: 90px;" onchange="this.style.width = '100%';" <div id='categoryImage' style='border:1px solid black; height:20px' ></div> --> <div id='libImage' style="display: none"></div> <div id='preview'></div> </span>
</div>
</div>
</form>
ajaximage.php
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
//echo "<script>alert(".$name.")</script>";
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = $txt.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
echo "<img src='../products/".$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 can fire change event using following code with jQuery
$("document").ready(function(){
$("#fileImage").change(function() {
$( "#imageform" ).submit();
});
});
OR you can use this also
$('#fileImage').on("change", function(){ $( "#imageform" ).submit(); });
see Fiddle