button stopped making POST request - php

I am facing a strange issue here,I had a piece of code which was working fine until yesterday.Suddenly my button has stopped making POST Request.
Below is the sample code.When i click on the button btnsubmit ,the page gets redirected to view_teacherupdate.php but it doesnt print "button submitted";
<form method="post" action="view_teacherUpdate.php">
<input type="submit" name="btnsubmit" value="submit"/>
</form>
view_teacherUpdate.php
if(isset($_POST["btnsubmit"]))
{
echo "button submitted";
}
I have enabled error_reporting(E_ALL); but I am not getting any error or warning.
Session is enabled in both pages.
any help would be appreciated.
Thanks in advance.
Full Code:
ViewTeacherUpdatePage:
<?php
session_start();
require_once 'includewisdom/class.user.php';
//require_once 'includewisdom/class.user.php';
error_reporting(E_ALL);
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('includewisdom/login.php');
}
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';
}
}
if(isset($_POST["btnUpdateNew"]))
{
echo "hfvghfhgfhgf enter";
$TeacherID=5;
$teachername=trim($_POST["teachername"]);
$current_address=trim($_POST["current_address"]);
$teaching_locationsarray=$_POST["teaching_locations"];
$teaching_locationsarray=array_unique($teaching_locationsarray);
$teaching_location="";
foreach($teaching_locationsarray as $temp)
{
$teaching_location=$temp.",".$teaching_location;
}
$teaching_location=rtrim($teaching_location,",");
//echo $teaching_location;
$teachingzone=trim($_POST["teachingzone"]);
//$TeacherLocation[]
$TeacherLocationarray=$_POST["TeacherLocation"];
$TeacherLocationarray=array_unique($TeacherLocationarray);
$TeacherLocation="";
foreach($TeacherLocationarray as $temp)
{
$TeacherLocation=$temp.",".$TeacherLocation;
}
$TeacherLocation=rtrim($TeacherLocation,",");
//$residenceZone=trim($_POST["residenceZone"]);
//$Teaching_subject[]
$Teaching_subjectarray=$_POST["Teaching_subject"];
$Teaching_subjectarray=array_unique($Teaching_subjectarray);
$Teaching_subject="";
foreach($Teaching_subjectarray as $temp)
{
$Teaching_subject=$temp.",".$Teaching_subject;
}
$Teaching_subject=rtrim($Teaching_subject,",");
//$residenceZone=trim($_POST["residenceZone"]);
//$TeachingGroup[]
$TeachingGrouparray=$_POST["TeachingGroup"];
$TeachingGrouparray=array_unique($TeachingGrouparray);
$TeachingGroup="";
foreach($TeachingGrouparray as $temp)
{
$TeachingGroup=$temp.",".$TeachingGroup;
}
$TeachingGroup=rtrim($TeachingGroup,",");
//$residenceZone=trim($_POST["residenceZone"]);
//$edu_subject[]
$edu_subjectarray=$_POST["edu_subject"];
$edu_subjectarray=array_unique($edu_subjectarray);
$edu_subject="";
foreach($edu_subjectarray as $temp)
{
$edu_subject=$temp.",".$edu_subject;
}
$edu_subject=rtrim($edu_subject,",");
//$residenceZone=trim($_POST["residenceZone"]);
//$EducationGroup[]
$EducationGrouparray=$_POST["EducationGroup"];
$EducationGrouparray=array_unique($EducationGrouparray);
$EducationGroup="";
foreach($EducationGrouparray as $temp)
{
$EducationGroup=$temp.",".$EducationGroup;
}
$EducationGroup=rtrim($EducationGroup,",");
$residenceZone=trim($_POST["residenceZone"]);
$gender=trim($_POST["gender"]);
$board=trim($_POST["board"]);
$Qualification=trim($_POST["Qualification"]);
$enrollmentdate=trim($_POST["enrollmentdate"]);
$dob=trim($_POST["dob"]);
}
ViewTeacherPage(where button gets clicked)
<?php
session_start();
require_once 'includewisdom/class.user.php';
//require_once 'includewisdom/class.user.php';
error_reporting(E_ALL);
define('PAC_PATH','phpAutocomplete');
require_once("phpAutocomplete/conf.php");
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('includewisdom/login.php');
}
$tutorRequirement=[];
if(isset($_POST["deleteDocs"]))
{
$TeacherID=trim($_GET["id"]);
//echo $TeacherID;
$stmt1 = $user_home->runQuery("UPDATE `teacher_info` SET `idproof`='',`degree`='',`marksheet`='',`tenmarksheet`='',`degreemarksheet`='',
`additionalDocuments`='',
`addressproof`='' WHERE userid=:uid");
$stmt1->bindparam(":uid",$TeacherID);
$stmt1->execute();
//echo "sgadjfdgs";
}
if(isset($_POST["submitRequestRequirement"]))
{
$noteid=trim($_GET["noteid"]);
$tutorid=trim($_GET["id"]);
$stmtInsert="";
$stmtRequest = $user_home->runQuery("SELECT * FROM `TutorRequestRequirement` WHERE TutorID='$tutorid' and RequestID='$noteid'");
$stmtRequest->execute();
//fetch(PDO::FETCH_ASSOC)
$tutorRequirement = $stmtRequest->fetchAll(PDO::FETCH_ASSOC);
$requestRequirement=trim($_POST["requestRequirement"]);
if(count($tutorRequirement)>0)
{
$stmtInsert = $user_home->runQuery("Update TutorRequestRequirement set Requirement=:Requirement where TutorID=:TutorID and RequestID=:RequestID");
}
else
{
$stmtInsert = $user_home->runQuery("INSERT INTO `TutorRequestRequirement`(`TutorID`, `Requirement`, `RequestID`) Values
(:TutorID,:Requirement,:RequestID)");
}
$stmtInsert->bindparam(":TutorID",$tutorid);
$stmtInsert->bindparam(":Requirement",$requestRequirement);
$stmtInsert->bindparam(":RequestID",$noteid);
$result=$stmtInsert->execute();
}
if(isset($_GET["noteid"]))
{
$noteid=trim($_GET["noteid"]);
$tutorid=trim($_GET["id"]);
$stmtRequest = $user_home->runQuery("SELECT * FROM `TutorRequestRequirement` WHERE TutorID='$tutorid' and RequestID='$noteid'");
$stmtRequest->execute();
//fetch(PDO::FETCH_ASSOC)
$tutorRequirement = $stmtRequest->fetchAll(PDO::FETCH_ASSOC);
//echo count($tutorRequirement);
//var_dump($tutorRequirement);
}
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';
}
}
$stmt = $user_home->runQuery("SELECT * FROM RoleInfoWisdomManagementSystem WHERE id=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$msg = "<div class='alert alert-block' style='background:#48cfad;margin-top:10px'>
<button class='close' data-dismiss='alert'>×</button>
<strong> Your Profile Updated Successfully. </strong>
</div>";
$role=$row['role'];
$name=$row['Name'];
$TeacherID=trim($_GET["id"]);
$stmt = $user_home->runQuery("SELECT * FROM teacher_info WHERE userid=:uid");
$stmt->execute(array(":uid"=>$TeacherID));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$teachingPreferencearray=explode(",",$row["tution_type"]);
$stmtArea = $user_home->runQuery("SELECT * FROM kolkata_locations");
$stmtArea->execute();
$rowarea = $stmtArea->fetchAll();
$stmt112 = $user_home->runQuery("SELECT distinct `subject_name` FROM `subjects`");
$stmt112->execute();
$rowsubjects = $stmt112->fetchAll();
$stmt1123 = $user_home->runQuery("SELECT * FROM `subjects`");
$stmt1123->execute();
$rowTeachingsubjects = $stmt1123->fetchAll();
//$arrinbox=explode("#",$inbox);
<form method="post" action="view_teacherUpdate.php">
<button id="btnUpdate" name="btnUpdateNew" value="btnUpdateNew" type="submit" class="btn btn-success">Save</button>
</form>

The code you submitted contains 2 submit-buttons (1 < button >, 1 < input type="submit" >. Depending on the button pressed, a different value is actually submitted. I guess that the form only adds the button (or element type=submit) that was actually clicked to the POST-data (which makes sense from an UI-standpoint)
Depending on the button pressed I either got
Array ( [btnsubmit] => Verzenden )
or
Array ( [btnUpdateNew] => btnUpdateNew )
("Verzenden" is the dutch translation for Send, as the browser translates this)
So, could it be that you were pressing the wrong button by any chance?
<form method="post" action="view_teacherUpdate.php">
<input type="submit" name="btnsubmit"/>
<button id="btnUpdate" name="btnUpdateNew" value="btnUpdateNew" type="submit" class="btn btn-success">Save</button>
</form>

I think in your ViewTeacherPage(where button gets clicked), you forgot to close the <?php tag before the <form> element.

Your ViewTeacherPage.php file. In this file Last three line for html Code Is correct. But you can put this code inside php tag. So, First closed php Tag. After put your html code.
<form method="post" action="view_teacherUpdate.php">
<button id="btnUpdate" name="btnUpdateNew" value="btnUpdateNew" type="submit" class="btn btn-success">Save</button>
</form>
?>
To Replace this
?>
<form method="post" action="view_teacherUpdate.php">
<button id="btnUpdate" name="btnUpdateNew" value="btnUpdateNew" type="submit" class="btn btn-success">Save</button>
</form>

I suspect there went something wrong with the required file includewisdom/class.user.php. Did you change that file recently? There can be also corrupted database tables for the user data when trying to check if the user is logged in. Check your database and the hosting log files for any errors.
Things to do to debug this
Put error_reporting(E_ALL); at the top and then generate a division by zero warning and throw a custom error to see if PHP errors are working:
<?php
error_reporting(E_ALL);
$i = 2 / 0; // Warning: Division by zero in ...
throw new Exception('Custom error to see if errors are working.'); // Fatal error: Uncaught Exception: Custom error to see if errors are working.
session_start();
require_once 'includewisdom/class.user.php';
//require_once 'includewisdom/class.user.php';
//error_reporting(E_ALL);
$user_home = new USER();
If you see the warning and the fatal error then you can see errors and you can continue.
Also try to throw a custom error imidiately after the $user_home = new USER();; maybe there is some other code inside the class.user.php that disables error_reporting.
Directly place the POST detection immediately after the error_reporting(E_ALL);
<?php
error_reporting(E_ALL);
if(isset($_POST["btnUpdateNew"]))
{
die("POST btnUpdateNew exists");
}
session_start();
require_once 'includewisdom/class.user.php';
//require_once 'includewisdom/class.user.php';
//error_reporting(E_ALL);
$user_home = new USER();
If you don't see the message, the the PHP script does not execute at all and maybe there is some server user pool restrictions for the current user running the PHP script view_teacherupdate.php under that particular site.
If you see the POST btnUpdateNew exists after you post the form, then the form is OK and the problem is somewhere at the user managment calls new USER(); or $user_home->is_logged_in().
Maybe there is something triggering an exit. To check this, try to print something after the check and call the $user_home->is_logged_in() function like this:
<?php
session_start();
require_once 'includewisdom/class.user.php';
//require_once 'includewisdom/class.user.php';
error_reporting(E_ALL);
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('includewisdom/login.php');
}
echo "User is logged in<br>";
If you don't see the message, then you got the problem and it's hidding insinde the user managment class; at its code or logic or maybe some data corruption when trying to read user info from the database.
If you see message "User is logged in" then put a post debug at the top of view_teacherupdate.php like this:
<pre><?php print_r($_POST) ?></pre>
with this, you'll find out exactly what the $_POST array contains when the script receives POST data.
Then check the POST data and please update your question with the result!

Related

PHP Post data not received

i'm currently working on a small script for my Homepage but i ran into a problem.
I Try to upload an Image, but it seems like the POST data from the form is not being received. What did i do wrong?
I already changed the post_max_size and everything in the php.ini.
These are the Errors i get:
"Notice: Undefined index: image in ...." & "Notice: Undefined index:
submit in ...."
<form method="POST" action="/eye/sites/handling/post.php" enctype="multipart/form-data">
<div class="fileUpload">
<span><i class="fa fa-folder-o" aria-hidden="true"></i> Bild wählen</span>
<input type="file" class="upload" name="image"/>
</div>
<input type="submit" value="Upload It!" name="submit"/>
</form>
<?php session_start();
error_reporting(E_ALL);
if (isset($_SESSION["login_stat"])) {
date_default_timezone_set('Europe/Berlin');
$config = "$_SERVER[DOCUMENT_ROOT]/eye/more/config.xml";
$xml = simplexml_load_file($config);
$picWidth = $xml->pic->width;
$picHeight = $xml->pic->height;
$fulldate = date('dmYHis');
if(isset($_POST["submit"])) {
if (file_exists($_FILES['image']['tmp_name']) || is_uploaded_file($_FILES['image']['tmp_name'])) {
$typeCheck = $_FILES['image']['type'];
if ($typeCheck != "image/jpeg") {
$error = "Not a .jpg";
header('location: /eye/sites/post.php?stat=bad&error='.$error);
exit;
}
$file = $_SERVER['DOCUMENT_ROOT']."/uploads/".$fulldate.".jpg";
$type = "image/jpeg";
move_uploaded_file($_FILES['image']['tmp_name'], $file);
$file_thmb = $_SERVER['DOCUMENT_ROOT']."/uploads/!1A_thmb/".$fulldate.".jpg";
include "resize-class.php";
$resizeObj = new resize($file);
$resizeObj->resizeImage($picWidth, $picHeight, 'crop');
$resizeObj->saveImage($file_thmb, 100);
// header('location: /eye/sites/post.php?stat=good');
} else{
// header('location: /eye/sites/post.php?stat=bad&error=No File');
}
} else{
// header('location: /eye/sites/post.php?stat=bad&error=No Data');
echo $_SERVER['CONTENT_TYPE'];
echo "<br>";
echo $_FILES['image']['tmp_name'];
echo "<br>";
echo $_POST['submit'];
echo "<br>";
}
} else {
header('location: /eye/index.php?stat=in');
}
?>
Edit:
The problem is definitely about my Localhost.
This whole thing is working fine on my Webspace, but on my localhost it's not working.
BUT: I'm not getting errors anymore, when is click on Submit it goes to the php file that should save the image, but nothing is happening. I just see a white Page.
But like i said, it runs perfectly on my webspace..
If this is running on your local machine, do a quick check to make sure your "php.ini" file is configured to allow file uploads.
php.ini
file_uploads = On
The codes look fine. Check if your form action is posting to the correct path and if I may suggest using a simpler approach to test your file upload function before making it more complex. Use the following to start testing.
if (isset($_POST["submit"])) {
if (file_exists($_FILES['image']['tmp_name']) || is_uploaded_file($_FILES['image']['tmp_name'])) {
echo "Upload is working!";
}
}
Keep us updated on your findings.
Perhaps this general information will help someone, as it helped me: a submitted form will only include fields that have defined 'name' attributes. 'id' is not enough.
The idea is that 'id' identifies an element in the DOM for use by JavaScript (either as a global variable or for use in document.getElementById(ID)), but 'name' identifies those elements whose names and values will be sent to the destination ('action') page.
So it makes sense that there are two different identifying attributes, used in two different ways.

file upload return to upload html page

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!

upload error with weird error

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');
?>

How do I check uploaded file is empty?

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.';
}

Stop form submition?

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.

Categories