How do I check uploaded file is empty? - php

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

Related

button stopped making POST request

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!

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

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.

How to make codeigniter sticky form when error comes from upload file field

I have a form that allows user to upload multiple files. Additionaly user have to fill other input text fields like address, email etc.
I don't know how to make form sticky if error comes from file uploading and how to access error messages set by form_validation library. Because if for example one of the filetype is not allowed I use redirect to step out of the loop responsible for uploading every file.
To keep upload error message I use $this->session->set_flashdata('errors', $errors) but then I'm not able to use error messages from form_validation library ( echo form_error('field_name) ) and display user input in form fields ( echo set_value('field_name'))
Here is controller method responsible for file upload and data insert:
function do_upload()
{
// load form validation library
$this->load->library('form_validation');
// set validation rules
$this->form_validation->set_rules('email','Email','trim|required|valid_email|matches[confirm_email]');
$this->form_validation->set_rules('confirm_email','Email','trim|required|valid_email');
$this->form_validation->set_rules('delivery_name','Nazwa','trim|required');
$this->form_validation->set_rules('delivery_street','Ulica','trim|required');
$this->form_validation->set_rules('delivery_city','Miasto','trim|required');
$this->form_validation->set_rules('delivery_postcode','Kod pocztowy','trim|required');
$this->form_validation->set_rules('delivery_country','Kraj','trim|required');
$this->form_validation->set_rules('captcha','Captcha','callback_check_captcha');
if ( $this->form_validation->run() )
{
// if validation passes I insert form data into database and I start to upload
// all the files using foreach loop
$config['upload_path'] = './uploads/upload_directory';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$upload_data = array();
$task_address_id_array = $this->MTasks->insertNewTask($task_directory);
$task_id = $task_address_id_array['task_id'];
$address_id = $task_address_id_array['address_id'];
// iterate over files to be uploaded
foreach ($_FILES as $key => $value)
{
if (!empty($value['name']))
{
$this->upload->initialize($config);
$result = $this->upload->do_upload($key);
if (!$result)
{
// if upload error occurs I need to redirect to break the loop
$errors = $this->upload->display_errors();
$this->session->set_flashdata('errors', $errors);
redirect();
}
else
{
$current_upload_data = $this->upload->data();
// insert upload data to database
$this->MTasks->insertFileInfo($current_upload_data,$task_id);
}
}
}
redirect('upload/success_message');
}
else
{
$this->load->view('include/header');
$this->load->view('upload_form',$this->data);
$this->load->view('include/footer');
}
}
The main problem is you can not put as validation rule file uploads, because the library executes one by one.
A simple solution is to validate your fields and then validate the file upload. Example:
<?php
function save()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$this->form_validation->set_error_delimiters('', '<br />');
echo validation_errors();
exit();
}
else
{
if($_FILES['imagen']['error'] != 4)
{
$image $this->_manage_image($this->input->post('name'));
}
else
{
exit('No empty field!');
}
# save in your bd o success message...
}
}
function _manage_image($name)
{
# config
$config['upload_path'] = './images/products/';
$config['allowed_types'] = 'gif|jpg|png';
// ...
$config['file_name'] = $name;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image'))
{
# errors...
echo $this->upload->display_errors();
exit();
}
else
{
# upload
return $img_data['file_name'];
}
}

Check if specific input file is empty

In my form I have 3 input fields for file upload:
<input type=file name="cover_image">
<input type=file name="image1">
<input type=file name="image2">
How can I check if cover_image is empty - no file is put for upload?
You can check by using the size field on the $_FILES array like so:
if ($_FILES['cover_image']['error'] == 4 || ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0))
{
// cover_image is empty (and not an error), or no file was uploaded
}
(I also check error here because it may be 0 if something went wrong (ie. a file was selected, but there's no data received). I wouldn't use name for this check since that can be overridden). error with a value of 4 is UPLOAD_ERR_NO_FILE, so we can check for that too.
Method 1
if($_FILES['cover_image']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
Method 2
if($_FILES['cover_image']['size'] == 0) {
// No file was selected for upload, your (re)action goes here
}
You can check if there is a value, and if the image is valid by doing the following:
if(empty($_FILES['cover_image']['tmp_name']) || !is_uploaded_file($_FILES['cover_image']['tmp_name']))
{
// Handle no image here...
}
if (empty($_FILES['cover_image']['name']))
simple :
if($_FILES['cover_image']['error'] > 0)
// cover_image is empty
check after the form is posted the following
$_FILES["cover_image"]["size"]==0
if (!$_FILES['image']['size'][0] == 0){ //}
if( ($_POST) && (!empty($_POST['cover_image'])) ) //verifies if post exists and cover_image is not empty
{
//execute whatever code you want
}
if(!empty($_FILES)) { // code if not uploaded } else { // code if uploaded }
$_FILES is an associative POST method array, if You want to check anything about $_FILES You must take into account the index... I tried a lot of suggested options, and the only method that worked for me, was when I included an index in my verification method.
$_FILES['Your_File']['name'][0];
So bye doing this:
if(empty($_FILES['Your_File']['name'][0])){
print('this thing is empty');
}else{
print('Something, something, something');
}
There's nothing like good old experimentation and lots of reading.
if($_FILES['img_name']['name']!=""){
echo "File Present";
}else{
echo "Empty file";
}
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
{
// Code comes here
}
This thing works for me........
<input type="file" class="custom-file-input" id="imagefile" name="imagefile[]" multiple lang="en">
<input type="hidden" name="hidden_imagefile[]" value="<?=$row[2]; ?>" class="form-control border-input" >
if($_FILES['imagefile']['name'] == '')
{
$img = $_POST['hidden_imagefile'];
}
else{
$img = '';
$uploadFolder = 'uploads/gallery/';
foreach ($_FILES['imagefile']['tmp_name'] as $key => $image) {
$imageTmpName = time() .$_FILES['imagefile']['tmp_name'][$key];
$imageName = time() .$_FILES['imagefile']['name'][$key];
$img .= $imageName.',';
$result = move_uploaded_file($imageTmpName, $uploadFolder.$img);
}
}
if ($_FILES['cover_image']['error'] == 4){
// the user did not choose any file
}else{
// the user chose a file to be uploaded
}
This will work
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
// checking if file is selected and not an error
{
// file is not selected and it is not an error
}
UPDATED:
Use this method:
First check if 'cover_image' key exists in $_FILES then check other file errors
if (in_array('cover_image', array_keys($_FILES) && $_FILES['cover_image']['error'] == 0) {
// TODO: write your code
} else {
// return error
}

Categories