PHP - Upload picture and display on page - php

The following code allows me to upload pictures (using a html form) to a directory on my server.
<?php
$target = "http://www.mockcourt.org.uk/user/htdocs/pics/2012/";
$target = $target . basename( $_FILES['uploaded']['name']);
$ok=1;
if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
Is there any way to modify it so that it will add the pictures to a html page instead?
Thanks

Well after you upload it, you can use javascript to put it on the html page.
I'm not quite sure what your question is, though
EDIT:
So, html form on your page:
<form action="imageUpload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="jupload();" id="form1" >
<div style="visibility:'hidden';" class="imageholder"> <!-- a gif image to show that the process wasn't finished -->
</div>
<input type="file" name="imgfile" />
<input type="submit" name="uploadButton" class="upbtn" value="Submit" />
</form>
Javascript(JQUERY) code for the upload and image add:
function jupload()
{
$(".imageholder").append('<img src="./images/loading.gif">');
}
function juploadstop(result)
{
if(result==0)
{
$(".imageholder").html("");
}
// the result will be the path to the image
else if(result!=0)
{
$(".imageholder").html("");
// imageplace is the class of the div where you want to add the image
$(".imageplace").append("<img src='"+result+"'>");
}
}
php code:
<?php
$target = "http://www.mockcourt.org.uk/user/htdocs/pics/2012/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
$result=$target;
}
else
{
$result=0;
}
?>
<script language="javascript" type="text/javascript">
window.top.window.juploadstop(<?php echo $result; ?>);
</script>

Suppose you have the form in HTML to submit the image.. make the submit button, not a submit button, but just a button.. e.g.
<input type='button' id='submit_form' value='upload' />
and in the javascript, use Ajax to submit the form and Jquery to display it in the web page
$('#submit_form')click(function(){
$.ajax({
type: 'POST',
url: path/phpfile.php,
data: image_input_name
});
//after submitting, get the url of the image form the server
$('#div_to_display_image').html("<img src='path/image_file.jpg' alt='this' />");
});
Hope this helps :-)

Related

Running PHP Script from HTML Leads to Blank PHP Page

