Basic form validation mechanism PHP - php

I'm trying to set up simple example for form validation, whether field is empty or not. If field is not empty action redirect me to page ok.php and if not back to formvalidation.php. and change css of the field. I have problem with returning error array back to formvalidation.php and testing it to change css for input field. What am I doing wrong?
formvalidation.php
<?php require("includes/functions.php"); ?>
<?php
global $errors;
?>
<form action="posting.php" method="p">
<ul>
<li id="field">
<label for="field">Contact person </label>
<input
<?php
if (empty($errors)) {
echo "style=\"background-color: #ECECEC;\"";
} else {
if (in_array("field", $errors)) {
echo "style=\"background-color: red;\"";}
} else {
echo "style=\"background-color: #ECECEC;\"";
}
}
?>
type="text" name="field"/>
</li>
<li>
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
action.php
<?php require("includes/functions.php"); ?>
<?php
$errors = form_validation ();
if (!empty($errors)) {
redirect_to("formvalidation.php");
} else {
redirect_to("ok.php");
}
?>
function
<?php
function form_validation () {
$errors = array ();
$required_fields = array('field');
foreach($required_fields as $fieldname) {
if (!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
$errors[] = $fieldname;
}
}
return $errors;
}

After redirect $error variable is empty use $_SESSION
<?php
$_SESSION['error']=form_validation ();
if (!empty($_SESSION['error'])) {
redirect_to("formvalidation.php");
} else {redirect_to("ok.php");}
?>
And in formvalidation.php
$error=$_SESSION['error'];
unset($_SESSION['error']);
don't forget to ensure that session_start() is on the top of your code

Just take a look at this tutorial: http://www.html-form-guide.com/php-form/php-form-validation.html. It's implemented more object-oriented.

Related

Display form validation error message on same page using only PHP?

I'm very new to PHP and I've cobbled this together from some other answers on here. Can anyone show me how to get the $errMsg to display? At present, a blank or incorrect name leads to a blank page. Is this because the form isn't being displayed again? If so, how should I go about 'reloading' the form with the error message?
<?php
$name = "Fred";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["name"])) {
if ($_POST["name"] == $name) {
include("welcomeFred.php");
}
else {
$errMsg = "Incorrect name";
}
}
else {
$errMsg = "Name required";
}
}
else { ?>
<html>
...
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" required>
<span><?php echo $errMsg;?></span>
<input type="submit" value="Submit">
</form>
...
</html>
<?php } ?>
You shouldn't put the rendering of the form in the else of your if structure. This is the reason your form isn't loaded when you submit the form.
Remove the else { ?> and <?php } ?> at the end of your file and it should work fine.

if ($_POST) always returns false

I'm having some trouble with a Form. It contains an input type File for uploading an image, and a select tag to choose where to put this image.
Code goes like this:
<?php
require_once("functions.php");
if(isset($_COOKIE['user']))
{
$username= checkcookie($_COOKIE['user']);
}
if (isset($_SESSION['user'])) {
if ($_POST) {
$errors = array();
$errors = SomeValidation();
if (empty($errors )) {
UpdateImages();
exit;
}else {
Header ("location: somefile.php?error=There was an error");
exit;
}
}else{
var_dump("error");
} ?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<?php if(isset($_GET['error'])) {?>
<div class="alert alert-danger" role="alert">
<ul>
<li><?php echo $_GET['error'] ?></li>
</ul>
</div>
<?php } ?>
<div class="cbp-mc-column">
<label>Choose new Image</label>
<select id="code" name="code">
<option value="1" >First</option>
<option value="2" >Second</option>
<option value="3" >Third</option>
</select>
<br/>
<input type="file" name="newimage" value="" />
<br>
<input type="submit" name="update" value="Update">
<br>
</div>
</form>
<!-- Bootstrap Core JavaScript -->
<script src="../js/bootstrap.min.js"></script>
</body>
</html>
<?php }else
{
header('location: panel.php');
}
?>
I'm always getting False for if($_POST), and also when I submit the form.
Any idea why?
EDIT: I forgot to mention, I'm sending the select value via post, so I can choose which file upload, and It is always empty.
to upload image or any other file you need to check the $_FILES array not post,
this question could be helpfull
How do you loop through $_FILES array?
It is better to check inputs instead of request method.. so use
if (!empty($_POST["update"])) {
....
}
First, you need to check if the submit button was clicked :isset($_POST['update'])
Next, check if a file has been selected: isset($_FILES['newimage']['tmp_name'])
if (isset($_POST['update'])) {
if (isset($_FILES['newimage']['tmp_name'])) {
$errors = array();
$errors = SomeValidation();
if (empty($errors )) {
UpdateImages();
exit;
} else {
Header ("location: somefile.php?error=There was an error");
exit;
}
} else {
echo "No file selected.";
}
} else {
echo "Not a POST request.";
}

