Note I am new to PHP, Apache and programming for servers so more thorough explanations will be appreciated.
Context
I created - in javascript - a progress bar to display when a file is uploaded. Current I have the progress bar update at a set frame-rate (to see if it works).
Clearly to make this an accurate progress bar, everything should in relation to the number of bytes transferred in comparison to the total number of bytes.
Question
using PHP5 how can I get information regarding the number of bytes transferred in relation to the total number of bytes of the file, such that I can pass that to a JS function updateProgress(bytesSoFar, totalBytes) to update my progress bar? Please verbosely walk me through the modifications needed to the code below to get this to work. I have seen xhr examples, but they are not thoroughly accessible.
I have just set up LocalHost and am using W3Schools' PHP File Upload tutorial. To get the simulated ''upload'' to work, I changed the local permissions as suggested in this S.O. post. I don't necessarily need to read the file, I just want to know many bytes have been transferred.
Code
Currently I have two files:
index.php
upload.php
index.php
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Update
I have found this code:
test.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_FILES["userfile"])) {
// move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
move_uploaded_file($_FILES["userfile"]["tmp_name"], "uploads/" . $_FILES["userfile"]["name"]);
}
?>
<html>
<head>
<title>File Upload Progress Bar</title>
<style type="text/css">
#bar_blank {
border: solid 1px #000;
height: 20px;
width: 300px;
}
#bar_color {
background-color: #006666;
height: 20px;
width: 0px;
}
#bar_blank, #hidden_iframe {
display: none;
}
</style>
</head>
<body>
<div id="bar_blank">
<div id="bar_color"></div>
</div>
<div id="status"></div>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST" id="myForm" enctype="multipart/form-data" target="hidden_iframe">
<input type="hidden" value="myForm" name="<?php echo ini_get("session.upload_progress.name"); ?>">
<input type="file" name="userfile"><br>
<input type="submit" value="Start Upload">
</form>
<script type="text/javascript">
function toggleBarVisibility() {
var e = document.getElementById("bar_blank");
e.style.display = (e.style.display == "block") ? "none" : "block";
}
function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}
function sendRequest() {
var http = createRequestObject();
http.open("GET", "progress.php");
http.onreadystatechange = function () { handleResponse(http); };
http.send(null);
}
function handleResponse(http) {
var response;
if (http.readyState == 4) {
response = http.responseText;
document.getElementById("bar_color").style.width = response + "%";
document.getElementById("status").innerHTML = response + "%";
if (response < 100) {
setTimeout("sendRequest()", 1000);
}
else {
toggleBarVisibility();
document.getElementById("status").innerHTML = "Done.";
}
}
}
function startUpload() {
toggleBarVisibility();
setTimeout("sendRequest()", 1000);
}
(function () {
document.getElementById("myForm").onsubmit = startUpload;
})();
</script>
</body>
</html>
progress.php
session_start();
$key = ini_get("session.upload_progress.prefix") . "myForm";
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
$message = ceil($current / $total * 100) : 100;
$message = "$message"
echo "<script type='text/javascript'>alert('$message');</script>";
}
else {
echo 100;
}
?>
Which, like my previous code, transfers the file. However, this doesn't show the bytes until the end (even though it should alert for that), also it opens a new window with the "Done." statement in the previous window.
You can check out this Php File Upload Progress Bar that may help you get started in case you insist on using Php to display progress. This uses the PECL extension APC to get uploaded file progress details. It is possible to calculate the number of bytes received by the server using the response of
apc_fetch() as per the first link.
Another interesting Track Upload Progress tutorial that uses Php's native Session Upload Progress feature.
Lastly, if you are a little open to using Javascript (or a JS library), that would be ideal. An easy to use, easy to setup, well known and a maintained library that I know of is FineUploader
You can use the Session Upload Progress feature. It's native but require some php.ini configuration.
Please, take a look at the PHP manual.
UPDATE 1
Note, you don't need to change your upload.php. You can create a new php file (ex. progress.php) and make requests to them to check the upload progress with your JS.
progress.php
<?php
$upload_id = $_GET['upload_id];
print json_encode($_SESSION['upload_progress_'.$upload_id]);
Then your JS will make a GET request to progress.php?upload_id=YourIdValue and you will receive a JSON with all progress information.
Related
here is my problem : On my website I want to allow users to upload any type of video. But with the HTML5 tag only .mp4 video can be used.
So I want to convert any type of video submit by the user to MP4 then add the path to the databse.
I've read something about FFmpeg but I can't figure out how to use it. I tried to use shell_exec("ffmpeg -i ".$vid." -vcodec libx264 -crf 20 out.mp4 2>&1") without success.
The html
<form method="post" enctype="multipart/form-data" name="form" action="post.php">
<input type="file" name="media-vid" class=" file_multi_video" accept="video/*">
</form>
The php script:
if(file_exists($_FILES['media-vid']['tmp_name']) && is_uploaded_file($_FILES['media-vid']['tmp_name']))
{
$targetvid = md5(time());
$target_dirvid = "videos/";
$target_filevid = $targetvid.basename($_FILES["media-vid"]["name"]);
$uploadOk = 1;
$videotype = pathinfo($target_filevid,PATHINFO_EXTENSION);
if ($_FILES["media-vid"]["size"] > 500000000) {
$uploadOk = 0;
echo "Sorry, your file is too large.";
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your video was not uploaded.";
// if everything is ok, try to upload file
} else {
$target_filevid = strtr($target_filevid,
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$target_filevid = preg_replace('/([^.a-z0-9]+)/i', '_', $target_filevid);
if (!move_uploaded_file($_FILES["media-vid"]["tmp_name"], $target_dirvid. $target_filevid)) {
echo "Sorry, there was an error uploading your file. Please retry.";
}else{
$vid= $target_dirvid.$target_filevid;
shell_exec("ffmpeg -i ".$vid." -vcodec libx264 -crf 20 out.mp4 2>&1");
}
}
}
Here is how I would do it:
Try out this code! ( Tested and works fine )
<form method="post" enctype="multipart/form-data" name="form">
<input type="file" name="media-vid" class=" file_multi_video" accept="video/*">
<input type="submit" name="submit" value="upload"/>
</form>
<?
if (isset($_POST['submit'])) {
if (file_exists($_FILES['media-vid']['tmp_name']) && is_uploaded_file($_FILES['media-vid']['tmp_name'])) {
$targetvid = md5(time());
$target_dirvid = "videos/";
$target_filevid = $targetvid . basename($_FILES["media-vid"]["name"]);
$uploadOk = 0;
$videotype = pathinfo($target_filevid, PATHINFO_EXTENSION);
//these are the valid video formats that can be uploaded and
//they will all be converted to .mp4
$video_formats = array(
"mpeg",
"mp4",
"mov",
"wav",
"avi",
"dat",
"flv",
"3gp"
);
foreach ($video_formats as $valid_video_format) {
//You can use in_array and it is better
if (preg_match("/$videotype/i", $valid_video_format)) {
$target_filevid = $targetvid . basename($_FILES["media-vid"] . ".mp4");
$uploadOk = 1;
break;
} else {
//if it is an image or another file format it is not accepted
$format_error = "Invalid Video Format!";
}
}
if ($_FILES["media-vid"]["size"] > 500000000) {
$uploadOk = 0;
echo "Sorry, your file is too large.";
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0 && isset($format_error)) {
echo $message;
// if everything is ok, try to upload file
} else if ($uploadOk == 0) {
echo "Sorry, your video was not uploaded.";
}
else {
$target_filevid = strtr($target_filevid, 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$target_filevid = preg_replace('/([^.a-z0-9]+)/i', '_', $target_filevid);
if (!move_uploaded_file($_FILES["media-vid"]["tmp_name"], $target_dirvid . $target_filevid)) {
echo "Sorry, there was an error uploading your file. Please retry.";
} else {
$vid = $target_dirvid . $target_filevid;
}
}
}
}
?>
Test it and let me know how it goes. If you have any other questions or need anything else, please do not hesitate to ask. I am always here to help and I would like you to have this file fully coded. Good luck bro!
Here's my background:
I'm using Amazon EC2 Linux Instance running Apache and LAMP.
I'm trying to make a PHP image upload.
I got the code from W3Schools.
I have tried signing in as Superuser (su) and changing the permissions on the upload folder (/var/www/html/photo/backend/images/uploads) to chmod 755.
I have tried running print_r($_FILES); and get Array ( ).
I've changed these things in php.ini:
set file_uploads to on
set max_execution_time to 300 (seconds)
set max_file_size to 100 (MB)
I've tried and Googled everything I can think of and I still can't figure out why my image doesn't upload. I'm sorry if this is broad, but I really don't know what the problem is.
Issue:
Image doesn't upload (no idea why, I think I've followed all the steps, see above)
Here's my code:
<?php
$target_dir = "/backend/images/uploads";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
print_r($_FILES);
}
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="/backend/images/upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Thanks for reading, and if anything doesn't make sense, please comment!
add / after uploads
change
$target_dir = "/backend/images/uploads";
to below code
$target_dir = "/backend/images/uploads/";
I have this simplified situation :
<form action='process.php' method='post'>
<div class="dropzone no-margin">
<div class="fallback">
<input name="file" type="file" multiple/>
</div>
</div>
</form>
$(".dropzone").dropzone({
url: "/test2.php",
maxFilesize: 2,
maxFiles: 5
});
test2.php works just fine, it upload files dropped on the dropzone immediately. but, the problem is, I need to pass those file names of uploaded files to the form as hidden text input.
here's test2.php looks like :
<?php
$target_dir = "user/product/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
I'm a beginner in javascript or jquery world. So, I really need your help to give me a clue how to pass the file names to the form as hidden text input so it can be written into database later on.
thank you so much and I really appreciate you help.
Try this :
there is method in Dropzone i.e sending that will use to send data before file is sent.if multiple files are uploaded then use sendingmultiple method.
$(".dropzone").dropzone({
url: "/test2.php",
maxFilesize: 2,
maxFiles: 5,
sending:function (data, xhr, formdata) {
console.log("data :",data);
//here you can get file name from data variable.you can add that to your form by following line.
formdata.append('hidden field name', 'file name');
//you can add as much parameter you want to pass to your post data by formdata.append() function. That will add data to your form data.you can refer that value by using $_POST['hidden_field_name'] at PHP side.
}
});
Please check following link for detail :
http://www.dropzonejs.com/#events
I have Ubuntu 12.04 LTS and using PHP 5.5 with Apache2 to implement the upload progress via the PHP session upload progress.
The issue is that it works sometimes and sometimes it doesn't work. I mean sometimes I get the progress percentage 100% direct at the beginning of the upload without finishing the upload (which means the $_SESSION[$key] is empty in that cases, but why?!)
I tried turning the value of session.upload_progress.cleanup to On and Off, but it didn't change anything.
You can try it yourself on this URL: http://138.128.124.172/upload_progress
In the php.ini, I have the below settings related to the upload:
;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;
; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads = On
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
;upload_tmp_dir =
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 100M
; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20
; Enable upload progress tracking in $_SESSION
; Default Value: On
; Development Value: On
; Production Value: On
; http://php.net/session.upload-progress.enabled
session.upload_progress.enabled = On
; Cleanup the progress information as soon as all POST data has been read
; (i.e. upload completed).
; Default Value: On
; Development Value: On
; Production Value: On
; http://php.net/session.upload-progress.cleanup
session.upload_progress.cleanup = Off
; A prefix used for the upload progress key in $_SESSION
; Default Value: "upload_progress_"
; Development Value: "upload_progress_"
; Production Value: "upload_progress_"
; http://php.net/session.upload-progress.prefix
;session.upload_progress.prefix = "upload_progress_"
; The index name (concatenated with the prefix) in $_SESSION
; containing the upload progress information
; Default Value: "PHP_SESSION_UPLOAD_PROGRESS"
; Development Value: "PHP_SESSION_UPLOAD_PROGRESS"
; Production Value: "PHP_SESSION_UPLOAD_PROGRESS"
; http://php.net/session.upload-progress.name
;session.upload_progress.name = "PHP_SESSION_UPLOAD_PROGRESS"
; How frequently the upload progress should be updated.
; Given either in percentages (per-file), or in bytes
; Default Value: "1%"
; Development Value: "1%"
; Production Value: "1%"
; http://php.net/session.upload-progress.freq
;session.upload_progress.freq = "1%"
; The minimum delay between updates, in seconds
; Default Value: 1
; Development Value: 1
; Production Value: 1
; http://php.net/session.upload-progress.min-freq
;session.upload_progress.min_freq = "1"
At the PHP side: I have the below code inside the page: progress.php:
session_start();
$key = ini_get("session.upload_progress.prefix") . "myForm";
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
}
else {
echo 100;
}
At the client side, I have the below code in the page index.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_FILES["userfile"])) {
// move_uploaded_file()
}
?>
<style>
#bar_blank {
border: solid 1px #000;
height: 20px;
width: 300px;
}
#bar_color {
background-color: #006666;
height: 20px;
width: 0px;
}
#bar_blank, #hidden_iframe {
display: none;
}
</style>
<html>
<head>
<title>File Upload Progress Bar</title>
</head>
<body>
<div id="bar_blank">
<div id="bar_color"></div>
</div>
<div id="status"></div>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST" id="myForm" enctype="multipart/form-data" target="hidden_iframe">
<input type="hidden" value="myForm" name="<?php echo ini_get("session.upload_progress.name"); ?>">
<input type="file" name="userfile"><br>
<input type="submit" value="Start Upload">
</form>
<iframe id="hidden_iframe" name="hidden_iframe" src="about:blank"></iframe>
</body>
</html>
<script>
function toggleBarVisibility() {
var e = document.getElementById("bar_blank");
e.style.display = (e.style.display == "block") ? "none" : "block";
}
function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}
function sendRequest() {
var http = createRequestObject();
http.open("GET", "progress.php");
http.onreadystatechange = function () { handleResponse(http) };
http.send(null);
}
function handleResponse(http) {
var response;
if (http.readyState == 4) {
response = http.responseText; //alert(response);return;
document.getElementById("bar_color").style.width = response + "%";
document.getElementById("status").innerHTML = response + "%";
if (response < 100) {
setTimeout("sendRequest()", 1000);
}
else {
toggleBarVisibility();
document.getElementById("status").innerHTML = "Done.";
document.getElementById("bar_color").style.width = 0 + "%";
}
}
}
function startUpload() {
toggleBarVisibility();
setTimeout("sendRequest()", 1000);
}
(function () {
document.getElementById("myForm").onsubmit = startUpload;
})();
</script>
I am not interested in the HTML5, Jquery or the flash. I would be thankful if you hint me also about better approaches to get a robust way to implement the upload with a progress bar.
Thanks for your help!
I use the reply part due to size of the answer. Or, size of some details...
In fact I've have the same problem, with PHP 5.5.18 running on Debian Whezzy.
After making a few test and putting a log in the progress.php in order to save the value of the $key, bytes_processed and content_length, here are my conclusions:
Discovery 1: we don't have an empty key. We have a key showing us informations with bytes_processed = content_length
Discovery 2: if you download eg 4 files with different size and then have a look at the log of your progress.php you'll see the value from the session for second file will give you the result for file 1.
Example:
Send test.docx -> 500.000 bytes. $key is empty
Send house.jpg -> 4.000.000 bytes. $key give bytes_processed = content_length = 500.000 so result of previous file
In many case, we use in the form, an hidden field like this:
echo "<input type=hidden value=\"myForm\" name=\"";
echo ini_get("session.upload_progress.name");
echo "\" />\n";
And we get the data using in progress.php:
$key = ini_get("session.upload_progress.prefix") . "myForm";
meaning ALL our $key have the same name.
I change by:
$val = time();
echo "<input type=hidden value=\"".$val."\" name=\"";
echo ini_get("session.upload_progress.name");
echo "\" />\n";
and
$key = ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")];
Now, each time I have an empty key.
My conclusion is that we have a cache problem which is what PHP.net say:
Warning
The web server's request buffering has to be disabled for this to work properly, else PHP may see the file upload only once fully uploaded. Servers such as Nginx are known to buffer larger requests.
Older post, but I'd suggest two things:
Make hidden field dynamic value
$_SESSION['ukey'] = substr(md5(uniqid(rand(), true)),0,6);
<input type="hidden" value="<?php echo $_SESSION['ukey'] ?>" name="<?php echo ini_get("session.upload_progress.name"); ?>">
By this you achieve that you can send same filenames again and it will work, you will get unique session id. Also you can use in php.ini the value session.upload_progress.cleanup = Off so data in session will be there after 100% is reached. In progres.php change to $key = ini_get("session.upload_progress.prefix") . echo $_SESSION['ukey'];
In progress script also this part of the code causing trouble:
else {
echo 100;
}
The reason is that there might be buffering in some intermediate device or apache or in the transit, so $_SESSION[$key] will be initialised even after browser already send all 100% of POST data. This is my scenario at certain ISPs. I removed this code and it is working fine. By this you achieve that AJAX will be pooling data always and not hang on this. You only need to handle exception when TCP would for some reason dropped and AJAX would be trying pooling endlessly until you close browser. But I don't know how often this would happen / if it happens.
whenever I refresh the page or leave and come back, the image disappears from the site and the database. I dont want the form to redirect to a different page, I just want it to stay on the same page but only run the query when the submit button is pressed.
<?php
$display = mysql_query("SELECT image FROM `blog_users` WHERE username = '$session->username'");
$res = mysql_fetch_array($display); echo "<image style='height: 50px; width:50px;' src='".$res['image']."'>";
$close = 0;
?>
//the above code displays the image
<?php
define ("MAX_SIZE","1000");
//This function reads the extension of the file. It is used to determine if the
// file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable is used as a flag. The value is initialized with 0 (meaning no
// error found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
//if it is not empty
if ($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and
// will not upload the file,
//otherwise we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension !=
"png") && ($extension != "gif"))
{
//print error message
echo '<h3>Unknown extension!</h3>';
$errors=1;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images
//folder)
$newname="upload/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
echo '<h3>Copy unsuccessfull!</h3>';
$errors=1;
}}}}
//this code sends the image location to the database
mysql_query("UPDATE blog_users SET image = '$newname' WHERE username = '$session->username'") ;
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) {
$_SESSION['postdata'] = $_POST;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
?>
<form name="newad" method="post" enctype="multipart/form-data"
action=""><img src="" alt="" />
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.0.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
$(document).ready(
function(){
$('input:submit').attr('disabled',true);
$('input:file').change(
function(){
if ($(this).val()){
$('input:submit').removeAttr('disabled');
}
else {
$('input:submit').attr('disabled',true);
}
});
});
</script>
</head>
<table>
<tr><td><input type="file" name="image" id="file"></td></tr>
<tr><td><input name="Submit" type="submit" value="Upload image" id="image_upload" disabled>
</td></tr>
</table>
</form>
Comments to answer to close the question.
if(isset($_POST['Submit'])){...} - ... = code to execute.
The way you have it now, is that mysql_query("UPDATE... will run regardless.
In other words, relocate the brace for it.
You have }}}}
Remove one of the braces and relocate it just before your ?> tag, and you should be good to go.
if(isset($_POST['Submit'])){
...
$errors=1;
}}}
//this code sends the image location to the database
mysql_query("UPDATE blog_users SET image = '$newname' WHERE username = '$session->username'") ;
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0) {
$_SESSION['postdata'] = $_POST;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
} // brace for if(isset($_POST['Submit']))
?>