I can upload the image to a new folder, but the main things is need to display it out from that folder to PDF. Then I am using FDPF, but then I get an error message when displaying:
"Uncaught Exception: FPDF error: Can't open image file: Tulips.jpg "
But when i echo the $img it display. Then i add on $img in pdf->Image($img) it wont work it appear above message error.
Here is what I have try to code htmltopdf.html
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function ValidateSingleInput(oInput) {
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
oInput.value = "";
return false;
}
}
}
return true;
}
function handleFileSelect(event)
{
console.log(event)
var input = this;
if (input.files)
{
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++)
{
var reader = new FileReader();
console.log(reader)
reader.onload = (function (e)
{
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="',e.target.result, '" title="', escape(e.name), '"/><span class="remove_img_preview"></span>'].join('');
document.getElementById('preview').insertBefore(span, null);
});
reader.readAsDataURL(input.files[i]);
}
}
}
$(document).ready(function(){
// Listen to click event on the submit button
$('#submit').click(function (e) {
e.preventDefault();
var myform = document.getElementById("form");
var fd = new FormData(myform);
$.ajax({
url:"upload1.php",
type:"POST",
data:fd,
//dataType: 'json',
processData: false,
contentType: false,
cache: false,
success:function(data){
alert("Success Insert!");
},
});
});
$('#fileToUpload').change(handleFileSelect);
//preview image and remove
$('#preview').on('click', '.remove_img_preview',function ()
{
$(this).parent('span').remove();
$("#fileToUpload").val("");
});
});
</script>
<style>
div.relative {
position: relative;
top: -300px;
}
#bottom{
position: relative;
right: 0;
bottom: 0;
}
.thumb
{
width: 100px;
height: 100px;
margin: 0.2em -0.7em 0 0;
}
.remove_img_preview
{
position:relative;
top:-25px;
right:5px;
background:black;
color:white;
border-radius:50px;
font-size:0.9em;
padding: 0 0.3em 0;
text-align:center;
cursor:pointer;
}
.remove_img_preview:before
{
content: "×";
}
table,th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
textarea {
width: 100%;
height: 300px;
padding: 12px 20px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
background-color: #f8f8f8;
font-size: 16px;
resize:none;
}
table.menu {
border: 1px solid black;
border-collapse: collapse;
width: 10%;
float:right;
}
</style>
<body>
<form action="generate_pdf.php" method="POST" id="form">
<input type="submit" value="Send" id="submit" name="submit"><input type="reset" value="Clear">
<input type="file" name="fileToUpload[]" id="fileToUpload" onchange="ValidateSingleInput(this);" multiple = "multiple" style="display: none;">
<input type="button" value="Browse..." onclick="document.getElementById('fileToUpload').click();" />
<input type="submit" value="PDF">
<div id="preview"></div>
</form>
</body>
</html>
Here is the upload1.php
<?php
require 'config.php';
$year = date("yy");
$year = substr($year, -2);
$month = date("m");
$key = "KM".$year.$month;
$total = count($_FILES['fileToUpload']['name']);
$sql = "SELECT * FROM images WHERE id LIKE '$key%' ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
//GET NEW RUNNING NUMBER BY CHECKING DATABASE
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$number = sprintf('%03d',substr($row['id'], -3)+ 1) ;
$ans = $key.$number;
}
}
else
{
$ans = $key."001";
}
$target_dir = "D:/XAMPP/htdocs/new3/new3/uploads/" . $ans;
if(!file_exists($target_dir))
{
mkdir($target_dir,0777,true);
}
$sql = $conn->query ("INSERT INTO images (id) VALUES ('$ans')");
$allowed = array('gif', 'png', 'jpg','xlsx','pdf','doc');
$ext = pathinfo($total, PATHINFO_EXTENSION);
if (!in_array($ext, $allowed)) {
echo 'error';
}
for( $i=0 ; $i < $total ; $i++ )
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$i], $target_dir."/".$ans."-".$_FILES["fileToUpload"]["name"][$i]))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"][$i]). " has been uploaded."."<br>";
}
else
{
echo "Sorry, there was an error uploading your file.";
}
}
?>
Here is the generate_pdf.php that i have try:
<?php
$img=$_FILES["fileToUpload"]["name"][0];
echo $img;
require 'fpdf181/fpdf.php';
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',10);
$pdf->Image($img,NULL,NULL,0,0,'PNG');
$pdf->Output();
?>
I don't know whether I wrote it correctly or not? Or just need to call back the path where image is stored and display it out? Myself already brainstorming, don't know how it works. Can anyone help? Maybe this is a duplicate questions but I can't even find any related things, just can found how to retrieve from database.
First problem is that your <form> tag is missing the enctype="multipart/form-data" attribute.
As for the PHP error, $_FILES["fileToUpload"] is an array, so $image=$_FILES["fileToUpload"]["name"] should change to $_FILES["fileToUpload"]["name"][0] (assuming you want the first file). So generate_pdf.php should start with:
$image=$_FILES["fileToUpload"]["name"][0];
After i have amend some of it the error come out is "Fatal error: Uncaught Exception: FPDF error: Can't open image file"
This is the code file i have amend call generate_pdf.php
$image=$_FILES["fileToUpload"]["name"][0];
$img="C:/xampp/htdocs/test/uploads/".$image;
require 'fpdf181/fpdf.php';
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',10);
$pdf->Image($img, NULL, NULL, 0, 0, 'png');
$pdf->Output();
Related
I edit multiple image upload scripts.
I added the features of uploading up to 3 photos and not uploading files larger than 5mb. It works successfully.
-- But I couldn't figure out how to define the text fields I added on js and how to send it to php document with post action.
Could you help?
I am posting the codes below.
php code:
<?php
$dts = $_POST['dts'];
$ttt = explode(',',$dts);
$others_image_last='';
$image_link="/upload_img/"; //folder name
for($i=0; $i<sizeof($_FILES['upload_files']['name']); $i++) {
if (in_array($i+1, $ttt)){}else{
$new_file = md5(microtime());
$image_type = $_FILES["upload_files"]["type"][$i];
$image_name = $_FILES["upload_files"]["name"][$i];
$image_error = $_FILES["upload_files"]["error"][$i];
$image_temp_name = $_FILES["upload_files"]["tmp_name"][$i];
print_r($image_temp_name);
if (($image_type == "image/jpeg") || ($image_type == "image/png") || ($image_type == "image/pjpeg") || ($image_type == "image/jpg")) {
$test = explode('.', $image_name);
$name = $new_file.'.'.end($test);
$url = '.'.$image_link. $name;
$info = getimagesize($image_temp_name);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($image_temp_name);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($image_temp_name);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($image_temp_name);
imagejpeg($image,$url,80);
}
echo $name;
/****** insert query here ******/
}
}?>
Html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>Multiple Photo Upload</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<style>
.suggested-posts-article{
background: white;
-moz-box-shadow: rgba(0,0,0,0.0666) 0 3px 10px;
-webkit-box-shadow: rgba(0,0,0,0.0666) 0 3px 10px;
box-shadow: rgba(0,0,0,0.0666) 0 3px 10px;
display: inline-block;
margin: 5px;
width: 23%;
}
article, aside, details, figcaption, figure, footer, header, main, nav, section {
display: block;
}
article, aside, footer, header, hgroup, main, nav, section {
display: block;
}
.suggested-posts-articlees {
display: inline-block;
width: 49.5%;
}
#media screen and (max-width:450px) {
.suggested-posts-article {
width:40% !important;
}
}
.more-photos:after{ right: 3px !important;
bottom: 0px !important;}
article, aside, details, figcaption, figure, footer, header, main, nav, section {
display: block;
}
.posts_article {
background-color: #333;
background-position: 50%;
background-size: cover;
margin-bottom: 2px;
padding-bottom: 63.5%;
}
#media screen and (max-width:450px) {
.suggested-posts-article {
width:40% !important;
}
}
.more-photos:after{ right: 3px !important;
bottom: 0px !important;}
.more-photos{
cursor:pointer !important;
}
.bluess {
width:100%;
margin:10px;
}
.btn-group-sm>.btn, .btn-sm {
padding: .25rem .5rem;
font-size: .875rem;
line-height: 1.5;
border-radius: .2rem;
}
.btn-outline-secondary {
color: #868e96;
background-color: transparent;
background-image: none;
border-color: #868e96;
}
.btnxc {
display: inline-block;
padding: .5rem .75rem;
border:1px solid #868e96;
margin:3px;
padding: .25rem .5rem;
font-size: .875rem;
line-height: 1.5;
border-radius: .2rem;
color:#868e96;
}
.rrrr{
color:red;
fill:red;
}
.rrrr2{
background-color: red;
}
.datepost{
margin-top:-15px;
}
.anther_ma
{
margin:1px;
}
.set_process
{
margin: 0px 7px 0px 0px;
}
.messaf{display:none;}
.progress{
width:80%;
}
.success_msg{
color:green;
display:none;
}
#post_send{
margin:8px 0 8px 0;
}
.fa_p{
margin-right:20px;
margin-top:10px;
border:0px;
z-index:9999
}
.p_run_div{
margin-top:-7px;
border-radius:0px;
padding:0px;
margin-bottom:8px;
display:none;
}
.btnxc{
margin-left:15px;
cursor:pointer;
}
.btnxc_r{
margin-left:15px;
display:none;
}
</style>
<div class="container">
<div class="row">
<div class="col-md-8">
<h2>Multiple Photo Upload</h2>
<div class="form-group">
<label for="examplename">Name</label>
<input type="text" class="form-control" id="examplename" placeholder="First Name">
</div>
<div class="form-group">
<label for="examplesurname">First Name</label>
<input type="text" class="form-control" id="examplesurname" placeholder="Last Name">
</div>
<div><button class="imgbuts btn btn-success" style='float:left'>Choose Photo...</button> <div id="uyari" style='float:left'>You can upload 3 photos.<br>
Each photo should not be larger than 5 mb.</b></div></div>
<div style="clear:both"></div>
<form action="method" name="upload-file" class="main_form" id="form-upload-file" enctype="multipart/form-data">
<div class="ui-block">
<aside class="suggested-posts">
<div class="suggested-posts-container">
<div class="row" id="message_box"></div>
</div>
</aside>
</div>
</form>
<button class="btn btn-primary btn-md-2 " id='post_send' onclick="save_muliple_image()">Upload</button>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width:0%">
<span class="sr-only">0</span>
</div>
</div>
<h2 class="success_msg">Photo upload completed.</h2>
</div>
</div>
</div>
<script>
var xp = 0;
var input_btn = 0;
var dts = [];
$(document).on("click", ".imgbuts", function (e) {
if(xp < 3){
input_btn++;
$("#form-upload-file").append(
"<input type='file' style='display:none;' name='upload_files[]' id='filenumber" +
input_btn +
"' class='img_file upload_files' accept='.gif,.jpg,.jpeg,.png,' multiple/>"
);
$("#filenumber" + input_btn).click();
} else {
uyari.innerHTML = ' You can upload up to 3 photos.';
}
});
$(document).on("change", ".upload_files", function (e){
files = e.target.files;
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
xp++;
var f = files[i];
var boyut = f.size;
var res_ext = files[i].name.split(".");
var img_or_video = res_ext[res_ext.length - 1];
var fileReader = new FileReader();
var yuvarlama = (boyut / (1024*1024)).toFixed(2) + ' mb';
uyari.innerHTML = '';
if (boyut > 5000000) {uyari.innerHTML = ' File size larger than 5mb'; xp--; return;}
fileReader.name = f.name;
fileReader.onload = function (e) {
var file = e.target;
$("#message_box").append(
"<article class='suggested-posts-article remove_artical" +
xp +
"' data-file='" +
file.name +
"'><div class='posts_article background_v" +
xp +
"' style='background-image: url(" +
e.target.result +
")'></div><div class='p_run_div'><span class='pp_run progress_run" +
xp +
"' style='opacity: 1;'></span></div><p class='fa_p p_for_fa" +
xp +
"'><span class='cancel_mutile_image btnxc cancel_fa" +
xp +
"' deltsid='"+0+"'><b>✖ SİL</b></span><span class='btnxc btnxc_r' >✔</span><span style='float:right'>"+ yuvarlama +"</span></p></article>"
);
};
fileReader.readAsDataURL(f);
}
});
function save_muliple_image() {
suggested = $(".suggested-posts-article").length;
if (suggested > 0) {
$(".cancel_mutile_image").prop("disabled", true);
$("#post_send").prop("disabled", true);
var formData = new FormData(document.getElementById("form-upload-file"));
formData.append("dts", dts);
var xhr = new window.XMLHttpRequest();
$.ajax({
url: 'upload_ajax.php',
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function (data) {
$(".main-content").find(".message-loading-overlay2").remove();
},
error: function (e) {
$("#preview_file_div ul").html(
"<li class='text-danger'>Something wrong! Please try again.</li>"
);
},
xhr: function (e) {
xhr.upload.addEventListener(
"progress",
function (e) {
console.log(e);
if (e.lengthComputable) {
var percentComplete = ((e.loaded || e.position) * 100) / e.total;
if(percentComplete==100){
$(".progress-bar").width(percentComplete + "%").html('99' + "%");
}else{
var yuzde = Math.floor(percentComplete);
$(".progress-bar").width(percentComplete + "%").html(yuzde + "%"); }
}
},
false
);
xhr.addEventListener("load", function (e) {
$('.progress-bar').css("background","#5cb85c").html('100' + "%");
$(".btnxc_r").show();
$(".success_msg").show();
$(".cancel_mutile_image").remove();
});
return xhr;
},
});
} else {
$(".messaf").show();
}
}
var rty=0;
$(document).on("click", ".cancel_mutile_image", function (e) {
$('.cancel_mutile_image').each(function(){
chk_id = $(this).attr('deltsid');
if(chk_id==0){ rty++; $(this).attr('deltsid',rty); }
});
deltsid = $(this).attr('deltsid');
dts.push(deltsid);
$(this).parents(".suggested-posts-article").remove();
xp--;
});
</script>
</body>
</html>
Uploading multiple files in php can be tricky but the trick you need to use here is that instead of using name="upload" in input filed use name="upload[]" it returns an array so it makes the code much cleaner ... And to upload files use loops ( I used for loop in to see demonstrate how to upload different files here ) you can write some js and before uploading add some validations as per your needs !
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$path = "./"; // Specifiy the path where uploaded files goes
// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);
// Loop through each file
for ($i = 0; $i < $total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a file path
if ($tmpFilePath != "") {
$target_path = $path;
$target_path = $target_path.basename($_FILES['upload']['name'][$i]);
// Upload files (YOUR IMAGES) into desired directory !
if (move_uploaded_file($tmpFilePath, $target_path)) {
$success = "success";
}
}
}
}
?>
<form action="index.php" method="POST" accept-charset="utf-8" enctype="multipart/form-data">
<input type="file" name="upload[]" multiple />
<button type="submit">Submit</button>
</form>
I am very new to PHP and need to figure this out for a project - I've made an image submit form in HTML that changes the img within a div to the image that selected using the form. Here is how I accomplish this:
echo '<div class="img-container">';
echo '<img class="userimg" src="../images/backgroundplanet.png" />';
echo '<img class="testimg" src="" />'; //stores image from php file
echo '</div>';
echo '<div class="upload-button">Edit Profile</div>';
echo '<input class="file-upload" enctype="multipart/form-data" type="file" name="submit" accept="image/*"/>';
echo '</div>';
and
$(document).ready(function() {
var readURL = function(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.userimg').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".file-upload").on('change', function(){
readURL(this);
});
$(".upload-button").on('click', function() {
$(".file-upload").click();
});
});
I need to upload this image to a column I have created for medium BLOBs in a MySql data base for each individual user. I've tried a number of different methods (tried $sql = new mysql, etc) but have no idea what I'm doing.
I'm now following this tutorial - http://www.sevenkb.com/php/how-to-insert-upload-image-into-mysql-database-using-php-and-how-to-display-an-image-in-php-from-mysql-database/ and have written the following that is supposed to upload an image to the database:
if(!isset($_FILES['upload_image']))
{
echo '<p>Please Select Image to Upload</p>';
}
else
{
try {
upload();
echo '<p>Image Uploaded into MySQL Database as LONGBLOB Using PHP </p>';
}
catch(Exception $e)
{
echo '<h4>'.$e->getMessage().'</h4>';
}
}
function upload(){
/*** check if a file was uploaded ***/
echo '<p>you uploaded</p>';
if(is_uploaded_file($_FILES['upload_image']['tmp_name']) && getimagesize($_FILES['upload_image']['tmp_name']) != false)
{
/*** get the image info. ***/
$size = getimagesize($_FILES['upload_image']['tmp_name']);
/*** assign our variables ***/
$type = $size['mime'];
$imgfp = fopen($_FILES['upload_image']['tmp_name'], 'rb');
$size = $size[3];
$name = $_FILES['upload_image']['name'];
$maxsize = 99999999;
/*** check the file is less than the maximum file size ***/
if($_FILES['upload_image']['size'] < $maxsize )
{
/*** connect to db ***/
$dbh = new PDO("mysql:host=localhost;dbname=sqlserver", 'username', 'password');
/*** set the error mode ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** our sql query ***/
$stmt = $dbh->prepare("INSERT INTO img (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");
/*** bind the params ***/
$stmt->bindParam(1, $type);
$stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
$stmt->bindParam(3, $size);
$stmt->bindParam(4, $name);
/*** execute the query ***/
$stmt->execute();
}
else
{
/*** throw an exception is image is not of type ***/
throw new Exception("File Size Error");
}
}
else
{
// if the file is not less than the maximum allowed, print an error
throw new Exception("Unsupported Image Format!");
}
}
But the image isn't uploading and does not appear in the new column I made in the database. The only thing displayed on the page is "Please Select Image to Upload"
What's wrong here? Ultimately I need to echo this in a div.. What should I do with this?
When trying to run example:
Errors when entering in my table name:
When going to phpadmin:
I have used the code from this link "http://www.formget.com/ajax-image-upload-php/" to get what you needed. This code apart from saving the file into a folder will save it into a database.
I have made a folder images to store image files and two php files one which shows frontend html form with javascript code and the other for upload and display.
The HTML code "index.php" is this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
<input type="hidden" name="image_id" id="image_id" value="2" class="submit" />
</div>
</form>
</div>
<h4 id='loading' >loading..</h4>
<div id="message"></div>
<style>
.userimg {
width: 50px;
height:auto;
}
</style>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
$.ajax({
url: "upload.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
// Function to preview image after validation
$(function() {
$("#file").change(function() {
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#previewing').attr('src','noimage.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$("#file").css("color","green");
$('#image_preview').css("display", "block");
$('#previewing').attr('src', e.target.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
};
});
</script>
<style>
body {
font-family: 'Roboto Condensed', sans-serif;
}
h1
{
text-align: center;
background-color: #FEFFED;
height: 70px;
color: rgb(95, 89, 89);
margin: 0 0 -29px 0;
padding-top: 14px;
border-radius: 10px 10px 0 0;
font-size: 35px;
}
.main {
position: absolute;
top: 50px;
left: 20%;
width: 450px;
height:530px;
border: 2px solid gray;
border-radius: 10px;
}
.main label{
color: rgba(0, 0, 0, 0.71);
margin-left: 60px;
}
#image_preview{
position: absolute;
font-size: 30px;
top: 100px;
left: 100px;
width: 250px;
height: 230px;
text-align: center;
line-height: 180px;
font-weight: bold;
color: #C0C0C0;
background-color: #FFFFFF;
overflow: auto;
}
#selectImage{
padding: 19px 21px 14px 15px;
position: absolute;
bottom: 0px;
width: 414px;
background-color: #FEFFED;
border-radius: 10px;
}
.submit{
font-size: 16px;
background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
border: 1px solid #e5a900;
color: #4E4D4B;
font-weight: bold;
cursor: pointer;
width: 300px;
border-radius: 5px;
padding: 10px 0;
outline: none;
margin-top: 20px;
margin-left: 15%;
}
.submit:hover{
background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}
#file {
color: red;
padding: 5px;
border: 5px solid #8BF1B0;
background-color: #8BF1B0;
margin-top: 10px;
border-radius: 5px;
box-shadow: 0 0 15px #626F7E;
margin-left: 15%;
width: 72%;
}
#message{
position:absolute;
top:120px;
left:815px;
}
#success
{
color:green;
}
#invalid
{
color:red;
}
#line
{
margin-top: 274px;
}
#error
{
color:red;
}
#error_message
{
color:blue;
}
#loading
{
display:none;
position:absolute;
top:50px;
left:850px;
font-size:25px;
}
</style>
For the upload script and display after upload (upload.php) you can use
<?php
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$maxsize = 99999999;
$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"] < $maxsize)//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("images/" . $_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 = "images/".$_FILES['file']['name']; // Target path where file is to be stored
$size = getimagesize($_FILES['file']['tmp_name']);
/*** assign our variables ***/
$type = $size['mime'];
$imgfp = fopen($_FILES['file']['tmp_name'], 'rb');
$size = $size[3];
$name = $_FILES['file']['name'];
/*** check the file is less than the maximum file size ***/
if($_FILES['file']['size'] < $maxsize )
{
/*** connect to db ***/
$dbh = new PDO("mysql:host=localhost;dbname=DM_NAME", 'DB_USER', 'DB_PASSWORD');
/*** set the error mode ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** our sql query ***/
$stmt = $dbh->prepare("INSERT INTO imageblob (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");
/*** bind the params ***/
$stmt->bindParam(1, $type);
$stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
$stmt->bindParam(3, $size);
$stmt->bindParam(4, $name);
/*** execute the query ***/
$stmt->execute();
$lastid = $dbh->lastInsertId();
//Move uploaded File
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
if(isset($lastid))
{
/*** assign the image id ***/
$image_id = $lastid;
try {
/*** connect to the database ***/
/*** set the PDO error mode to exception ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** The sql statement ***/
$sql = "SELECT image, image_type FROM imageblob WHERE image_id=$image_id";
/*** prepare the sql ***/
$stmt = $dbh->prepare($sql);
/*** exceute the query ***/
$stmt->execute();
/*** set the fetch mode to associative array ***/
$stmt->setFetchMode(PDO::FETCH_ASSOC);
/*** set the header for the image ***/
$array = $stmt->fetch();
/*** check we have a single image and type ***/
if(sizeof($array) == 2)
{
//To Display Image File from Database
echo '<img src="data:image/jpeg;base64,'.base64_encode( $array['image'] ).'"/>';
}
else
{
throw new Exception("Out of bounds Error");
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
else
{
echo 'Please input correct Image ID';
}
}
else
{
/*** throw an exception is image is not of type ***/
throw new Exception("File Size Error");
}
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>
You can download the entire code from here http://www.filehosting.org/file/details/569640/upload.zip. Change the database details and also image displayed is the last insert id in the form . I hope you can do the rest.
I am trying to autocomplete a field that picks names of users from LDAP. My codes are as follows :
index.php
$(document).ready(function() {
$("#search-box").keyup(function() {
$.ajax({
type: "POST",
url: "readCountry.php",
data: 'keyword=' + $(this).val(),
beforeSend: function() {
$("#search-box").css("background", "#FFF url(LoaderIcon.gif) no-repeat 165px");
},
success: function(data) {
$("#suggesstion-box").show();
$("#suggesstion-box").html(data);
$("#search-box").css("background", "#FFF");
}
});
});
});
function selectCountry(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
body {
width: 610px;
}
.frmSearch {
border: 1px solid #F0F0F0;
background-color: #C8EEFD;
margin: 2px 0px;
padding: 40px;
}
#country-list {
float: left;
list-style: none;
margin: 0;
padding: 0;
width: 190px;
}
#country-list li {
padding: 10px;
background: #FAFAFA;
border-bottom: #F0F0F0 1px solid;
}
#country-list li:hover {
background: #F0F0F0;
}
#search-box {
padding: 10px;
border: #F0F0F0 1px solid;
}
<html>
<head>
<TITLE>jQuery AJAX Autocomplete - Country Example</TITLE>
<head>
<body>
<div class="frmSearch">
<input type="text" id="search-box" placeholder="Country Name" />
<div id="suggesstion-box"></div>
</div>
</body>
</html>
readCountry.php
<?php
if(!empty($_POST["keyword"])) {
$Name=$_POST["keyword"];
$username="********";
$password="********";
$lc = ldap_connect("********") or
die("Couldn't connect to AD!");
ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($lc,$username,$password);
$base = "OU=********,DC=********,DC=********";
$filt = "(&(&(&(objectCategory=person)(objectClass=user)(name=$Name*))))";
$sr = #ldap_search($lc, $base, $filt);
$info = ldap_get_entries($lc, $sr);
for ($i = 0; $i < $info["count"]; $i++) {
$info[$i]["cn"][0] ;
}
if ($i == 0) {
echo "No matches found!";
}
if(!empty($info[$i]["cn"][0])) {
?>
<ul id="country-list">
<?php
foreach($info[$i]["cn"][0] as $country) {
?>
<li onClick="selectCountry('<?php echo $country ?>');"><?php echo $country ?></li>
<?php } ?>
</ul>
<?php } } ?>
What I have :
This isn't returning names from LDAP nor is there any error that is dispalyed for me to fix it.
What I need :
When A is typed, all the names starting with 'A' should be shown in the dropdown.
Appreciate any help :) Thanks in advance! :)
$('#search').keyup(function () {
var data = this.value.split(" ");
var rows = $("#table tbody tr").hide();
if(this.value ===""){
rows.show();
return;
}
rows.hide();
rows.filter(function(i,v){
var t = $(this);
for (var d = 0; d < data.length; d++) {
if (t.is(":Contains('" + data[d] + "')")) {
return true;
}
}
return false;
}).show();
});
I found a way out! Just had to change the onclick in readcountry.php as shown below :
<?php
if(!empty($_POST["keyword"])) {
$Name=$_POST["keyword"];
$username="********";
$password="********";
$lc = ldap_connect("********") or
die("Couldn't connect to AD!");
ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($lc,$username,$password);
$base = "OU=********,DC=********,DC=********";
$filt = "(&(&(&(objectCategory=person)(objectClass=user)(name=$Name*))))";
$sr = #ldap_search($lc, $base, $filt);
$info = ldap_get_entries($lc, $sr);
for ($i = 0; $i < $info["count"]; $i++) {
<li onClick="selectCountry('<?php echo $info[$i]["cn"][0] ?>');"><?php echo $info[$i]["cn"][0] ?></li>
}
if ($i == 0) {
echo "No matches found!";
} }
I got the jquery variables to update the height width and positions when the divs are dragged but I need them to do the same when they are resized....how can I do this? Here is my code that I'm using right now to get the variables and send them to the php document:
<?
$query = mysql_query("SELECT * FROM users WHERE username='derekshull'");
$rows = mysql_fetch_array($query);
$googlewebx = $rows['googlewebx'];
$googleweby = $rows['googleweby'];
$googlewebh = $rows['googlewebh'];
$googlewebw = $rows['googlewebw'];
$googleimagex = $rows['googleimagex'];
$googleimagey = $rows['googleimagey'];
$googleimageh = $rows['googleimageh'];
$googleimagew = $rows['googleimagew'];
$googlenewsx = $rows['googlenewsx'];
$googlenewsy = $rows['googlenewsy'];
$googlenewsh = $rows['googlenewsh'];
$googlenewsw = $rows['googlenewsw'];
$wikix = $rows['wikix'];
$wikiy = $rows['wikiy'];
$wikih = $rows['wikih'];
$wikiw = $rows['wikiw'];
$wolfx = $rows['wolfx'];
$wolfy = $rows['wolfy'];
$wolfh = $rows['wolfh'];
$wolfw = $rows['wolfw'];
$twitterx = $rows['twitterx'];
$twittery = $rows['twittery'];
$twitterh = $rows['twitterh'];
$twitterw = $rows['twitterw'];
?>
<html>
<head>
<style>
.resizable { color: white; width: 1px; height: 1px; padding: 0.1em; bottom: 0; left: 0; }
.resizable h3 { text-align: center; margin: 0; }
</style>
<style>
#set div.resizable {
background: rgba(0, 157, 255, 0.9);
color: black;
float: left;
margin: 0 10px 10px 0;
padding: 0.5em;
}
#set { clear:both; float:left; width: 368px;}
p { clear:both; margin:0; padding:1em 0; }
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script>
function stop(ui, type) {
var pos_x;
var pos_y;
var window_width;
var window_height;
var need;
if (type == 'draggable') {
pos_x = ui.offset.left;
pos_y = ui.offset.top;
window_width = window.innerWidth;
window_height = window.innerHeight;
need = ui.helper.data("need");
} else if (type == 'resizable') {
pos_x = $(ui.element).offset().left;
pos_y = $(ui.element).offset().top;
window_width = window.innerWidth;
window_height = window.innerHeight;
need = ui.helper.data("need");
}
var width;
var height;
if (need == 1) {
width = $("#web").width();
height = $("#web").height();
}
if (need == 2) {
width = $("#image").width();
height = $("#image").height();
}
if (need == 3) {
width = $("#wiki").width();
height = $("#wiki").height();
}
if (need == 4) {
width = $("#twitter").width();
height = $("#twitter").height();
}
if (need == 5) {
width = $("#googlenews").width();
height = $("#googlenews").height();
}
if (need == 6) {
width = $("#wolf").width();
height = $("#wolf").height();
}
console.log(pos_x);
console.log(pos_y);
console.log(width);
console.log(window_width);
console.log(need);
//Do the ajax call to the server
alert(' x:' + pos_x +
' y:' + pos_y +
' ned_id:' + need +
' width:' + width +
' height:' + height +
' window_width:' + window_width +
' window_height:' + window_height);
}
$("#set div").draggable({
stack: "#set div",
preventCollision: true,
containment: $('#main_content'),
stop: function (event, ui) {
stop(ui, 'draggable');
}
});
$(".resizable").resizable({
stop: function (event, ui) {
stop(ui, 'resizable');
}
});
</script>
<meta http-equiv='Content-type' content='text/html;charset=UTF-8'>
<title>15:11 Project | You • Your Community • Your World</title>
</head>
<body>
<form action='' method='post'>
<fieldset><center>
<input type='search' name='q' /><input type='submit' value='Search' name='submit' />
</fieldset></center>
</form>
<div id="main_content" style="position: fixed; bottom: 0; left: 0; width:100.8%; margin:0 auto; height:95.1%; background-color: #ffffff; color: #000000;">
<div id="set">
<?
if(isset($_POST['q'])){
?>
<div id='web' style='overflow:hidden; left: 5%; top: 5%; width: 20%; height: 15%; position:fixed !important;' class='resizable ui-widget-content' data-need='1'>
<?php
enter code here for div 1.
echo "</div>";
}
?>
<?
if(isset($_POST['q'])){
?>
<div id='image' style='overflow:hidden; height: 19%; width: 32%; left: 60%; top: 12%; position:fixed !important;' class='resizable ui-widget-content' data-need='2'><center>
<?php
Enter code here for div 2
echo "</center></div>";
}
?>
<?
if(isset($_POST['q'])){
?>
<div id='wiki' style='overflow:hidden; left: 5%; top: 36%; height: 17%; width: 25%; position:fixed !important;' class='resizable ui-widget-content' data-need='3'>
<?php
Enter div 3.
}
?>
</div>
</div>
</div>
You can attach a function to the stop event...
$(function() {
$( ".resizable" ).resizable({
stop: function(){
// Do your updates here
}
});
});
Working fiddle:
http://jsfiddle.net/zkDHJ/
Resizable function has the same event stop and you can create a function to do what you are doing in draggable stop and call it from resizable stop
http://api.jqueryui.com/resizable/#event-stop
$(function() {
$( ".resizable" ).resizable({
stop: function() {
// call the same function as in draggable event stop
}
});
});
I would recommend creating a function to call from both events such as
function stop(ui, type) {
// your code
}
And then call it from both events:
$( ".resizable" ).resizable({
stop: function(event, ui) {
stop(ui, 'resizable');
)};
$( ".draggable" ).resizable({
stop: function(event, ui) {
stop(ui, 'draggable');
}
)};
EDIT: You see can see this jsfiddle showing you code working:
http://jsfiddle.net/v8efG/1/
There's a difference from the objects returned by draggable and resizable.
Draggable contains an offset property you can just use. Take a look at the wiki:
http://api.jqueryui.com/draggable/#event-stop
And Resizable does not contain offset but it contains element and you can obtain the offset from it. Take a look at the wiki:
http://api.jqueryui.com/resizable/#event-stop
When draggable
pos_x = ui.offset.left;
When resizable
pos_x = $(ui.element).offset().left;
So im trying to have an upload with a progress bar, i installed uploadprogress pecl, and the upload worked perfectly if the action in the form leads to upload.php, any other name, and it stops working.
If the name is not upload.php the output is simply "100" (which can be seen why below with the getprogress.php file)
this is the form: (this versions works, as the file is upload.php)
<form method="post" action="/test/upload.php" enctype="multipart/form-data" id="upload-form" target="upload-frame">
<input type="hidden" id="uid" name="UPLOAD_IDENTIFIER" value="<?php echo $uid; ?>">
<input type="file" name="file">
<input type="submit" name="submit" value="Upload!">
</form>
</div>
<div style="float:left;width:100%;">
<div id="progress-bar"></div>
</div>
<iframe id="upload-frame" name="upload-frame"></iframe>
this is the jquery:
<script>
(function ($) {
var pbar;
var started = false;
$(function () {
$('#upload-form').submit(function() {
pbar = $('#progress-bar');
pbar.show().progressbar();
$('#upload-frame').load(function () {
started = true;
});
setTimeout(function () {
updateProgress($('#uid').val());
}, 1000);
});
});
function updateProgress(id) {
var time = new Date().getTime();
$.get('../uploadprogress/getprogress.php', { uid: id, t: time }, function (data) {
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
started = progress < 100;
updateProgress(id);
}
started && pbar.progressbar('value', progress);
});
}
}(jQuery));
</script>
this is the file getprogress.php
<?php
if (isset($_GET['uid'])) {
// Fetch the upload progress data
$status = uploadprogress_get_info($_GET['uid']);
if ($status) {
// Calculate the current percentage
echo round($status['bytes_uploaded']/$status['bytes_total']*100, 1);
}
else {
// If there is no data, assume it's done
echo 100;
}
}
?>
ive spent about 5 hours on this trying to figure out why, and i cant. help would be greatly appreciated.
You can use this class, without using jquery:
<?php
/**
* Progress bar for a lengthy PHP process
* http://spidgorny.blogspot.com/2012/02/progress-bar-for-lengthy-php-process.html
*/
class ProgressBar {
var $percentDone = 0;
var $pbid;
var $pbarid;
var $tbarid;
var $textid;
var $decimals = 1;
function __construct($percentDone = 0) {
$this->pbid = 'pb';
$this->pbarid = 'progress-bar';
$this->tbarid = 'transparent-bar';
$this->textid = 'pb_text';
$this->percentDone = $percentDone;
}
function render() {
//print ($GLOBALS['CONTENT']);
//$GLOBALS['CONTENT'] = '';
print($this->getContent());
$this->flush();
//$this->setProgressBarProgress(0);
}
function getContent() {
$this->percentDone = floatval($this->percentDone);
$percentDone = number_format($this->percentDone, $this->decimals, '.', '') .'%';
$content .= '<div id="'.$this->pbid.'" class="pb_container">
<div id="'.$this->textid.'" class="'.$this->textid.'">'.$percentDone.'</div>
<div class="pb_bar">
<div id="'.$this->pbarid.'" class="pb_before"
style="width: '.$percentDone.';"></div>
<div id="'.$this->tbarid.'" class="pb_after"></div>
</div>
<br style="height: 1px; font-size: 1px;"/>
</div>
<style>
.pb_container {
position: relative;
}
.pb_bar {
width: 100%;
height: 1.3em;
border: 1px solid silver;
-moz-border-radius-topleft: 5px;
-moz-border-radius-topright: 5px;
-moz-border-radius-bottomleft: 5px;
-moz-border-radius-bottomright: 5px;
-webkit-border-top-left-radius: 5px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-left-radius: 5px;
-webkit-border-bottom-right-radius: 5px;
}
.pb_before {
float: left;
height: 1.3em;
background-color: #43b6df;
-moz-border-radius-topleft: 5px;
-moz-border-radius-bottomleft: 5px;
-webkit-border-top-left-radius: 5px;
-webkit-border-bottom-left-radius: 5px;
}
.pb_after {
float: left;
background-color: #FEFEFE;
-moz-border-radius-topright: 5px;
-moz-border-radius-bottomright: 5px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 5px;
}
.pb_text {
padding-top: 0.1em;
position: absolute;
left: 48%;
}
</style>'."\r\n";
return $content;
}
function setProgressBarProgress($percentDone, $text = '') {
$this->percentDone = $percentDone;
$text = $text ? $text : number_format($this->percentDone, $this->decimals, '.', '').'%';
print('
<script type="text/javascript">
if (document.getElementById("'.$this->pbarid.'")) {
document.getElementById("'.$this->pbarid.'").style.width = "'.$percentDone.'%";');
if ($percentDone == 100) {
print('document.getElementById("'.$this->pbid.'").style.display = "none";');
} else {
print('document.getElementById("'.$this->tbarid.'").style.width = "'.(100-$percentDone).'%";');
}
if ($text) {
print('document.getElementById("'.$this->textid.'").innerHTML = "'.htmlspecialchars($text).'";');
}
print('}</script>'."\n");
$this->flush();
}
function flush() {
print str_pad('', intval(ini_get('output_buffering')))."\n";
//ob_end_flush();
flush();
}
}
echo 'Starting…<br />';
$p = new ProgressBar();
echo '<div style="width: 300px;">';
$p->render();
echo '</div>';
for ($i = 0; $i < ($size = 100); $i++) {
$p->setProgressBarProgress($i*100/$size);
usleep(1000000*0.1);
}
$p->setProgressBarProgress(100);
echo 'Done.<br />';
?>
You can call the setProgressBarProgress function inside a while process, depending on your needs!!! It's great!.