(Note: Updated title to better match the question)
I am working on adding an image upload feature to ajax chat, and I have the HTML and PHP already written (basically copied from W3Schools) to do this. I have a test HTML page set up on the server to test the image uploads and that works just fine - the form works and the file is uploaded when the "Upload Image" button is pressed (to execute the PHP upload code). However, once the upload is complete the page switches to a blank page with the URL for my upload.php file.
I am currently using a modal in HTML to initially hide the image upload form and only appear when the "Image" button in the chat is pressed. The code is very simple, and as I said is basically the same as seen in the above link but placed inside a modal.
And before anyone complains, I know PHP is easy to exploit and can be dangerous when put on a website but this has been determined to be a non-issue in my case.
Below is the code for the image upload modal. Please pardon all the in-line CSS, I will eventually move it to its own stylesheet but have been using in-line for development purposes. Note that display is set to block for debugging. For the live site it would be set to none and a javascript function is used to set it to block when the "Image" button is pressed in the chat module.
<html>
<body>
<div id="imageUploadModal" style="display:block; position:fixed; z-index:1; left:0; top:0; width:100%; height:100%;.
overflow:auto; background-color:rgb(0,0,0); background-color:rgba(0,0,0,0.4);">
<div style="background-color:#fefefe; margin:15% auto; padding:20px; border:1px solid #888; width:80%;">
<span style="color:#aaa; float:right; font-size:28px; font-weight:bold;">×</span>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image:
<input type="file" name="fileToUpload" id="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
</div>
</div>
</body>
</html>
UPDATE:
Below are the contents of upload.php:
<?php
// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is an actual image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
//The file is an image
$uploadOk = 1;
} else {
//The file is not an image
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
//The file already exists
$uploadOk = 0;
}
// Check file size
if (2000000 < $_FILES["fileToUpload"]["size"]) {
//The file is too large
$uploadOk = 0;
}
// Allow certain file formats
if (($imageFileType != "jpg") && ($imageFileType != "png")
&& ($imageFileType != "jpeg") && ($imageFileType != "gif")) {
//Only JPG, JPEG, PNG, and GIF files are allowed
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
//The file was not uploaded
exit();
// if everything is ok, try to upload the file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
exit();
} else {
//There was an error uploading the file
exit();
}
}
?>
EDIT: Updated HTML/Javascript
// Ajax image upload
$(document).ready(function() {
$("#uploadForm").submit(function(event) {
event.preventDefault();
var $form = $("#uploadForm");
var serializedData = $form.serialize();
var request = $.ajax({
type: "POST",
url: "/upload.php",
data: serializedData
});
request.done(function() {
console.log("AJAX Success!");
closeImageUploadModal();
});
})
});
HTML:
<div id="imageUploadModal" style="display:none; position:fixed; z-index:1; left:0; top:0; width:100%; height:100%;
overflow:auto; background-color:rgb(0,0,0); background-color:rgba(0,0,0,0.4);">
<div style="background-color:#0e0e0e; color:#aaa; margin:15% auto; padding:20px; border:1px solid #888; width:50%;">
<span id="close" style="color:#aaa; float:right; font-size:28px; font-weight:bold;" onclick="closeImageUploadModal()">×</span>
<form id="uploadForm">
<h3><b>Select image:</b></h3>
<input type="file" name="fileToUpload" id="fileToUpload" accept=".jpg, .JPG, .png, .PNG, .jpeg, .JPEG, .gif, .GIF"/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
</div>
</div>
How to upload a file without refreshing or redirecting.
Method 1: Plugins
Plugins would probably be the best for you, since they are usually well tested and relatively bug free and require hardly any work to get it running. There are a number of plugins you can use, I have them listed below.
jQuery File Uploader
Multiple File Upload Plugin
Mini Multiple File Upload
jQuery File Upload
Method 2: Other StackOverflow Answers
There has been plenty of answers for this type of problem. I have listed some below.
How can I upload files asynchronously?
jQuery AJAX file upload PHP
How to use $.ajax() for input field text AND FILE upload?
jQuery Ajax File Upload
File Upload Ajax PHP
Additional Sources to look at
https://www.sanwebe.com/2012/06/ajax-file-upload-with-php-and-jquery
https://www.formget.com/ajax-image-upload-php/
If you need more sources to look at try searching:
How to upload file with AJAX and PHP
Uploading File with AJAX and PHP
Sending File to AJAX and PHP upload
File Upload AJAX and PHP
Solution
HTML
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" onclick="UploadFile()" />
</form>
<progress></progress>
JavaScript and AJAX
Note: You will need jQuery for this section. Please link the lastest
CDN to your document.
function UploadFile()
{
$.ajax({
url: 'upload.php',
type: 'POST',
data: new FormData($('form')[0]),
cache: false,
contentType: false,
processData: false,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload)
{
myXhr.upload.addEventListener('progress', function(e)
{
if (e.lengthComputable)
{
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
}, false);
}
return myXhr;
},
success: function() {
// close modal here
}
});
}
This does work since I have tested it. You will need to change your PHP a little.
Just merge your PHP code and HTML to a file and then, in the form, submit to it self.
<?php
$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];
?>
<html>
<head>
<title>Personal INFO</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
First Name:<input type="text" size="12" maxlength="12" name="Fname"><br />
Last Name:<input type="text" size="12" maxlength="36" name="Lname"><br />
</form>
<?
echo "Hello, ".$Fname." ".$Lname.".<br />";
?>

ajax form data serialization failed

