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
Related
code:
<?php
if(isset($_POST['submit']))
{
if(isset($_FILES['img_url']['name']))
{
for($i=0; $i<count($_FILES['img_url']['name']); $i++)
{
$tmpFilePath = $_FILES['img_url']['tmp_name'][$i];
if ($tmpFilePath != "")
{
$path = "../images/hotel_images/";
$name = $_FILES['img_url']['name'][$i];
$size = $_FILES['img_url']['size'][$i];
list($txt, $ext) = explode(".", $name);
$file= time().substr(str_replace(" ", "_", $txt), 0);
$info = pathinfo($file);
$filename = $file.".".$ext;
$filepath_upload = $path.$filename;
$imageFileType = strtolower(pathinfo($filename,PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
$j2 = $i+1;
$msg = "<div class='alert alert-success'>Sorry, ".$j2." Image files Extension .".$ext." are not Uploaded & Other files Uploaded Successfully <br/>.</div>" ;
}
else if(move_uploaded_file($_FILES['img_url']['tmp_name'][$i], $filepath_upload))
{
$banner_image_source_file = $filepath_upload;
$banner_image_save_file = $filepath_upload;
list($width_orig, $height_orig) = getimagesize($banner_image_source_file);
$img_url_name.=$filename."|";
}
}
$filepath = rtrim($img_url_name, '|');
}
if(!empty($filepath))
{
$query = mysqli_query($con, "INSERT INTO `hotel`(`img_url`, `status`) VALUES ('".$filepath."')");
if($query)
{
$msg .= "<div class='alert alert-success'>Hotel Record Added Successfully</div>";
}
else
{
$msg = "<div class='alert alert-success'>Unbale to Add Hotel Record Please Try Again !!!</div>";
}
}
else
{
$msg = "<div class='alert alert-success'>Unable to Add Please Try Again !! </div>";
}
}
else
{
$msg = "<div class='alert alert-success'>Unable to Add Please Try Again !! </div>";
}
}
?>
<form action="" method="POST" enctype="multipart/form-data" id="add-hotel-form">
<div class="form-group col-md-12">
<label for="hotel">Upload Hotel Images</label>
<input type="file" class="form-control-file" id="upload_hotel_img1" name="img_url[]" multiple>
</div>
<div class="form-group col-md-12">
<label for="room">Upload Room Images</label>
<input type="file" class="form-control-file" id="upload_room_img1" name="img_url2[]" multiple>
</div>
<input type="submit" class="btn btn-primary" name="submit" value="Submit">
</form>
In the following code I have create a simple form where I have two input field type='file' where I am able to upload only first one i.e. <label for="hotel">Upload Hotel Images</label> and move into the folder successfully but I also want to upload and move second input field i.e. <label for="room">Upload Room Images</label>. I don't have any idea about this. So, How can I do this? Please help me.
Thank You
Your Room Image input is called img_url2, which you never interact with in code.
For best practice, move the bulk of your PHP code into a file upload function, then call it once with img_url $_FILE input, and once with img_url2.
Example:
<?php
error_reporting(E_ALL);
ini_set("display_errors", true);
ini_set("display_startup_errors", true);
function uploadFile($file, $path)
{
$img_url_name = "";
if(is_array($file) && isset($file['name']) && isset($file['tmp_name']) && isset($file['size']))
{
$tmpFilePath = isset($file['tmp_name'][0]) ? $file['tmp_name'][0] : "";
$name = isset($file['name'][0]) ? $file['name'][0] : "";
list($txt, $ext) = explode(".", $name);
$file = time().substr(str_replace(" ", "_", $txt), 0);
$filename = $file.".".$ext;
$filepath_upload = $path.$filename;
$imageFileType = strtolower(pathinfo($filename,PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
return "<div class='alert alert-success'>Sorry, ".$name." Image files Extension .".$ext." are not Uploaded & Other files Uploaded Successfully <br/>.</div>" ;
}
else if(move_uploaded_file($tmpFilePath, $filepath_upload))
{
$img_url_name .= $filename."|";
}
$filepath = rtrim($img_url_name, '|');
if(!empty($filepath))
{
if(!isset($con))
{
global $con;
}
$query = mysqli_query($con, "INSERT INTO `hotel`(`img_url`, `room_url`) VALUES ('".$filename."','".$filepath."')");
if($query)
{
return "<div class='alert alert-success'>Hotel Record Added Successfully</div>";
}
}
}
return "<div class='alert alert-success'>Unable to Add Please Try Again !! </div>";
}
if(isset($_POST['submit']))
{
if(isset($_FILES['img_url']['name']))
{
echo uploadFile($_FILES['img_url'], "../images/hotel_images/");
}
if(isset($_FILES['img_url2']['name']))
{
echo uploadFile($_FILES['img_url2'], "../images/room_img/");
}
}
?>
<form action="" method="POST" enctype="multipart/form-data" id="add-hotel-form">
<div class="form-group col-md-12">
<label for="hotel">Upload Hotel Images</label>
<input type="file" class="form-control-file" id="upload_hotel_img1" name="img_url" multiple>
</div>
<div class="form-group col-md-12">
<label for="room">Upload Room Images</label>
<input type="file" class="form-control-file" id="upload_room_img1" name="img_url2" multiple>
</div>
<input type="submit" class="btn btn-primary" name="submit" value="Submit">
</form>
I use FormData() to upload multiple images from multiple fields. Please take a look at this code:
<head>
<title>Example</title>
</head>
<body>
<form enctype="multipart/form-data" id="add-hotel-form">
<div class="form-group col-md-12">
<label for="hotel">Upload Hotel Images</label>
<input type="file" class="form-control-file" id="upload_hotel_img1" name="img_url" multiple>
</div>
<div class="form-group col-md-12">
<label for="room">Upload Room Images</label>
<input type="file" class="form-control-file" id="upload_room_img2" name="img_url2" multiple>
</div>
<input type="button" class="btn btn-primary" name="submit" value="Submit" onclick="myfunction();">
</form>
</body>
<script>
function myfunction(){
var form_data = new FormData();
var image = document.getElementById('upload_hotel_img1').files.length;
var images = document.getElementById('upload_room_img2').files.length;
for (var x = 0; x < image; x++) {
form_data.append("image", document.getElementById('upload_hotel_img1').files[x]);
}
for (var x = 0; x < images; x++) {
form_data.append("images[]", document.getElementById('upload_room_img2').files[x]);
}
}
</script>
We can retrieve these images in the backend using the follwing : $_FILES["image"]['name'] and $_FILES["images"]['name'] respectively.
I am on Ubuntu. I am trying to take user file upload of small images. I checked the $_FILES it's filled with data. I tried to debug the move command but it doesnot echo anything.
if ($_SERVER['REQUEST_METHOD'] == 'POST' ){
//Now handle everything
if(isset($_POST["submit"])) {
print_r($_FILES);
//Store the image
if(!empty($_FILES['uploaded_file']))
{
$path = "/neel/public/img/";
$path = $path.basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo 'Its working';
} else{
echo 'I am done!!!';
die();
}
}
createnewEvent($conn);
header('Location:/neel/index.php');
}
}
You can check if the file exists by checking its name.
if(!empty($_FILES['file']['name']))
Where file is the name of input field for file.
P. G above here is correct.
Instead of checking, if $_POST['submit']
You should check this:
if(isset($_FILES['uploaded_file']['name']))
Try this code it's a complete sign up form with PHP , Bootstrap
HTML
<div class="container">
<div class="row">
<br>
<h1 class="text-center">Create new account</h1>
<br>
<div class="col-lg-4 col-md-6 col-sm-12">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="name" placeholder="Your Name">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="password" placeholder="Password">
</div>
<div class="form-group text-center">
<div class='file-input'>
<input type='file' name="profile-img">
<span class='button label' data-js-label>Choose your profile image</span>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success form-control form-control-lg" name="signup" value="Signup">
</div>
</form>
</div>
</div>
</div>
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors;
if (empty($_POST['name'])) {
$errors[] = "Name field is empty";
}
if (empty($_POST['username'])) {
$errors[] = "Username field is empty";
}
if (empty($_POST['password'])) {
$errors[] = "Password field is empty";
}
if (empty($_FILES['profile-img'])) {
$errors[] = "You should upload profile image";
} else{
$img = $_FILES['profile-img'];
$ext = end(explode('.', $img['name']));
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$max_size = 4; //MegaBytes
if (! in_array($ext, $allowed_extensions)) {
$errors[] = "Please , Choose a valid image";
}
$img_size = $img['size'] / 1000000; // By Megabyte
if ($img_size > $max_size) {
$errors[] = "This picture is so large";
}
}
if (!empty($errors)) {
echo '<div class="container">';
foreach ($errors as $error) {
echo '
<div class="alert alert-danger" role="alert">
' . $error . '
</div>
';
}
echo "</div>";
} else {
$username = filter_var(htmlentities(trim($_POST['username'])), FILTER_SANITIZE_STRING);
$name = filter_var(htmlentities(trim($_POST['name'])), FILTER_SANITIZE_STRING);
$password = sha1(filter_var(htmlentities(trim($_POST['password'])), FILTER_SANITIZE_STRING));
// Profile Picture :-
$imgname = uniqid(uniqid()) . #date("Y-m-d") . "." . $ext;
$target_bath = "uploads/imgs/";
$target_bath = $target_bath . basename($imgname);
$orginal_img = $img['tmp_name'];
if (move_uploaded_file($orginal_img, $target_bath)) {
$sql = "INSERT INTO users(name, username, password,profile_picture, r_d) VALUES ('$name', '$username', '$password', '$target_bath', NOW())";
$result = mysqli_query($conn, $sql);
header('location: ./login.php');
}
}
}
The script you've shown shown will only "not echo anything" if $_SERVER['REQUEST_METHOD'] is not "POST". Assuming your description of events is accurate, then the problem is in the form #halojoy has asked that you show here.
I do hope that you are not redirecting the script back to itself. Also you shouldn't attempt to do a redirect after an echo.
i am creating a page called events i have created a form which submits on post file, this is my form code, `
Adding Staff
<div class="box">
<label>Heading</label>
<input type="text" name="heading" id="heading"/>
</div>
<div class="box" style="margin-left: 120px">
<label>Description 1</label>
<textarea cols="30" rows="5" name="description_1" id="description_1"></textarea>
</div>
<div class="box">
<label>Description 2</label>
<textarea cols="30" rows="5" name="description_2" id="description_2"></textarea>
</div>
<div class="clear"> </div>
<div class="box">
<label>Upload Images</label>
<input type="file" name="picture" id="picture"/>
<label>Is Rename <input type="checkbox" name="is_rename"> </label>
</div>
<div class="clear"> </div>
<div class="box" style="width: 100px; margin-left: 350px;">
<input style="padding: 4px" type="submit" name="submit" value="submit">
</div>`
This is my post
<?php
ob_start();
session_start();
include_once "../../classes/addClasses.php";
$heading = $_POST['heading'];
$description_1 = $_POST['description_1'];
$description_2 = $_POST['description_2'];
$picture = $_POST['picture'];
$target_dir = "../../../uploads/";
$target_file = $target_dir . basename($_FILES["picture"]["name"]);
print_r($_FILES);
if( isset( $_POST['is_rename'] ) )
$file_name = time().'-'.basename($_FILES["picture"]["name"]);
else
$file_name = basename($_FILES["picture"]["name"]);
if(empty($_FILES['picture']['name'])){
echo "please select a file to upload";
?>
<script>window.location.href="http://localhost/learner-pack/admin/admin/add_events.php?error=empty"</script>
<?php
}
$target_file = $target_dir . $file_name;
if (move_uploaded_file($_FILES["picture"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["picture"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
if (file_exists($target_file)) {
echo "Sorry, file '".$file_name."' already exists.";
}elseif (move_uploaded_file($_FILES["picture"]["tmp_name"], $target_file)) {
echo "The file " . $file_name . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
/*$created_by = $_POST['created_by'];
$updated_by = $_POST['updated_by'];
$current_date = $_POST['current_date'];
$updated_date = $_POST['updated_date'];
$visitor_counter = $_POST['visitor_counter'];*/
if($admin->addingEvents($heading,$description_1,$description_2, $file_name))
{
header('Location: ../view_events.php?added=true');
}
else
{
echo "Error";
}
?>
please help me to store multiple images in table using one field and retireve them to view on events page when i fetch one row so that all images on that row are fetchable
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>
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;
}
?>