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.
Related
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.
test.php
<?php
//CLICK SUBMIT BUTTON
if(isset($_POST['submit']))
{
$membername = $_POST['membername'];
$errors = '';
if(empty($membername))
{
$errors = "Please enter member name!<br />";
}
if($errors)
{
//MEMBER NAME TEXTFIELD EMPTY
//SHOW ERROR MESSAGE AND DISPLAY FORM AGAIN
echo '<span style="color:red;font-weight: bold;">'.$errors.'</span>';
displayForm();
}
else
{
//GO TO OUTPUT.PHP PAGE
header("Location:output.php");
exit();
}
}
else
{
displayForm();
}
?>
<?php
//DISPLAY FORM
function displayForm()
{
?>
<html>
<head></head>
<body>
<form action="test.php" method="post">
Member Name
<input type="text" name="membername" value="<?php if(isset($_POST['membername'])) echo $_POST['membername'];
else echo ''; ?>" /><br />
<input type="submit" name="submit" value="add" />
[HERE]
</form>
</body>
</html>
<?php
}
?>
In [HERE] section, I write the hidden input field:
<input type="hidden" name="mname" value="<?php echo $_POST['membername']; " />
After that, I go to output.php get the hidden field value:
<?php
echo $_POST['mname'];
?>
When I run the code, I get this error:
Undefined index: mname
What happened to my program?
header() function cannot applied to $_POST method?
Any solutions to solve it?
There Could be two solutions to get the value on redirected page :
1. By Session :
You can put the value in session and get on the redirected page.
$_SESSION['mname'] = $_POST['mname'];
2. Using GET :
You can send values in header.
header("Location:output.php?val=$_POST['mname']");
I have a simple php calculator which code is:
<html>
<head>
<title>PHP calculator</title>
</head>
<body bgcolor="orange">
<h1 align="center">This is PHP Calculator</h1>
<center>
<form method="post" action="phptest.php">
Type Value 1:<br><input type="text" name="value1"><br>
Type value 2:<br><input type="text" name="value2"><br>
Operator:<br><input type="text" name="sign"><br>
Result:<br><input type"text" name="result">
<div align="center">
<input type="submit" name="submit" value="Submit">
</div>
</form>
</center>
<?php
if(isset($_POST['submit'])){
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
if($value1=='') {
echo "<script>alert('Please Enter Value 1')</script>";
exit();
}
if($value2=='') {
echo "<script>alert('Please Enter Value 2')</script>";
exit();
}
if($sign=='+') {
echo "Your answer is: " , $value1+$value2;
exit();
}
if($sign=='-') {
echo "Your answer is: " , $value1-$value2;
exit();
}
if($sign=='*') {
echo "Your answer is: " , $value1*$value2;
exit();
}
if($sign=='/') {
echo "Your answer is: " , $value1/$value2;
exit();
}
}
?>
All I want to do is that answer should be displayed in the result input field instead of echoing them separately. Please help? I Know it's simple but I am new in PHP.
One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input> tag.
Try this -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
inside the Form, You can use this code. Replace your variable name (i use $variable)
<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">
Try this
<input class="qtytext-box" type="number" value= <?php echo $colll2; ?> >
I have following login form (login.php) in which I am asking for username and password.
<form action="processlogin.php" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
Following is the code snippet from my processlogin.php file
if(!$_POST["username"] || !$_POST["password"])
{
$msg = "You left one or more of the required fields.";
echo $msg;
//header("Location:http://localhost/login.php");
}
This code checks whether all the mandatory fields are filled on not. If not, it shows the error message.
Till now everything is fine.
My problem is that, error message is shown in plain white page. I want to show it above the login form in login.php file. How should I change my code to get
my functionality.
I would prefer Jquery Validation or Ajax based Authentication. But still you can do it this way:
Put your Error Message in Session like this :
$_SESSION['Error'] = "You left one or more of the required fields.";
Than simple show it like this:
if( isset($_SESSION['Error']) )
{
echo $_SESSION['Error'];
unset($_SESSION['Error']);
}
In this case you can assign multiple messages in different Operations.
header("Location:http://localhost/login.php?x=1")
In the login.php
if(isset($_GET('x'))){
//your html for error message
}
Hope it helps you,
In processlogin.php,
if(!$_POST["username"] || !$_POST["password"])
{
$msg = "You left one or more of the required fields.";
$msgEncoded = base64_encode($msg);
header("location:login.php?msg=".$msgEncoded);
}
in login.php file,
$msg = base64_decode($_GET['msg']);
if(isset($_GET['msg'])){
if($msg!=""){
echo $msg;
}
}
You can display the message in table or span above the form.
<span>
<?php if(isset($_REQUEST[$msg]))
echo $msg;
?>
</span>
<form>
</form>
And also don't echo $msg in the form's action page.
Try this:
html:
<form action="processlogin.php" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
<span>
<?php if(isset($_GET['msg']))
echo $_GET['msg'];
?>
</span>
</form>
php:
if(!$_POST["username"] || !$_POST["password"])
{
$msg = "You left one or more of the required fields.";
header("Location:http://localhost/login.php?msg=$msg");
}
Use only one page (your login.php) to display the form and also to validate its data if sent. So you don't need any $_SESSION variables and you have all in one and the same file which belongs together.
<?php
$msg = null;
if(isset($_GET['send'])) {
if(!$_POST["username"] || !$_POST["password"]){
$msg = "You left one or more of the required fields.";
//header("Location:http://localhost/login.php");
}
}
?>
<?php echo ($msg !== null)?'<p>ERROR: ' . $msg . '</p>':null; ?>
<form action="?send" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
use these functions:
<?php
session_start();
define(FLASH_PREFIX,'Flash_')
function set_flash($key,$val){
$_SESSION[FLASH_PREFIX.$key]=$val;
}
function is_flash($key){
return array_key_exits(FLASH_PREFIX.$key,$_SESSION);
}
function get_flash($key){
return $_SESSION[FLASH_PREFIX.$key];
}
function pop_flash($key){
$ret=$_SESSION[FLASH_PREFIX.$key];
unset($_SESSION[FLASH_PREFIX.$key]);
return $ret;
}
?>
And when you want to send a message to another page use
set_flash('err_msg','one field is empty');
header('location: another.php');
exit();
another.php
<html>
.
.
.
<body>
<?php if(is_flash('err_msg')){?>
<span class="err_msg"><?php echo pop_flash('err_msg'); ?></span>
<?php } ?>
.
.
.
</body></html>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
if(!$_POST["username"] || !$_POST["password"])
{
$msg = "You left one or more of the required fields.";
echo $msg;
//header("Location:http://localhost/login.php");
}
}
?>
<form action="<?php echo $PHP_SELF;?>" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
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.