loading blank page despite form action location upon error - php

I am creating a simple form that a user submits and email. I am trying to pose an error if the form is blank or it's not a valid email and if successful, then reload the page with a success message.
When I submit blank it reloads the page without an error, and if I enter anything in ( valid or invalid email ) it reloads the page white, despite the form action being correct. I've been stuck on this and need help. Thanks.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/includes/system/init.php');
if(isset($_POST['submit'])) {
$email = $_POST['email'];
if(empty($_POST['email']) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = "Please enter a valid email";
}else{
$success = true;
mysql_query("INSERT INTO survey
(email) VALUES('".$_POST['email']."' ) ")
or die(mysql_error());
}
}
?>
<div class="email-survey">
<?php if(isset($success)) { ?>
<div class="success">Thank You!</div>
<?php } ?>
<?php if(isset($error)) { ?>
<div class="error">
<?php echo $error; ?>
</div>
<?php } ?>
<form name="settings" action="/survey-confirm.php" method="post">
<input type="text" name="email" /> <br />
<input type="submit" name="submit" value="submit" />
</form>
</div>

<?php
function control($type, $text)
{
echo '<div class="'.$type.'">'.$text.'</div>';
}
require_once($_SERVER['DOCUMENT_ROOT'] . '/includes/system/init.php');
if(isset($_POST['submit'])) {
$email = $_POST['email'];
if(empty($_POST['email']) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
control('error', 'Type valid mail!');
}else{
control('success', 'All done!');
mysql_query("INSERT INTO survey
(email) VALUES('".$_POST['email']."' ) ")
or die(mysql_error());
}
}
else
{echo 'echo '<form name="settings" action="/survey-confirm.php" method="post">
<input type="text" name="email" /> <br />
<input type="submit" name="submit" value="submit" />
</form>
</div>';}
?>
This is small function named control, you can call this and put your custom div name and text to show user.
control('THIS IS DIV NAME','THIS IS MESSAGE FOR USER')

Related

Unable to call PHP function in HTML file, tried using the same code in different code its working fine but not here

When I press the Login button it refreshes the page and doesn't do anything. I tried entering wrong Server IP just to check the error, but I guess it's not responding to the login button and directly refreshing the page.
Unable to call a PHP function in the HTML file, tried using the same code in a different code and it's working fine there but not here:
<title> Database Login </title>
<body>
</head>
<body>
<span>
<div class="heading">
<h3><img src="http://zicom.com/img/ilayashop-1482233381.jpg" alt="Zicom Logo" >
<h1><b>MAaaS Login<b></h1><br>
</span>
</div>
<div class='admin'>
<form method='post' action=''>
<p class='main'> Enter your Details </p>
<p> Enter User Name <input type="text" name="name" id="userInput"></p>
<p> Enter password <input type="password" name="pass" id="userInput"> </p>
<br>
<input id="login" type="submit" name="submit" value="Login">
</form>
</div>
<?php
if($_POST){
$UN = $_POST['name'];
$PS = $_POST['pass'];
$scon=odbc_connect("Driver={SQL Server};Server=XXXXXXX; Database=Sampledata;","XX","XXXXX");
$query="SELECT [password] FROM [Simcarddata].[dbo].[MasterUser] Where username='$UN'";
$rs=odbc_exec($scon,$query);
if (!$rs)
{
$msg="SQL statement failed with error:\n";
$msg.=odbc_error($scon).": ".odbc_errormsg($scon)."\n";
} else {
$number_of_rows = odbc_num_rows($rs);
$msg="$number_of_rows records found.\n";
}
while(odbc_fetch_row($rs))
{
$field1 = odbc_result($rs,1);
// print ("$PS and $field1");
if ($PS == $field1){
print ("TRUE");
header("Location: /test.php");
}
else {
print ("Incorrect Username or password");
}
}
odbc_close($scon);
header("Refresh:2");
}
?>
</body>
</html>
I just tidied up the HTML tags a little and used a better method of checking for POST data - but I think the issue was the badly formed HTML was confusing the form
<html>
</head>
<title> Database Login </title>
</head>
<body>
<span>
<div class="heading">
<h3><img src="http://zicom.com/img/ilayashop-1482233381.jpg" alt="Zicom Logo" ></h3>
<h1><b>MAaaS Login<b></h1>
<br>
</div>
</span>
<div class='admin'>
<form method='post'>
<p class='main'> Enter your Details </p>
<p>Enter User Name <input type="text" name="name" id="userInput"></p>
<p>Enter password <input type="password" name="pass" id="userInput"></p>
<br>
<input id="login" type="submit" name="submit" value="Login">
</form>
</div>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['name'], $_POST['pass'] ) ){
$UN = $_POST['name'];
$PS = $_POST['pass'];
$scon=odbc_connect("Driver={SQL Server};Server=XXXXXXX;Database=Sampledata;","XX","XXXXX");
$query="SELECT [password] FROM [Simcarddata].[dbo].[MasterUser] Where username='$UN'";
$rs=odbc_exec( $scon, $query );
if (!$rs) {
$msg="SQL statement failed with error:\n";
$msg.=odbc_error($scon).": ".odbc_errormsg($scon)."\n";
} else {
$number_of_rows = odbc_num_rows($rs);
$msg="$number_of_rows records found.\n";
}
while( odbc_fetch_row( $rs ) ) {
$field1 = odbc_result($rs,1);
if ($PS == $field1){
print ("TRUE");
header("Location: /test.php");
} else {
print ("Incorrect Username or password");
}
}
odbc_close($scon);
header("Refresh:2");
}
?>
</body>
</html>
if ($_SERVER['REQUEST_METHOD'] === 'POST') use this please instead of if($_POST) or use if(isset($_POST))

php validation on submit when jump from one page to another

In this program when i am clicking submit button the page directly goes on other page 2222.php. The error message not pop up.. I just want hit error message when clicking on submit button...
php_validation.php
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$name = $email = $gender ="";
// On submitting form below function will execute.
if(isset($_POST['submit']))
{
if (empty($_POST["name"])) //---------------------------------------------- -------------------------
{
$nameError = "Name is required";
}
else
{
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only letters and white space allowed";
}
//-----------------------------------------------------------------------
}
if (empty($_POST["email"])) //---------------------------------------------- -------------------------
{
$emailError = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailError = "Invalid email format";
}
}
//-----------------------------------------------------------------------
if (empty($_POST["gender"]))
{
$genderError = "Gender is required";
}
else
{
$gender = test_input($_POST["gender"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" name="myForm" action="2222.php">
<p>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError;?></span>
</p>
<br><br>
<p>
Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError;?></span>
</p>
<br><br>
<p>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">*<?php echo $genderError;?></span><br><br />
</p>
<input class="submit" type="submit" name="submit" value="Submit" >
</form>
</body>
2222.php
<?php
$name = $_POST['fname'];
$email = $_POST['email'];
$radio = $_POST['gender'];
echo "<h2>Your Input:</h2>";
echo "user name is: ".$name;
echo "<br>";
echo "user email is: ".$email;
echo "<br>";
echo "user is ".$radio;
?>
So I've done a quick code for you :
Here is your "php_validation.php" :
<?php
//Init error var
$nameError = '';
$emailError = '';
$genderError = '';
//Did we have an error ?
if(isset($_GET['error'])){
//Split error return into an array
$errorList = explode('_', $_GET['error']);
//Verify every possible error
if(in_array('name',$errorList)){
$nameError = 'Please enter your name<br>';
}
if(in_array('email',$errorList)){
$emailError = 'Please enter your email<br>';
}
if(in_array('gender',$errorList)){
$genderError = 'Please enter your gender';
}
}
?>
I didnt changed the form
Then this is your "2222.php" :
<?php
$error ='';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//When we receive data
if(isset($_POST)){
//Verify all possible data and set error
if(!empty($_POST['fname'])){
$name = test_input($_POST['fname']);
}else{
$error .= 'name_';
}
if(!empty($_POST['email'])){
$email = test_input($_POST['email']);
}else{
$error .= 'email_';
}
if(!empty($_POST['gender'])){
$radio = test_input($_POST['gender']);
}else{
$error .= 'gender_';
}
//if we have an error then redirect to form with error
if(!empty($error)){
header("Location:php_validation.php?error=".$error);
}
}
?>
Didnt changed your output on this page either.
So as I said previously when you here is what happend when you click the submit button :
Submit Click
Form sent to 2222.php as $_POST and you're redirected to this page
There is no way that could be working if your form is posting on an other page than the one where the check is made.
Since your form's action is "2222.php", on click the submit button will automatically redirect you to 2222.php before doing anything.
If you want to check what you've received by your form, you can do it in your "2222.php", then redirect it with the error message to php_validation.php
You could do one of the following things:
Do all the checking in Javascript "onClick" function
Do Ajax call "onClick" to a handler page, get the validation message from that page.
Do the validation on "2222.php" page
action back to the same page (since you are doing some validation here) and redirect after validation on "2222.php" page
Now depends only on you which fits your program.
If you want to stay on the same page you could submit the form to an iframe, as the results of the processing script would be displayed in the iframe itself.
Example:
files:
file-with-form.php
form-submit-processing-file.php
Code examples:
file-with-form.php
<!DOCTYPE html>
<html>
<head>
<title>[Your page title]</title>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<!-- Form -->
<form action="[path-to-form-submit-process]" method="[GET|POST]"
target="form-processor">
<div>
<label>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError ?></span>
</label>
</div>
<div>
<label>Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError ?></span>
</label>
</div>
<div>
<label>Gender:
<p><input type="radio" name="gender" value="female"> Female</p>
<p><input type="radio" name="gender" value="male"> Male</p>
<p><span class="error">*<?php echo $genderError ?></span></p>
</label>
<input class="submit" type="submit" name="submit" value="Submit" >
</div>
</form>
<!-- The iframe to submit the form to -->
<iframe name="form-processor" id="form-processor"
src="[path-to-form-submit-process]"></iframe>
<!--
NOTE: The error message spans are left there just because you had them
in your code, those will not work here at this point, actually depending
on your php configuration will most probably throw errors/warnings,
because such variables were not defined at all...
-->
</body>
</html>
As:
[path-to-form-submit-process] - a placeholder to be replaced with the URL to the file/ Controller -> Action that would process the passed form data
[*] - placeholders that should be replaced with the values for your case
form-submit-processing-file.php
<?php
# Processing the form fields and displaying the messages
$post = $_POST;
# Preprocessing the passed data
// Here you would filter out data from the $_POST superglobal variable
# Validating the passed data
// Check if the data entries, e.g.
// Flag for error risen - does not let the process to be completed
$invalidFormData = false;
$messages = [];
function addErrorMessage($message, &$messages, &$errorFlag)
{
$errorFlag = true;
$errorMessageTemplate = '<p class="error-message">{message}</p>';
array_push($messages, str_replace('{message}', $message,
$errorMessageTemplate));
}
// Validating the email
$email = array_key_exists('email', $post)
? $post['email']
: null;
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
// Raising the flag for an error on validation
addErrorMessage("$email is not a valid email address", $messages, $invalidFormData);
}
// ........
// validation of rest of fields
// ........
$internalError = false;
# Some business logic after the validation, recording more messages etc.
try {
// ........
} catch (Exception $e) {
$internalError = true;
}
# Stop execution on internal error
if ($internalError === true)
{
?>
<h2>Sorry, there's an error on our side... we'll do all in our
powers to fix it right away!</h2>
<?php
exit;
}
# Displaying the results
if ($invalidFormData === true) {
// Building errors message
$messagesHeading = '<h2>There were problems submitting your data. :/</h2>';
} else {
$messagesHeading = '<h2>Your data was successfully submitted! Yay!</h2>';
}
// Placing the heading in front of other messages
array_unshift($messages, $messagesHeading);
// Displaying the messages:
echo implode('', $messages);
However I believe this should be done via an AJAX call insted.
Also there are a lot of bad practices in this case, so I would suggest checking out some design patterns and architectures as MVC for instance and consider using a framework like Symfony/Laravel/CodeIgniter... There are a lot of tools that will make your life easier :)

Simple Validator in PHP not working

I created a little form validator with PHP and having some problems with it.
MY VIEW FILE is here :
<form action="" method="post">
<?php if( isset($status) ) : ?>
<p class="notice"><?php echo $status; ?> </p>
<?php endif; ?>
<ul>
<li>
<label for="name">Your Name : </label>
<input type="text" name="name">
</li>
<li>
<label for="email">Your Email : </label>
<input type="text" name="email">
</li>
<li>
<input type="submit" value="Sign Up">
</li>
</ul>
</form>
and here's my little controller :
<?php
require 'index.tmpl.php';
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if (empty($name) || empty($email)) {
$status = "Please provide a name and a valid email address";
}
echo $name;
}
?>
Now what happens is that , when I open up the page and leave the form fields blank and submit it ,it just reloads ,does not echo anything.
You want to echo $status, not $name.
How about moving the require line to below the if?
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if (empty($name) || empty($email)) {
$status = "Please provide a name and a valid email address";
}
echo $name;
}
require 'index.tmpl.php';
?>
The <form action="" points to the location where the form will be submitted. If blank, it submits the form back to itself.
<form action="yourLittleController.php" method="POST">
Edited with more info:
in php, post is not POST. Example here: https://eval.in/89002
make sure you have
method="POST">
and not
method="POST">
you should mention your second file name in your view file's form's action attribute like action = "controller.php"

How to show error messages in HTML page in PHP?

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>

Error appears before submit in php form

I have the following code but unfortunately $error appears as soon as the page loads, before clicking on submit. What am I doing wrong?
(filename= form.php)
<?php
$error="";
if (isset($_POST['submit']) && $_POST['submit'] == "Submit") {
$name = $_POST['name'];
$email = $_POST['email'];
if($name=="" || $email==""){
$error .= "Error: all fields are required";
}
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email)) {
$error .= "<br/> Error: Invalid email address";
}
if (isset($error) && ($error!=="")) {
echo $error;
}
elseif (empty($error)){
// this works no need to write here... send form.
}
}
echo<<<_END
<html><head><body>
<form method='post' action='form.php'>
<p>Name</p> <input type="text" name="name" value='$name'>
<p>Email</p> <input type="text" name="email" value='$email'>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</form>
</body>
</html>
_END;
?>
if (isset($error) && (!$error=="")) {
echo $error;
}
if $error is set and $error equals nothing echo $error?
$error is being set when you intialize it to "" in the first line and it is equal to ""
Just noticed the ! in the second part of the if. Do what the person below me said.
Replace (!$error=="")) with ($error!=="")).

Categories