I have a HTML with a form in it like this:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
</head>
<body>
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
Your Photo: <input id="thefile" type="file" name="photo" size="25" />
<input type="button" name="submit" value="Submit" onclick="submitform();"/>
</form>
</body>
<script>
function submitform()
{
data = $('*').serialize();
$.post(
'http://localhost/banksoal/1.0.0/accept-file.php',
data
);
}
</script>
</html>
and the .php script like this:
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
print_r($_FILES['photo']);
$message = 'default message';
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = 'd:\\' . '--test-- '.basename($_FILES['photo']['name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
else
{
$valid_file = true;
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], $new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
var_dump($message);
?>
The problem:
in the submitform() function, in the script tag at the line:
data = $('*').serialize();
why I get empty result?
What is wrong with the code?
Thank you
change this
data = $('*').serialize();
to
data = $('theform').serialize();
and change this
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
to
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform" name ="theform">
Give thsi a try as mentioned here: http://api.jquery.com/serialize/
$('form').submit(function() {
console.log($(this).serialize());
return false;
});
You can also use
echo json_encode($data);
http://php.net/manual/en/function.json-encode.php
You cannot upload files using Ajax, if you MUST upload files in an AJAX-like way you can use hidden iframes, set the target attribute equal to the iframe and grab the iframe's content to know whether the request has failed or not
This is what i usually do for this purpose, create a hidden iframe that will be the target to the form, something like this:
<iframe name='formTarget' src='#' style='display:none;' onload='processResult(this);'></iframe>
and in processResult you can fetch the iframe's content by:
$(results).html();
This way when the iframe is loaded it will automatically trigger the function to inform the request is complete

Ajax file upload not working in I.E

I am uploading images using ajax and php. My code is working fine in firefox. But in I.E, it doesn't work!
Here is my HTML code,
<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
body { padding: 30px }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<form action="fileup.php" method="post" enctype="multipart/form-data">
<input id="inp" type="file" name="uploadedfile" style="display:none"><br>
<input id="btn" type="submit" value="Upload File to Server" style="display:none">
</form>
<div id="fileSelect" class="drop-area">Select some files</div>
<script>
(function() {
$('form').ajaxForm({
complete: function(xhr) {
alert(xhr.responseText);
}
});
})();
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("inp");
fileElem.addEventListener("change",function(e){
document.getElementById('btn').click();
},false)
fileSelect.addEventListener("click", function (e) {
fileElem.click();
e.preventDefault();
}, false);
</script>
</body>
</html>
Here is php code,
<?php
$target_path = "images/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
In firefox the file uploads perfectly and alert comes up, But in I.E nothing happens!
From the examples page of the form plugin
Browsers that support the XMLHttpRequest Level 2 will be able to
upload files seamlessly.
IE doesn't support XMLHttpRequest Level 2.
EDIT:
Okay, it doesn't seem to be an Ajax issue, because the plugin uses a iframe fallback. You may need to refactor your javascript code
$(function(){
$('form').ajaxForm({
complete: function(xhr) {
alert(xhr.responseText);
}
});
$('#inp').change(function(e) {
$('#btn').click();
});
});
But as a side note, file drop is also not available in IE. So it only works if you select a file manually in IE. And a hidden file select will not allow the user to select a file. Raising the click event from javascript on a file input is also not possible, you have to go with a transparent file input.

uploadprogress extension : uploadprogress_get_info always returning null

i want to add a progress bar to my upload code
so i've installed uploadprogress extension ( actually i've downgraded my wamp server to wamp 2.0 as this one already has the extension but new versions seems to have problem with it )
here is my backend code
/////////////////// uploading
<?php
if (isset($_POST['upload'])) {
echo 'UPLOADING . . . <br />';
$location = './uploads';
$new= uniqid().'.'.end(explode('.' , basename($_FILES['mailfile']['name']) ));
if(move_uploaded_file( $_FILES['mailfile']['tmp_name'],"$location/$new"))
echo 'DONE !! ';
else
echo 'error';
}
/////////////// getting upload info
else if(isset($_GET['get_info']))
{
if (function_exists("uploadprogress_get_info")) {
$info = uploadprogress_get_info($_GET['get_info']);
} else {
$info = 'nofunc';
}
var_dump($info);
}
/////////////// upload form
else
{ $uploadID = substr(md5(microtime(true)), 0, 10);
?>
<form enctype="multipart/form-data" action="uploadprogress.php" method="post" >
<input type="text" name="UPLOAD_IDENTIFIER" value="<?php echo $uploadID; ?>" id="uploadIdentifier" />
<input id="file" name="mailfile" type="file" />
<input type="submit" value="Send File" id="btn" name="upload" />
</form>
<?php
}
and this is my front html/jquery code
when file is being uploaded it gets the UPLOAD_IDENTIFIER value from iframe and the sends it to the set() function which is suppose to get the upload progress via ajax calls but it always returns null
<html>
<head>
<script language="javascript" src="../../js/jquery.js"></script>
<script>
var val;
$(function(){
$('#progress_iframe').load(function() {
var ifr = $(this);
$(this)
.contents()
.find('#btn')
.bind('click', function() {
val = ifr.contents().find('#uploadIdentifier').val();
set();
// do stuff
});
});
})
function set() {
$.get('uploadprogress.php' , {get_info : val} , function(data){
data = $.trim(data);
$('#info').html(data) ;
if(data < 100 )
set();
})
}
</script>
</head>
<body>
<div>
<iframe id="progress_iframe" src="uploadprogress.php" frameborder="0"> </iframe>
<span id="info"></span>
</div>
</body>
</html>
so the file is being uploaded without any problem and i've tried a big file but still as the file was being uploaded the uploadprogress_get_info was null
Check if the UploadProgress tmp directory is accessible on the server. Meaning the "uploadprogress.file.filename_template" refers to the right tmp folder in the phpinfo.
You can run the following code to check this.
<div id="status" style="border: 1px black solid;<?php
$templateini = ini_get("uploadprogress.file.filename_template");
$testid = "thisisjustatest";
$template = sprintf($templateini, $testid);
$templateerror = false;
if ($template && $template != $templateini && #touch($template) && file_exists($template)) {
// print '('.$templateini.' is writable. The realpath is ' . str_replace($testid,"%s",realpath($template)) .')';
unlink($template);
} else {
$templateerror = true;
}
if (function_exists("uploadprogress_get_info")) {
if ($templateerror) {
print 'background-color: red;"';
print ">Problem. ";
if ($template == $templateini) {
print "uploadprogress.file.filename_template ($templateini) doesn't have an %s in it for making unique temporary files. Please adjust.<br/>";
} else {
print "$templateini is NOT writable. <br/>Please make sure the directory exists and is writable for the webserver. <br/>
Or adjust the ini setting 'uploadprogress.file.filename_template' to a correct path.";
}
} else {
print 'background-color: green;">The uploadprogress extension is installed and initial checks show everything is good';
}
} else {
?>
background-color: red;">The uploadprogress extension is not installed.
<?php } ?>
</div>
If the above code gives error, point to the correct tmp directory in the php.ini file. The following line was added in the php.ini file for Xampp tmp directory on windows localhost machine. uploadprogress.file.filename_template = C:\xampp\tmp\some_name_%s.txt
Now your code should work.

How to list the names of files successfully uploaded?

I have a a form which contains a file input and upload button
<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='stopImageUpload(this);' class='imageuploadform' >
<p class='imagef1_upload_form' align='center'><label>Image File: <input name='fileImage' type='file' class='fileImage' /></label>
<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>
</p>
<p><span class='list></span></p>
</form>
Now what I want is that if an image has finished uploading, at the bottom of this form (in the span tag 'list') I want the name(s) of the file that have been uploaded. So when a file is successfully uploaded, then it should display the name of the uploaded file. If a second file is successfully upoaded, then it displays the name of the uploaded second file below the name of the first file.
Is this possible in Javascript?
I have uploading of files all sorted out in php and javascript. Below is javascript function after uploading is complete:
function stopImageUpload(success) {
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
};
return true;
}​
This function is in the same page in the fomr but not in the same page as the uploading script but in the uploading script does call on this function using this javascript code below:
<script language="javascript" type="text/javascript">window.top.window.stopImageUpload(<?php echo $result; ?>);</script>
Below is part of the uploading php code where it uploads the file into the server:
move_uploaded_file($_FILES["fileImage"]["tmp_name"],"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
Your PHP callback should contain the name of the file currently uploaded, or even an array of all uploaded files.
Then, in the stopImageUpload function, read that second parameter and manipulate #list accordinly (update/add html):
<ul id="list"></ul>
function stopImageUpload(success, filename) {
var result;
if (success == 1)
result = '<li class="msg">The file '+filename+' was uploaded successfully!</li>';
else
result = '<li class="emsg">There was an error during upload of file '+filename+'!</li>';
$('#list').append(result);
return true;
}​

Categories