when I'm upload a pdf it give me the code below. it doesn't show what kind of error like the file is too large or the file is not pdf instead it print out the form in the browser.
it's not the matter the file size, I've upload the file under 5 MB, and i already change the file size into 15 MB and set my php.ini more than 10MB and it's still the same. I think there's some problem on script that i missed. if it's error it supposes show error messages from error handler or from php it self rather than the code above.
<input type="hidden" name="MAX_FILE_SIZE" value="5242880">
<fieldset><legend>Fill out the form to add a PDF to the site:</legend>
<div class="form-group has-error"><label for="title" class="control-label">Title</label><input type="text" name="title" id="title" class="form-control"><span class="help-block">Please enter the title!</span></div><div class="form-group has-error"><label for="description" class="control-label">Description</label><span class="help-block">Please enter the description!</span><textarea name="description" id="description" class="form-control"></textarea></div><div class="form-group has-error"><label for="pdf" class="control-label">PDF</label><input type="file" name="pdf" id="pdf"><span class="help-block">No file was uploaded.</span><span class="help-block">PDF only, 5MB Limit</span>
</div> <input type="submit" name="submit_button" value="Add This PDF" id="submit_button" class="btn btn-default" />
</fieldset>
</form>
<!-- END CONTENT -->
</div><!--/col-9-->
</div><!--/row-->
</div><!--/container-->
</div><!--/wrap-->
<div id="footer">
<div class="container">
<p class="text-muted credit"><span class="pull-left">Site Map | Policies</span> <span class="pull-right">© Knowledge is Power - 2013</span></p>
</div>
</div>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
0
here's the PHP code:
<?php
// This page is used by an administrator to add a PDF to the site.
// This script is created in Chapter 5.
// Require the configuration before any PHP code as the configuration controls error reporting:
require('./includes/config.inc.php');
// If the user isn't logged in as an administrator, redirect them:
redirect_invalid_user('user_admin');
// Require the database connection:
require(MYSQL);
// Include the header file:
$page_title = 'Add a PDF';
include('./includes/header.html');
// For storing errors:
$add_pdf_errors = array();
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Check for a title:
if (!empty($_POST['title'])) {
$t = escape_data(strip_tags($_POST['title']), $dbc);
} else {
$add_pdf_errors['title'] = 'Please enter the title!';
}
// Check for a description:
if (!empty($_POST['description'])) {
$d = escape_data(strip_tags($_POST['description']), $dbc);
} else {
$add_pdf_errors['description'] = 'Please enter the description!';
}
// Check for a PDF:
if (is_uploaded_file($_FILES['pdf']['tmp_name']) && ($_FILES['pdf']['error'] === UPLOAD_ERR_OK)) {
// Get a reference:
$file = $_FILES['pdf'];
// Find the size:
$size = ROUND($file['size']/1024);
// Validate the file size (5MB max):
if ($size > 15120) {
$add_pdf_errors['pdf'] = 'The uploaded file was too large.';
}
// Validate the file type:
// Create the resource:
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
// Check the file:
if (finfo_file($fileinfo, $file['tmp_name']) !== 'application/pdf') {
$add_pdf_errors['pdf'] = 'The uploaded file was not a PDF.';
}
// Close the resource:
finfo_close($fileinfo);
// Move the file over, if no problems:
if (!array_key_exists('pdf', $add_pdf_errors)) {
// Create a tmp_name for the file:
$tmp_name = sha1($file['name']) . uniqid('',true);
// Move the file to its proper folder but add _tmp, just in case:
$dest = PDFS_DIR . $tmp_name . '_tmp';
if (move_uploaded_file($file['tmp_name'], $dest)) {
// Store the data in the session for later use:
$_SESSION['pdf']['tmp_name'] = $tmp_name;
$_SESSION['pdf']['size'] = $size;
$_SESSION['pdf']['file_name'] = $file['name'];
// Print a message:
echo '<div class="alert alert-success"><h3>The file has been uploaded!</h3></div>';
} else {
trigger_error('The file could not be moved.');
unlink ($file['tmp_name']);
}
} // End of array_key_exists() IF.
} elseif (!isset($_SESSION['pdf'])) { // No current or previous uploaded file.
switch ($_FILES['pdf']['error']) {
case 1:
case 2:
$add_pdf_errors['pdf'] = 'The uploaded file was too large.';
break;
case 3:
$add_pdf_errors['pdf'] = 'The file was only partially uploaded.';
break;
case 6:
case 7:
case 8:
$add_pdf_errors['pdf'] = 'The file could not be uploaded due to a system error.';
break;
case 4:
default:
$add_pdf_errors['pdf'] = 'No file was uploaded.';
break;
} // End of SWITCH.
} // End of $_FILES IF-ELSEIF-ELSE.
if (empty($add_pdf_errors)) { // If everything's OK.
// Add the PDF to the database:
$fn = escape_data($_SESSION['pdf']['file_name'], $dbc);
$tmp_name = escape_data($_SESSION['pdf']['tmp_name'], $dbc);
$size = (int) $_SESSION['pdf']['size'];
$q = "INSERT INTO pdfs (title, description, tmp_name, file_name, size) VALUES ('$t', '$d', '$tmp_name', '$fn', $size)";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) === 1) { // If it ran OK.
// Rename the temporary file:
$original = PDFS_DIR . $tmp_name . '_tmp';
$dest = PDFS_DIR . $tmp_name;
rename($original, $dest);
// Print a message:
echo '<div class="alert alert-success"><h3>The PDF has been added!</h3></div>';
// Clear $_POST:
$_POST = array();
// Clear $_FILES:
$_FILES = array();
// Clear $file and $_SESSION['pdf']:
unset($file, $_SESSION['pdf']);
} else { // If it did not run OK.
trigger_error('The PDF could not be added due to a system error. We apologize for any inconvenience.');
unlink ($dest);
}
} // End of $errors IF.
} else { // Clear out the session on a GET request:
unset($_SESSION['pdf']);
} // End of the submission IF.
// Need the form functions script, which defines create_form_input():
require('includes/form_functions.inc.php');
?><h1>Add a PDF</h1>
<form enctype="multipart/form-data" action="add_pdf.php" method="post" accept-charset="utf-8">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880">
<fieldset><legend>Fill out the form to add a PDF to the site:</legend>
<?php
create_form_input('title', 'text', 'Title', $add_pdf_errors);
create_form_input('description', 'textarea', 'Description', $add_pdf_errors);
// Add the file input:
echo '<div class="form-group';
// Add classes, if applicable:
if (array_key_exists('pdf', $add_pdf_errors)) {
echo ' has-error';
} else if (isset($_SESSION['pdf'])) {
echo ' has-success';
}
echo '"><label for="pdf" class="control-label">PDF</label><input type="file" name="pdf" id="pdf">';
// Check for an error:
if (array_key_exists('pdf', $add_pdf_errors)) {
echo '<span class="help-block">' . $add_pdf_errors['pdf'] . '</span>';
} else { // No error.
// If the file exists (from a previous form submission but there were other errors),
// store the file info in a session and note its existence:
if (isset($_SESSION['pdf'])) {
echo '<p class="lead">Currently: "' . $_SESSION['pdf']['file_name'] . '"</p>';
}
} // end of errors IF-ELSE.
echo '<span class="help-block">PDF only, 5MB Limit</span>
</div>';
?>
<input type="submit" name="submit_button" value="Add This PDF" id="submit_button" class="btn btn-default" />
</fieldset>
</form>
<?php // Include the HTML footer:
include('./includes/footer.html');
?>
Related
I'm looking to return to the previous page after a file upload and have "file uploaded successfully" on the upload page.
In upload.php at the top I have placed
sesssion_start();
And at the end of the file upload script I have placed
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
Now I know i need to put some code into the html document but unsure what needs to go in. Below is my html form script
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000" />
Select video to upload:
Please choose a file: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
I know it is going to be something similar to this but unsure how or where I would place it.
session_start();
if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) {
echo "File uploaded successfully";
}
If someone could walk me through adding the HTML code into the correct place I will be very greatful
After the comments i amend my php code to look like this.
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
sesssion_start();
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name'] );
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'] , $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name'] ). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
exit();
And the syntax inside the stream.php to:
<?phpsession_start();
if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) {
echo "File uploaded successfully";
}
?>
Thanks,
Mark
Nota: You also cannot use echo and header together because that would considered as outputting before header, so we'll just use a session array as the message and the header to redirect to "upload_form.php", then show the respective message on that page afterwards.
Use session_destroy() also to destroy any previous sessions.
Sidenote: Use two seperate files.
HTML form: call this "upload_form.php"
<?php
session_start();
session_destroy();
?>
<form action="stream.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000" />
Select video to upload:
Please choose a file: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File">
</form>
<?php
if(isset($_SESSION['upload_success'])){
echo $_SESSION['upload_success'];
}
else{
echo "Please select a file.";
}
?>
PHP (file 2): call this "stream.php"
<?php
session_start();
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name'] );
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'] , $target))
{
$_SESSION['upload_success'] = "File successfully uploaded.";
header("Location: upload_form.php");
exit;
}
else {
$_SESSION['upload_success'] = "Sorry, there was a problem uploading your file.";
header("Location: upload_form.php");
exit;
}
Edit:
Modify and add the following after if(move_uploaded_file...
if(isset($_FILES['uploadedfile']) && !empty($_FILES['uploadedfile'])){
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name']);
}
Your code works fine, but you should remove session['upload_success'] with unset function after you do echo success message.
try
unset( $_SESSION['upload_success'])
in stream.php right after
echo "File uploaded successfully";
update :
if you want to work all these on a single page, You can simply do it like below:
if(isset($_SESSION['upload_success']) and $_SESSION['upload_session'])
{
//echo success message
//remove session
}
if(isset($_POST['file'])){
//upload process , if it was successfull make seesion true...
}
else {
//show form
}
For a quick solution, you could use Ravi Kusuma's jQuery File Upload Plugin or an AJAX solution to do this.
Another alternative, though, to those proposed above is to programmatically construct / output an HTML form with some javascript, and get it to POST a message to stream.php:
CAVEAT: I haven't tried this myself, but I can't think why it wouldn't work. Would someone please confirm my sanity? -- Tested it myself: it works.
<?php
//upload.php
//Do file upload stuff, then:
$out = '
<form id="frmUpOkay" action="stream.php" method="post">
<input name="upMsg" value="Upload Successful" />
</form>
<script type="text/javascript">
$(function(){
$("#frmUpOkay").submit();
});
</script>
';
echo $out;
?>
You must also add this bit to the top of the stream.php file:
<?php
if ( isset($_POST['upMsg']) && isset($_POST['upMsg']) != '' ){
$upMsg = $_POST['upMsg']; //you should sanitize this input
}else{
$upMsg = '';
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div>
Your normal website content is here.<br>
<br>
Upload message: <?php echo $upMsg; ?> <br>
<br>
</div>
</body>
Notes:
Above code uses jQuery, so you would need the jQuery library included on your upload.php page (as shown above).
Placing
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
At the end, I believe, would set true no matter what actually happened with the file's upload the reason being, there is not a condition being checked.
Unless the script has an exit command when it fails, it will eventually get to the part where it says: "Set the upload success as true and then go to stream.php" rather than saying, "If the upload is successful, set the upload success as true and then go to stream.php"
I would try:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
if($_FILES['uploadedfile']['size'] == 0)//In other words, if no file was selected.
{
$_SESSION['upload_success'] = 4;//File wasn't selected
header("Location: stream.php");
exit();
}
if(!file_exists('upload/' . basename($_FILES['uploadedfile']['name'])))
{
$_SESSION['upload_success'] = (move_uploaded_file($_FILES['uploadedfile']['tmp_name'],'upload/' . basename($_FILES['uploadedfile']['name'])) ? 1 : 2);
}
elseif(file_exists('upload/' . basename($_FILES['uploadedfile']['name'])))
{
$_SESSION['upload_success'] = 3;
}
header("Location: stream.php");
exit();
?>
Now in stream.php where you have your if statement that displays the message do this instead:
<?php
session_start();
switch (#$_SESSION['upload_success']) {
case 1:
echo "File uploaded successfully";
break;
case 2:
echo "Sorry, there was a problem uploading your file.";
break;
case 3:
echo "A file with that name already exists!";
break;
case 4:
echo "You must select a file to upload!";
break;
}
unset($_SESSION['upload_success']);
?>//So if you reload stream.php yet another time no messages will be displayed again for no reason. ie. none of the cases will match an unset variable.
Last, you cannot echo (or do any type of output meant to be viewed by a user) before you header(Location: "somepage.php");
The page will switch before the user can read the output.
The way your code is currently written in your question you could have the following happen:
The server echos "Sorry, there was a problem uploading your file", which will never be seen by the user.
$_SESSION['upload_success'] is then set to TRUE, which is obviously not in agreement with #1.
It then sends the user to stream.php where a success message is
displayed.
An alternate, lazier way with less useful scenario descriptions to also fix your problem would be to do this instead (in upload.php):
else
{
die("Sorry, there was a problem uploading your file.");
}
Hope that helps!
I have a file upload page that works but I'm trying to do some error alerts to choose if you want to replace or not.
This is my php file that does the upload
<?php
require ("connect.php");
$filename = "docs/".$_FILES['datafile']['name']."";
$d=explode(".",$_FILES['datafile']['name']);
if (file_exists($filename)) {
echo "<script>alert('Full dump for ".$d[0]." already exists.')</script>";
$error = 1;
} else {
$target_path = "docs/";
$target_path = $target_path . basename( $_FILES['datafile']['name']);
if(move_uploaded_file($_FILES['datafile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['datafile']['name'])." has been uploaded";
$error = 0;
}
else
{
echo "There was an error uploading the file, please try again!";
$error = 1;
}
}
if ($error != 1)
{
$r1 = mysql_query("insert into full_dump (file_name) values ('".$_FILES['datafile']['name']."')")or die(mysql_error());
$file1 = "docs/".$_FILES['datafile']['name']."";
$lines = file($file1);
$count = count($lines);
$fp = fopen("docs/".$_FILES['datafile']['name']."","r");
$data=fread($fp,filesize("docs/".$_FILES['datafile']['name'].""));
$tmp=explode ("\n", $data);
for ($i=0; $i<$count; $i++)
{
$a=$tmp[$i];
$b=$i+1;
$r2 = mysql_query("update full_dump set field_".$b."='".$a."' where file_name='".$_FILES['datafile']['name']."'")or die(mysql_error());
}
echo"</br>";
echo "Uploading Complete</br>";
echo "Uploaded File Info:</br>";
echo "Sent file: ".$_FILES['datafile']['name']."</br>";
echo "File size: ".$_FILES['datafile']['size']." bytes</br>";
echo "File type: ".$_FILES['datafile']['type']."</br>";
}
?>
What I want to have is instead of
if (file_exists($filename)) {
echo "<script>alert('Full dump for ".$d[0]." already exists.')</script>";
$error = 1;
}
to have an alert if I would like to replace the file or not. If it's yes it would replace the file, delete the old record in the db and insert the new record. I it's no don't do nothing...or show a message "canceled by user". Could I have $error to be assigned a value for YES or NO on user choosing or not to replace?
UPDATE
This is the form page for upload.
<html>
<head>
<script language="Javascript">
function fileUpload(form, action_url, div_id) {
// Create the iframe...
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "upload_iframe");
iframe.setAttribute("name", "upload_iframe");
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("border", "0");
iframe.setAttribute("style", "width: 0; height: 0; border: none;");
// Add to document...
form.parentNode.appendChild(iframe);
window.frames['upload_iframe'].name = "upload_iframe";
iframeId = document.getElementById("upload_iframe");
// Add event...
var eventHandler = function () {
if (iframeId.detachEvent) iframeId.detachEvent("onload", eventHandler);
else iframeId.removeEventListener("load", eventHandler, false);
// Message from server...
if (iframeId.contentDocument) {
content = iframeId.contentDocument.body.innerHTML;
}
else if (iframeId.contentWindow) {
content = iframeId.contentWindow.document.body.innerHTML;
}
else if (iframeId.document) {
content = iframeId.document.body.innerHTML;
}
document.getElementById(div_id).innerHTML = content;
// Del the iframe...
setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
}
if (iframeId.addEventListener) iframeId.addEventListener("load", eventHandler, true);
if (iframeId.attachEvent) iframeId.attachEvent("onload", eventHandler);
// Set properties of form...
form.setAttribute("target", "upload_iframe");
form.setAttribute("action", action_url);
form.setAttribute("method", "post");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("encoding", "multipart/form-data");
// Submit the form...
form.submit();
document.getElementById(div_id).innerHTML = "Uploading...";}
</script>
</head>
<body>
<form enctype=\"multipart/form-data\" method=\"POST\">
<input type="file" name="datafile" />
<input type="button" value="upload" onClick="fileUpload(this.form,'file_upload.php','upload'); return false;" >
<div id="upload"></div>
</form>
<?php
require("connect.php");
$result = mysql_query("SELECT * FROM full_dump")or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "Job number: ".$row['file_name']."</br>";
}
?>
you should do this with ajax... when you will send ajax request you will check if file exist or not .. if yes return eg -1 and ask user for relapsing ...
Enjoy :)
instead of using upload code on same page. do one thing, upload file by using ajax request. then check on backend site file is aleady exist or not and according to that show message as you like
I am attempting to do some validation on uploaded images. When I check to see if any images have been selected and uploaded it should return an error message if no images have been uploaded. But in my method it always returns false.
Heres the method:
class event{
private $dbh;
private $post_data;
public function __construct($post_data, PDO $dbh){
$this->dbh = $dbh;
$this->post_data = array_map('trim', $post_data);
}
public function checkValidImages(){
$errors = array();
if(empty($this->post_data['event-images'])){
$errors[] = 'Please select at least one image to upload.';
}
if(count($errors) > 0){
return $errors;
}else{
return FALSE;
}
}
and calling it here:
// Check all images are valid
$images = new event($_FILES, $dbh);
var_dump($imageErrors = $images->checkValidImages());
The var_dump() returns bool(false).
heres the form:
<form name="submit-event" action="submit-event.php" method="post" enctype="multipart/form-data">
<div class="large-12 columns no-padding">
<p>Select images for this event</p><br />
<input type="file" class="right" name="event-images[]" size="50" multiple="multiple" />
</div>
</form>
So why is my method returning false even when I don't select any images.
When an HTML file input is left empty, the browser will still submit the name of the form element, so you will still get that entry in the $_FILES array, but with an error code of UPLOAD_ERR_NO_FILE and a filename of "".
You should check the error code anyway as lots of things can go wrong. So your validation code becomes something like:
$numOkayFiles = 0;
$numIntendedFiles = 0;
foreach ($_FILES['event-images']['error'] as $errorCode) {
$numIntendedFiles += ($errorCode != UPLOAD_ERR_NO_FILE);
switch ($errorCode) {
case UPLOAD_ERR_OK:
$numOkayFiles++;
break;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
$errors[] = 'Your file was bigger than the maximum allowed size.';
break;
case UPLOAD_ERR_NO_FILE:
// ignore
break;
default:
$errors[] = 'A problem occured during file upload.';
}
}
if ($numIntendedFiles == 0) {
$errors[] = 'Please select at least one image to upload.';
}
I have a form which stores data to mysql.It works fine and there are no errors.The form contains name,price,category and image field when i click on submit button the data is inserting into database perfectly.but when i miss uploading an image it is not submitting but the page is refreshing when i click on submit button by which i am lossing all the data of other fileds.Finaly, what my doubt is i need to stop refresh when i miss uploading a image.
Mycode is
<form enctype="multipart/form-data" action="#" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<label>Name:</label><input type="text" name="name" id="name" size="25"/><br />
<label >Price:</label><input type="text" name="price" id="price" size="25"/><br />
<label>category:</label>
<?php
$con=mysql_connect("","","");
if(!$con)
{
die('couldnot connect to database'.mysql_error());
}
mysql_select_db("dbname",$con);
$dropdown=0;
$result=mysql_query("select DISTINCT(category) from category") or die("No such table"."<br/><br/>".mysql_error());
while($row=mysql_fetch_array($result))
{
$dropdown.="\r\n<option value='{$row['category']}'>{$row['category']} </option>";
}
?>
<?php echo "<select name= 'category' id='category' style='width:14em;'>".$dropdown."</select>";?><br />
<label style="color:#FFFFFF;font-weight:bold">Description:</label></td><td> <input type="text" name="description" id="des"
size="40"/><br />
<label style="color:#FFFFFF;font-weight:bold">Upload Image:</label></td><td><input name="userfile" type="file" /><br /><br
>
<input type="submit" value="Submit" id="submit" style="color:#2594BA;font-size:18px;text-decoration:none;background:#FFF;
padding:3px;border-radius:5px;padding-left:8px;padding-right:8px;"/><br><div id="errormessage">insert data</div>
</form>
</div>
<?php
if(!isset($_FILES['userfile']))
{
}
else
{
try {
$msg= upload(); //this will upload your image
echo $msg; //Message showing success or failure.
}
catch(Exception $e) {
echo $e->getMessage();
echo 'Sorry, could not upload file';
}
}
// the upload function
function upload() {
if(empty($_FILES['userfile']))
{
die();
}
/*database connection code;*/
$maxsize = 10000000; //set to approx 10 MB
//check associated error code
if($_FILES['userfile']['error']==UPLOAD_ERR_OK) {
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
if( $_FILES['userfile']['size'] < $maxsize) {
$imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
mysql_connect($host, $user, $pass) OR DIE (mysql_error());
mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());
$sql = "INSERT INTO menu(name,description,price,picture,category)
VALUES
('{$_POST['name']}','{$_POST['description']}','{$_POST['price']}','images/{$_FILES['userfile']['name']}','{$_POST['category']}');";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg='<p>data successfully inserted into database with id ='. mysql_insert_id().' </p>';
}
else {
$msg='<div>File exceeds the Maximum File limit</div>
<div>Maximum File limit is '.$maxsize.' bytes</div>
<div>File '.$_FILES['userfile']['name'].' is '.$_FILES['userfile']['size'].
' bytes</div><hr />';
}
}
else
$msg="File not uploaded successfully.";
}
else
{
$msg= file_upload_error_message($_FILES['userfile']['error']);
echo $msg;
}
}
// Function to return error message based on error code
function file_upload_error_message($error_code) {
switch ($error_code) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:
return 'File upload stopped by extension';
default:
return 'Unknown upload error';
}
}
?>
You can use javascript to validate and limit the form submission like below. It returns false if the userfile field is empty.
function validate_form(thisform)
{
with (thisform)
{
if (userfile.value==="")
{
return false;
}
}
return true;
}
in your for tag
<form onsubmit="return validate_form(this)">
You can add the html5 "required" attribute in the client side.
You can also validate in the JS by checking if it's value is null. For that you can use javascript's document.getElementsByName method or you can use Jquery's $('#id').val() method.
PS: I would recommend that you validate it server-side as well.
Stopping the page refresh server side is needlessly complex. This is because, according to the Request-Response model, the user has made their request. The page refresh has all but happened. But what you can do, is use some client side script to prevent the request from ever firing. Most commonly, Javascript is perfect for this:
function validate()
{
if($('nameTxt').text() != "" && $('otherTxt').text() != "" ...)
{
this.submit();
}
}
NOTE: I've assumed the use of jQuery in my example. People often use frameworks with javascript, but this isn't necessary. See JJPA's answer for a Framework free option.
I have solved my problem. I have just added validation to file type.That's it.
and thanks for your valuable suggestions.
Hopefully someone here might have an answer to my question.
I have a basic form that contains simple fields, like name, number, email address etc and 1 file upload field.
I am trying to add some validation into my script that detects if the file is too large and then rejects the user back to the form to select/upload a smaller file.
My problem is, if a user selects a file that is bigger than my validation file size rule and larger than php.ini POST_MAX_SIZE/UPLOAD_MAX_FILESIZE and pushes submit, then PHP seems to try process the form only to fail on the POST_MAX_SIZE settings and then clears the entire $_POST array and returns nothing back to the form.
Is there a way around this? Surely if someone uploads something > than the max size configured in the php.ini then you can still get the rest of the $_POST data???
Here is my code.
<?php
function validEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "#");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
} else {
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
}
return $isValid;
}
//setup post variables
#$name = htmlspecialchars(trim($_REQUEST['name']));
#$emailCheck = htmlspecialchars(trim($_REQUEST['email']));
#$organisation = htmlspecialchars(trim($_REQUEST['organisation']));
#$title = htmlspecialchars(trim($_REQUEST['title']));
#$phone = htmlspecialchars(trim($_REQUEST['phone']));
#$location = htmlspecialchars(trim($_REQUEST['location']));
#$description = htmlspecialchars(trim($_REQUEST['description']));
#$fileError = 0;
#$phoneError = "";
//setup file upload handler
$target_path = 'uploads/';
$filename = basename( #$_FILES['uploadedfile']['name']);
$max_size = 8000000; // maximum file size (8mb in bytes) NB: php.ini max filesize upload is 10MB on test environment.
$allowed_filetypes = Array(".pdf", ".doc", ".zip", ".txt", ".xls", ".docx", ".csv", ".rtf"); //put extensions in here that should be uploaded only.
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
if(!is_writable($target_path)) die('You cannot upload to the specified directory, please CHMOD it to 777.'); //Check if we can upload to the specified upload folder.
//display form function
function displayForm($name, $emailCheck, $organisation, $phone, $title, $location, $description, $phoneError, $allowed_filetypes, $ext, $filename, $fileError)
{
//make $emailCheck global so function can get value from global scope.
global $emailCheck;
global $max_size;
echo '<form action="geodetic_form.php" method="post" name="contact" id="contact" enctype="multipart/form-data">'."\n".
'<fieldset>'."\n".'<div>'."\n";
//name
echo '<label for="name"><span class="mandatory">*</span>Your name:</label>'."\n".
'<input type="text" name="name" id="name" class="inputText required" value="'. $name .'" />'."\n";
//check if name field is filled out
if (isset($_REQUEST['submit']) && empty($name))
{
echo '<label for="name" class="error">Please enter your name.</label>'."\n";
}
echo '</div>'."\n". '<div>'."\n";
//Email
echo '<label for="email"><span class="mandatory">*</span>Your email:</label>'."\n".
'<input type="text" name="email" id="email" class="inputText required email" value="'. $emailCheck .'" />'."\n";
// check if email field is filled out and proper format
if (isset($_REQUEST['submit']) && validEmail($emailCheck) == false)
{
echo '<label for="email" class="error">Invalid email address entered.</label>'."\n";
}
echo '</div>'."\n". '<div>'."\n";
//organisation
echo '<label for="phone">Organisation:</label>'."\n".
'<input type="text" name="organisation" id="organisation" class="inputText" value="'. $organisation .'" />'."\n";
echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n";
//title
echo '<label for="phone">Title:</label>'."\n".
'<input type="text" name="title" id="title" class="inputText" value="'. $title .'" />'."\n";
echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n";
//phone
echo '<label for="phone"><span class="mandatory">*</span>Phone <br /><span class="small">(include area code)</span>:</label>'."\n".
'<input type="text" name="phone" id="phone" class="inputText required" value="'. $phone .'" />'."\n";
// check if phone field is filled out that it has numbers and not characters
if (isset($_REQUEST['submit']) && $phoneError == "true" && empty($phone)) echo '<label for="email" class="error">Please enter a valid phone number.</label>'."\n";
echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n";
//Location
echo '<label class="location" for="location"><span class="mandatory">*</span>Location:</label>'."\n".
'<textarea name="location" id="location" class="required">'. $location .'</textarea>'."\n";
//check if message field is filled out
if (isset($_REQUEST['submit']) && empty($_REQUEST['location'])) echo '<label for="location" class="error">This field is required.</label>'."\n";
echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n";
//description
echo '<label class="description" for="description">Description:</label>'."\n".
'<textarea name="description" id="queryComments">'. $description .'</textarea>'."\n";
echo '</div>'."\n". '</fieldset>'."\n".'<fieldset>'. "\n" . '<div>'."\n";
//file upload
echo '<label class="uploadedfile" for="uploadedfile">File:</label>'."\n".
'<input type="file" name="uploadedfile" id="uploadedfile" value="'. $filename .'" />'."\n";
// Check if the filetype is allowed, if not DIE and inform the user.
switch ($fileError)
{
case "1":
echo '<label for="uploadedfile" class="error">The file you attempted to upload is not allowed.</label>';
break;
case "2":
echo '<label for="uploadedfile" class="error">The file you attempted to upload is too large.</label>';
break;
}
echo '</div>'."\n". '</fieldset>';
//end of form
echo '<div class="submit"><input type="submit" name="submit" value="Submit" id="submit" /></div>'.
'<div class="clear"><p><br /></p></div>';
} //end function
//setup error validations
if (isset($_REQUEST['submit']) && !empty($_REQUEST['phone']) && !is_numeric($_REQUEST['phone'])) $phoneError = "true";
if (isset($_REQUEST['submit']) && $_FILES['uploadedfile']['error'] != 4 && !in_array($ext, $allowed_filetypes)) $fileError = 1;
if (isset($_REQUEST['submit']) && $_FILES["uploadedfile"]["size"] > $max_size) $fileError = 2; echo "this condition " . $fileError;
$POST_MAX_SIZE = ini_get('post_max_size');
$mul = substr($POST_MAX_SIZE, -1);
$mul = ($mul == 'M' ? 1048576 : ($mul == 'K' ? 1024 : ($mul == 'G' ? 1073741824 : 1)));
if ($_SERVER['CONTENT_LENGTH'] > $mul*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) echo "too big!!";
echo $POST_MAX_SIZE;
if(empty($name) || empty($phone) || empty($location) || validEmail($emailCheck) == false || $phoneError == "true" || $fileError != 0)
{
displayForm($name, $emailCheck, $organisation, $phone, $title, $location, $description, $phoneError, $allowed_filetypes, $ext, $filename, $fileError);
echo $fileError;
echo "max size is: " .$max_size;
echo "and file size is: " . $_FILES["uploadedfile"]["size"];
exit;
} else {
//copy file from temp to upload directory
$path_of_uploaded_file = $target_path . $filename;
$tmp_path = $_FILES["uploadedfile"]["tmp_name"];
echo $tmp_path;
echo "and file size is: " . filesize($_FILES["uploadedfile"]["tmp_name"]);
exit;
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$path_of_uploaded_file))
{
echo 'error while copying the uploaded file';
}
}
//test debug stuff
echo "sending email...";
exit;
}
?>
PHP is returning this error in the log:
[29-Apr-2010 10:32:47] PHP Warning: POST Content-Length of 57885895 bytes exceeds the limit of 10485760 bytes in Unknown on line 0
Excuse all the debug stuff :)
FTR, I am running PHP 5.1.2 on IIS.
PHP throws all the POST data away because there was no room to put it. There is nothing reliable to be had from only part of the data.
I would work around this problem by uploading the necessary files in a separate step, a different form. You can store the values already obtained in session, ensuring they are not lost because of excessive POST data.
Erisco is right, this will need to be broken down into multiple steps. I do not believe, however, that there is any need to expose this back-end delineation to the user, so I would recommend one of the following courses of action:
Break the file upload into a separate <form> element. When the submit action is taken on either form, cancel the default action, and instead do one of the two things:
Submit the regular form data via AJAX, and when that is complete submit the uploaded file via the standard process (involving the page reloading and what-not)
Check out this example of iFrame trickery to upload the file first, ensure it is not too large, and prevent the page from even reloading if it would not otherwise pass. If the file does pass, store its identifier in a hidden input element and submit the form normally. Take whatever action is appropriate if the file does not upload correctly. Note that this solution does not require you to use the PHP session, just a little bit of response trickery.
You might try seeing if you can read anything from php://input or php://stdin after you find the _POST array has been nuked. You may be able to retrieve the POST data from there and process it manually, but the manual also says that this will not work for //input if your form is using enctype=multipart/form-data
"Try moving the file field to the
bottom of the form and see what
happens. – Marc B"
Unfortunately the same happens: the $_POST array is cleared.
So the iFrame trickery seems to be one of the best solutions. Thanks for that, Dereleased!
one of the tricks is to use something like this:
$lE = error_get_last();
if ( !empty($lE) && strpos($lE['message'] , 'POST Content-Length' ) !== false)
{
die ('Naughty naughty. you can only upload xxxxx bytes');
}