How can i use custom function to validate post data in php

I want to validate my form post using function and then insert it into database.
I have been able to do that without putting it into function but when i put it into a function it inserts without validating the input fields.
Thanks ;)
Here is my code:
<?php
function validate_post(){
global $link;
if (isset($_POST['submit'])) {
$error = array();
if (!isset($_POST['cat_title']) || empty($_POST['cat_title'])) {
$error[] = "field cannot be empty";
} else {
//check if a name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/", $_POST['cat_title'])) {
$cat_err = "Only letters and whitespace allowed";
}
}
//if no errors found
if (empty($error) && empty($cat_err)) {
$cat_title = htmlentities($_POST['cat_title']);
$sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
$insert = mysqli_query($link, $sql);
confirm_query($insert);
if (mysqli_affected_rows($link) == 1) {
$post_info = "Category has been added";
redirect("categories.php");
} else {
$post_info = "Adding category failed";
}
} else {
$post_info = "Field cannot be empty";
}
}
}
?>
<?php validate_post(); ?><!-- call validate_post function-->
<!-- ADD CATEGORY FORM -->
<form action="" method="post">
<?php
if(isset($post_info))echo $post_info."<br>";
if(isset($cat_err))echo $cat_err."\n" ?>
<div class="form-group">
<label for="cat_tile">Categories</label>
<input type="text" class="form-control" name="cat_title" id="cat_tile"/>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="+ Add Category" name="submit" >
</div>
</form>
You can pass your post data by reference to a function like this:
function checkFormValue(&$inputData) {
if (isset($inputData) && !empty($inputData)) {
return $inputData;
}
return "";
}
Call this function on $_POST data to validate it:
$catTitle = checkFormValue($_POST["cat_title"]);
var_dump($catTitle);
If it fails to validate than it will return empty string. Using this function you can check isset and for !empty many of your form fields.
below code will help you ..
<?php
function validate_post(){
global $link;
if (isset($_POST['submit'])) {
$cat_err = "";
if (!isset($_POST['cat_title']) || empty($_POST['cat_title']) || $_POST['cat_title']=="") {
$cat_err = "field cannot be empty";
} else {
//check if a name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/", $_POST['cat_title'])) {
$cat_err = "Only letters and whitespace allowed";
}
}
//if no errors found
if ($cat_err=="") {
$cat_title = htmlentities($_POST['cat_title']);
$sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
$insert = mysqli_query($link, $sql);
confirm_query($insert);
if (mysqli_affected_rows($link) == 1) {
$cat_err = "Category has been added";
redirect("categories.php");
} else {
$cat_err = "Adding category failed";
}
} else {
$cat_err = "Field cannot be empty";
}
return $cat_err;
}
}
?>
<?php $data=validate_post();echo $data;?><!-- call validate_post function-->
<!-- ADD CATEGORY FORM -->
<form action="" method="post">
<div class="form-group">
<label for="cat_tile">Categories</label>
<input type="text" class="form-control" name="cat_title" id="cat_tile"/>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="+ Add Category" name="submit" >
</div>
</form>
Your function doesn't return any information. You need to tell it to return the errors, and then do something with them. You need to restructure the way messages are organized in your function, but the gist is this:
add return $error; to the end of your validate function.
Then in your page body:
<?php $errors = validate_post(); ?><!-- call validate_post function-->
<!-- ADD CATEGORY FORM -->
<form action="" method="post">
<?php
foreach($errors as $error)
{
echo $error;
}
?>
<div class="form-group">
So, change your validate function to save all messages into a single array, return the array, then process the items.
Variables declared inside a function only "exist" within the scope of that function. $post_info inside your function has no relationship to $post_info outside the function.
Try to pass in the $_POST array:
if (isset($_POST['submit'])){
validate_post($_POST)
}
function validate_post($post_array) {
// your code here
}
Matt first suggested this, but here is how you would do that.
Using your code this is the rundown to what you need to do for the function.
<?php
function validate_post($link, $data=[]) {
$error = array();
if (!isset($data['cat_title']) || empty($data['cat_title'])) {
$error[] = "field cannot be empty";
} else {
//check if a name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/", $data['cat_title'])) {
$cat_err = "Only letters and whitespace allowed";
}
}
//if no errors found
if (empty($error) && empty($cat_err)) {
$cat_title = htmlentities($data['cat_title']);
$sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
$insert = mysqli_query($link, $sql);
confirm_query($insert); //This is another function you created???
if (mysqli_affected_rows($link) == 1) {
$post_info = "Category has been added";
redirect("categories.php");
} else {
$post_info = "Adding category failed";
}
} else {
$post_info = "Field cannot be empty";
}
}
if (isset($_POST['submit'])) {
include 'dbfile.php'; // Containing your db link variable if that is how you've done it
validate_post($link, $_POST); // Usually you need to pass your database link by reference also rather than by global.
}
?>
--html section--

