At the moment i'm preventing a resubmit with a redirect header location. But I imagine that the page loads slower because it's a waste of time to go to one place just to be redirected to another. It adds one extra step to the process.
What other options do I have with PHP?
Is there a way maybe to send form data to another file/page on submit without getting "redirected" to that page as well? And is it possible to do that without the need for redirect, because you where never sent there from the beginning. Just passing on the "form data" to the other page.
Open to other solutions as well, as long it's PHP.
Take care
Use include to include the PHP in your other page it will process the form without a redirect.
include 'YourFile.php';
here is a structural example of this.
<?php
include 'functions/db.php';// your db connection to process the form
$error['last'] = '';
$error['first'] = '';
$error['user'] = '';
if(isset($_POST['addUser'])){ // Check if form is submitted
$LastImp = $_POST['LastImp'];
$FirstImp = $_POST['FirstImp'];
$UserImp = $_POST['UserImp'];
if($LastImp == '' || $FirstImp == '' || $UserImp == ''){// Check if inputs are empty.
if($streetImp == ''){$error['street'] = 'Must enter a Street';}
if($LastImp == ''){$error['last'] = 'Must enter a Last Name';}
if($FirstImp == ''){$error['first'] = 'Must enter a First Name';}
if($UserImp == ''){$error['user'] = 'Must enter a Username';}
$error['alert'] = "All Fields are Required.";
include 'views/employee_front.php';
exit();
} else {
//Process the Form.
}}
include 'YourFile.php';// the php reads this first because all the other code is conditional upon submit.
This is YourFile Page
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Untitled 1</title>
<body>
<form method="post">
<div class="rowContainer">
<label class="User">Username</label>
<input class="Userimp" name="UserImp" type="text"></div>
<div class="error"><?php echo $error['user']; ?></div>
<div class="rowContainer">
<label class="First">First Name</label>
<input class="Firstimp" name="FirstImp" type="text"></div>
<div class="error"><?php echo $error['first']; ?></div>
<div class="rowContainer">
<label class="Last">Last Name</label>
<input class="Lastimp" name="LastImp" type="text"></div>
<div class="error"><?php echo $error['last']; ?></div>
<button class="addSubmitA" type="submit" name="addUser">Add User</button>
</form>
give the php file in action attribute of form tag <form method="POST" action="submit-data.php"> and in the submit-data.php,after successful data submission give header('Location:form.php') . It works fine for me without resubmission of data on browser reload. It is one way to prevent resubmission of data on page reload. Second way is use Ajax Jquery method to submit data.
I am new to PHP and am trying to do Server Side Form Validation. There are two PHP files Login.php and Form.php. Registration is done in Login.php and Validation in Form.php. The idea is that Form.php will process the form data sent by Login.php
My problem: even if form fields are empty, the variables are still being inserted into the database.
I don't want to insert if its empty. Rather, it has to route back to Login.php with error messages stored as a session variable.
I have checked the Form fields using !isset() and empty in Form.php using an if..else clause. In the if..else clause you can find out if the form fields are empty, and if so, they must go the session variable clause (inside the if condition). Instead, it is going to the else condition and inserting the empty values in variables ('$username','$password','$phone','$mailid','$city') in to the database.
I have read previous questions for similar problem here and even checked Youtube for Server Side Validation. What did I do wrong? Is there a problem with the use of session variables. Kindly assist
Login.php:
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<?php
session_start();
$passworderr='';
if(isset($_SESSION["passworderr"])) {
$passworderr=$_SESSION["passworderr"];
}
?>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Form.php:
<?php
session_start();
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if(!isset($_POST["username"])) {
$_SESSION["usernameerr"]="UserName is required";
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if(!isset($_POST["password"])) {
$_SESSION["passworderr"]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if(!isset($_POST["phone"])) {
$_SESSION["phoneerr"]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if(!isset($_POST["mailid"])) {
$_SESSION["mailiderr"]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if(!isset($_POST["city"])) {
$_SESSION["cityerr"]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
There are a bunch of ways to do this. A blank form field is present on the server side with an empty value. So in addition to checking if the variable is set, in your case you want to check if the value is non-empty.
One way to do that is to use the strlen function.
So an example for you is:
if(!isset($_POST["username"]) || strlen($_POST["username"]) == 0) {
NOTE: Do not use the empty function since the string "0" is considered 'empty'. Read the manual for other such cases.
You may want to consider using a helper function to do the determination. Basically something like this:
function DoesPostFormFieldHaveValue($formFieldName) {
return(
isset($_POST[$formFieldName])
&& strlen($_POST[$formFieldName]) > 0
);
}
First of all, session_start should always be the first line of the php page you need to use sessions on.
Also, I'm not sure why you are using so many session variables for storing errors. Instead of this, use a single session variable, declare it as array and store all the errors in it.
Here's your updated form :-
<?php
session_start();
if((isset($_SESSION['errors']))) //check if we have errors set by the form.php page
{
echo "Please fix the following errors";
foreach($_SESSION['errors'] as $error) //loop through the array
{
echo $error;
}
}
?>
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Backend processing file :-
<?php
session_start();
$_SESSION['errors'] = array(); //declare an array
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if((!isset($_POST["username"])) || (empty($_POST['username']))) {
$_SESSION["errors"][]="UserName is required"; //push error message to array if $_POST['username'] is empty or is not set
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if((!isset($_POST["password"])) || (empty($_POST['password']))) {
$_SESSION["errors"][]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if((!isset($_POST["phone"])) || (empty($_POST['phone']))) {
$_SESSION["errors"][]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if((!isset($_POST["mailid"])) || (empty($_POST['mailid']))) {
$_SESSION["errors"][]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if((!isset($_POST["city"])) || (empty($_POST['city']))) {
$_SESSION["errors"][]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(count($_SESSION['errors']) < 1) //check if the the $_SESSION['errors'] count is less than 1 (0), this means there are no errors.
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
The thing about isset is that it checks if the variable exists, and therefore allows variables that contain an empty string, like you have. When the current form is submitted without any user input, it is submitting a whole bunch of variables containing empty strings.
Now the solution is to change all your isset() to empty() and that should solve your problem!
[Note] There is no need to use both isset() and empty() like this:
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
because empty() is doing everything that isset() does.
check like this:
if(!isset($_POST["username"]) && $_POST["username"]!="")
Your PHP code is checking for isset only, I don't see any empty check. isset will be always true in your case to either of the forms, as the form fields are submitting - just the values are blank.
To prevent empty insertions, add a !empty check to your conditions. Your conditional statements should look like this -
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
first of all a little advice. If you want to start a new project, I would advice you learn how to use PDO connection to MySQL Databases, and not MySQLi. As PDO is much better method, and secured (especially when using prepared statements).
Anyway, as I can see you are storing the errors in a multiple $_SESISON variables, but after you are finishing the validation checks, you are not doing a correct if statement.
Instead of doing that:
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
Do something like this:
if(!isset($_SESSION['usernameerr']) && !isset($_SESSION['passworderr']) && !isset($_SESSION['phoneerr'] && !isset($_SESSION['mailiderr'] && !isset($_SESSION['cityerr'])))
Should work.
Another think I'm advising is to unset the sessions of the errors, in your case I would do that in the end of the Login.php page. Just in case, so there won't be any problems if you fix the form inputs and submit it again.
Another thing, based on the unset idea. If you will do this, it would be much more cleaner way to change the setting of the error sessions instead of:
$_SESSION['cityerr']
to:
$_SESSION['errors']['cityerr']
So afterwards, you can clean the specific form error session in one command, like that:
unset($_SESSION['errors']);
Hope it helped ;)
if(isset($_POST['field_name']))
{
$field_name=$_POST['field_name']
}else
{
unset($_POST['field_name'])
}
Hi all this is an easy question but right now i can't think about ..
I've a form where people can insert a personal code like "Abcdef301"
On submit i want to redirect them to url:
http://domain.tld/yoururls/Abcdef301
I've tried with some Post and Get (like the emails form but i've failed)
Any help?
<?php
if(isset($_POST['VAI'])) {
if(isset($_POST['text']) && $_POST['text'] != "") {
header("Location: http://domain.tld/yoururls/".$_POST['text']);
} else {
// handle error of no code in form field here if you want to
}
}
?>
<html>
<head>
<title>page title</title>
</head>
<div id="feedback-form">
<div class="success-block"></div>
<form action="" method="post">
<input name="text" placeholder="Inserire Codice Evento" required type="text">
<input type="submit" value="VAI" class="btn">
</form>
</div>
</html>
Should be what you're looking for.
I'm working with a .html and a .php. In the default.html the user must enter some info and when the button is clicked the html does a post to the default2.php.
In default2.php the data is checked and if it's correct it redirects the user to another page. The problem I'm having is when the data entered is wrong.
I'm having two issues here:
When the data is wrong I'm redirecting the user to the default.html, because if I don't do that, it will stay in default2.php and default2.php has nothing important for the user to see. I don't know if this is the best way to do this.
When the data entered is wrong, I want an echo message to the user in default.html. But I don't know how to trigger this from default2.php.
How can I solve these two issues?
Thanks...
default.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP4</title>
<style type="text/css">
body {
background-color: #CCC;
}
</style>
</head>
<body>
<p> </p>
<form id="form1" name="form1" method="post" action="default2.php">
<p>
<label for="textfield1">User Name</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="textfield2">Password</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="submit" name="button1" id="button1" value="Submit" />
<br />
<br />
<label id="label1">
</label></p>
<p> </p>
</form>
<p> </p>
</body>
</html>
default2.php:
<?php
require 'connection.php';
if (isset($_POST['button1'])) {
$username_v = $_POST['username'];
$password_v = $_POST['password'];
// Then you can prepare a statement and execute it.
$stmt = $dbh->prepare("CALL login(?, ?)");
$stmt->bindParam(1, $username_v, PDO::PARAM_STR);
$stmt->bindParam(2, $password_v, PDO::PARAM_STR);
// call the stored procedure
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
header("Location: main.php");
}
else
{
header("Location: default.html");
}
}
?>
Just add some parameter to
header("Location: default.html?test=failed");
And in html use Javascript to display something sensible when variable test is set to failed. You can find a tutorial how to get value of url parameter with javascript here.
Hope that helps.
Other than that you can use PHP in your default.html and perhaps even AJAX request to do validation without leaving the page and highlighting validation errors.
Personally, I don't like to expose states like "error" and "invalid" to the user using a query string. In this situation, I would merge the two files in one single PHP file, with the PHP code at the top and the HTML code at the bottom.
The if statement in the PHP code would be:
if ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
header("Location: main.php");
exit;
}
else
{
$error = true;
}
And down in the HTML where you want to display the message:
<?php
if( isset( $error ) && $error )
echo 'You have entered the wrong data!';
?>
Ofcourse, in the form element, you would have to remove action="default2.php".
If you prefer separating the logic and the markup, you could change default.html to for example template.php and include it at the end of your controller php file.
I just don't like the idea of an extra page without any content that only acts as a redirector.
If you made default.html a PHP file, you could pass a variable via the URL, this would then allow you check if this variable has been passed using $_GET[]and show the user a message.
So for example, if you forwarded the user to
default.php?error=1
On the default page, you could have a segment of code such as
if (isset($_GET['error'])) {
echo "Show user a message here";
}
I am a beginner to PHP and i want to make a static method that if its argument is empty it'll show the message. If not, it'll set the given message to a static variable for later use. But when i call the method to set the message, and then call it in another page to show the message. Nothing appear.
Here's my portion of code for this "session.php" :
class Session {
public static $message;
public static function notify($message = ""){
if(!empty($message)){
self::$message = $message;
} else {
return self::$message;
}
}
}
$session = new Session();
"add_user.php" :
<?php
require_once '../helper/session.php';
?>
<?php
if (isset($_POST["submit"])) {
$user->username = $_POST["username"];
$user->password = $_POST["password"];
$user->first_name = $_POST["first_name"];
$user->last_name = $_POST["last_name"];
if($result = $user->add_user()){
Session::notify("New user added");
redirect_to("../view/login.php");
} else { Session::notify("Cannot add new user"); }
}
?>
"login.php" :
<?php
require_once "../control/add_user.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" href="../stylesheet/login.css" />
<title>Welcome to Harmony</title>
</head>
<body>
<header>
<h2>Harmony</h2>
</header>
<section>
<div id="formStyle">
<h3>Login or Signup:</h3>
<form action="login.php" method="post">
<p><label for="username">Username: </label>
<input type="text" name="username" value="" placeholder="Username"/></p>
<p><label for="password">Password: </label>
<input type="text" name="password" value="" placeholder="Password"/></p>
<input type="submit" name="submit" value="Submit" />
<input type="button" name="sign_up" value="Sign up" onClick="parent.location='add_user.php'">
</form>
<?php echo Session::notify(); ?>
</div>
</section>
</body>
</html>
You aren't really writing to the session, now are you?
You should create two more methods for getting and setting the variables in the actual session. After the redirect, your message dissapears, because it is only saved on script execution.
function set_notification($message) {
$_SESSION['notification'] = $message; }
function get_notification() {
if(!empty($_SESSION['notification'])) {
return $_SESSION['notification']; }
Something like that :)
Of course, for sessions to work, you should do a session_start() call in the beginning of the script. read more about them here
HTTP by nature is shared-nothing, so anything you do in one request is not available to any other request. You will need to use a shared datastore to persist these messages.
A database, memcache, even a text file on the server (assuming you are operating on a single server and are not load balancing multiple) are all choices.
You can use cookies on the client side to persist a small amount of data. But keep in mind its not a secure solution (without using encryption) and you are limited in the amount of data you can store in cookies.
HTTP - and PHP - is stateless. You need to use session variables to track data across sessions
http://www.php.net/manual/en/book.session.php