PHP Passing arguments in a user defined function into $_POST()

I'm creating a function for PHP form validation. The idea is that if a user has not filled out a required field (for example, if a $_POST variable called "name" is empty), then the user will be warned.
This function doesn't seem to work, however:
function addError($x) {
if (!$_POST["$x"]) {
$error.="Please enter your $x";
}
}
echo $error;
I've isolated the problem down to the passing of the argument $x into $_POST, i.e. this line:
if (!$_POST["$x"]) {
Specifically, $_POST["$x"]. Is this the right way/syntax to pass an argument?
Thank you!
Your code should be like -
$error = '';
function addError($x, $error) {
if (!$x) { // Check for the data
$error.="Please enter your $x"; // Concatenate the errors
}
return $error; // return the error
}
echo addError($_POST[$x], $error); // Pass the data to check & the error variable
Try this.....
<form method="post">
<input type="text" name="name" />
<input type="submit" value="submit" />
</form>
<?php
$x=$_POST["name"];
function addError($x)
{
if ($x==null)
{
$error="Please enter your name";
}
else
{
$error='';
}
return $error;
}
echo addError($x);
?>
Try this :-
$error = "";
function addError($x)
{
global $error;
if ("" == $_POST['"'.$x.'"'])
{
$error.="Please enter your".$x;
}
}
addError("name");
echo $error;
I referenced above two answers and write some code for this question. It works when I tested. You might get some idea for your coding.
Here is my tested code.
PHP section
<?php
function check_error($x){
$error = "";
if(isset($_POST[$x]) && $_POST[$x] == ""){
$error = "Please Enter Data";
}
return $error;
}
echo check_error('txt_name');
?>
HTML section
<!DOCTYPE html>
<html>
<head>
<title> Testing </title>
</head>
<body>
<h1> Testing </h1>
<hr/>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<input type="text" name="txt_name" value="" placeholder="Your name" />
<input type="Submit" name="btn_submit" value="Submit" />
</form>
</body>
</html>
Make $error a global variable.

Submitting form results that there is no error to another page

i want to know how to send value form my_name in index.php below to result.php.
below is the php code to check for errors after the input form.
and how to send form results that there is no error to result.php
here is index.php
<?php
if ($_POST["_submit_check"]) {
if ($form_errors = validate_form()) {
show_form($form_errors);
} else {
process_form();
}
} else {
show_form();
}
function process_form() {
//if doesnt makes error
//i want to send result "my_name" to result.php
header('Location: result.php');
}
function show_form($errors = '') {
if ($errors) {
print implode('</li><li><br>', $errors);
print '</li></ul>';
}
print<<<_HTML_
<form method="POST" action="$_SERVER[PHP_SELF]">
Your name: <input type="text" name="my_name">$errors[0];
<br/>
<input type="submit" value="Submit">
<input type="hidden" name="_submit_check" value="1">
</form>
_HTML_;
}
function validate_form() {
$errors = array();
if (strlen($_POST['my_name']) < 3) {
$errors[] = "Your name must be at least 3 letters long.";
}
return $errors;
}
?>
here is result.php
<?php
//prints result form from index.php
?>
you can do it with HTTP GET variables
header('Location: result.php?name='.$_POST['my_name']);
in result.php
you can see the value
echo $_GET['name'];
PHP session variables hold information among pages.
Please try this.
At index.php
<?php
session_start();
// set post date into session variable
$_SESSION['my_name'] = $_POST['my_name'];
$_SESSION['my_number'] = $_POST['my_number'];
?>
And at result.php
<?php
session_start();
// get date from session variable
$my_name = $_SESSION['my_name'];
$my_number= $_SESSION['my_number'];
echo $my_name;
echo $my_number;
?>

Categories