PHP form error logic - php

Normally when we submit form in php and show errors then the errors are posted in other page.
Now my question is.
If we want to show the errors on same page mean on the form page, then how to do it?
I used session for that and found it better then other process but when I want to show all session variable at once then it will not show, why?
My code is:
if(isset($_POST) && count($_POST)>0) {
$user =test_input($_POST['user']);
$pass = test_input($_POST['pass']);
$securepassword=hash('sha512', $pass);
if(empty($user)&&empty($pass))
{
echo 'fill every field';
}
else if(empty($user)||empty($pass))
{
echo 'fill both the field';
}
else
{
$sSQL = "SELECT * FROM signup WHERE Username ='".$user."' AND Password = '".$securepassword."'";
$result = mysql_query($sSQL) or die(mysql_error());
$row=mysql_num_rows($result);
if($row==1)
{
// Set username session variable
$_SESSION['user'] = $user;
// Jump to secured page
header('location:index.php');
}
else
{
header('location:signin.php');
}
}
}

You better use JavaScript for validating the form. Lets say this is your HTML code.
<form method="post" name="loginForm" action="abc.php">
<input type="text" name="user">
<input type="password" name="pass">
</form>
Now, let’s add validate this form before you POST to abc.php:
<form method="post" name="loginForm" action="abc.php" onsubmit="return validater()">
<input type="text" name="user">
<input type="password" name="pass">
</form>
And the JavaScript is:
function validater() {
var a= document.forms["loginForm"]["user"].value;
if (a==null || a=="") {
alert("Fill out the username");
return false;
}
var b= document.forms["loginForm"]["pass"].value;
if (b==null || b=="") {
alert("Enter your password");
return false;
}
}

Logic is simple you can put the php code and html code on the same page. In the following order.
Put your php validation code.
Put your error code to show errors above the form.
Put your html code to show the form fields on the page.
There is no need of session to show errors to the user.

Related

How to stay on php page and display error message on submit form without removing action="ex.php"?

i'm have a form that's posting to another page. But i'm trying to stay on the same page if the fields are null and display all the error messages instead of going into my action page. Is there a way around this? i have tried using javascript to stop the form from submitting however it is not displaying the error messages. I want to know if this do-able using only php? I know i could just put everything in a page but i'm curious which way is more efficient or how it's suppose to be done? thanks a million
register.php
<?php include 'formCheck.php'; ?>
<form method="post" action="add.php">
<div class="textbox">
<label for="uname">Username:</label>
<span class="error">* <?php echo $uerror;?></span>
<input type="text" name="username" placeholder="Username">
</div>
add.php
<?php
require_once "db.php";
if ( !empty($_POST['username'])) {
$u = mysqli_real_escape_string($db, $_POST['username']);
$sql= "INSERT INTO users (username) VALUES ('$u')";
echo "<pre>\n$sql\n</pre>\n";
mysqli_query($db,$sql);
echo 'Success -Continue...';
return;
}
formCheck.php
<?php
$uerror = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$uerror = "Username is required";
}
}
?>
You can use jQuery to help you with this task.
$( "form" ).submit(function( event ) {
event.preventDefault(); //prevents from reloading
// your stuff
return false;
});

isset and !empty always returns true for login field

I'm trying to create a php file (login.php) that can check the login field and validate the username and password. At the moment, it's just checking username using regex. Below is my code. I can't trigger the second else clause, it seems that isset and !empty are always true, even when I can see that they're visually empty, like immediately after refreshing the page.
<?php
if (isset($_POST['login']) && !empty($_POST['login'])) {
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST['username'])) {
echo 'set';
}
else {
echo 'wrong';
}
} else {
echo 'required field';
}
?>
<div id="login"> <!-- Login field with link to registration -->
<form method="POST" action="login.php">
<Legend>Login</Legend>
Username <input type="text" name="username"/>
Password <input type="password" name="password"/>
<input type="submit" name="login">
<div id="register">
Not a member? Click here to register!
</div>
</form>
</div>
I would suggest something more like this. First, check if $_POST['login'] is set first, so that you won't check anything else if the submit button hasn't been clicked yet. Then inside that, verify that username and password have been entered. If they have, go on with however you're going to validate them.
if (isset($_POST['login'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
echo 'required field';
} else {
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST['username'])) {
echo 'set';
}
else {
echo 'wrong';
}
}
}
Try this. Just check if any POST request are made,
if (!empty($_POST))
{
// Your code...
}

php prevent form resubmission using sessions

So I am trying to prevent form resubmission using sessions
and this is my code :
<?php
session_start();
if(isset($_GET['unid']))
{
if ($_GET['unid']==$_SESSION["uid"])
{
echo "Form is Submited do something";
}
else
{
echo "no you can't do that";
}
}
$unid = md5(uniqid());
$_SESSION["uid"] = $unid;
?>
<form method="GET">
<input name="name" value="test">
<input name="unid" value="<?php echo $unid;?>">
<input type="submit">
and it works ...but if the user opens another tab then it will break so how can I fix it ?
I'm not sure about this but may be assigning a new global session variable will work, say $_SESSION['checkSub']. So once the form is submitted, set it to 1 or true and only let form submission if it isn't 1 or false.
You can check to see if the unid is set in the session before generating a new unique id. See updated code below:
<?php
session_start();
if(isset($_GET['unid']))
{
if (isset($_SESSION['unid']) && $_GET['unid']==$_SESSION['unid'])
{
//form has been submitted with matching unid - process it as needed
unset($_SESSION['unid']);
}
else
{
// Form was resubmitted or some other logic error
}
}
$unid = ''; //declare here for good scope
if (isset($_SESSION["unid"])) {
$unid = $_SESSION["unid"];
}
else {
$unid = md5(uniqid());
$_SESSION["unid"] = $unid;
}
?>
<form method="GET">
<input name="name" value="test">
<input name="unid" value="<?php echo $unid;?>">
<input type="submit">
Rather than using form method GET, try to use POST. It will work for you. The $_POST array will only have data in it when form is submitted, so you should not have to use the session to know whether form is submitted or not.

Registration Validation in PHP, with Javascript alert boxes

I wanted to create a registration validation system (to make sure that the user registered has valid info) with PHP and Javascript Alert Boxes. Each time a user does not do a field correctly, I want him to get an alert box saying that it is incorrect. So here it is:
Code #1 - For generating alerts in PHP (This is for the event in the button).
function alert($string)
{
echo "javascript:alert('$string');";
}
Code #2 - PHP placed inside the onclick="" attribute for the submit button.
if (!isset($fname) || empty($fname))
{
alert('Please enter your first name!');
}
elseif (!isset($lname) || empty($lname))
{
alert('Please enter your last name!');
}
elseif (!isset($gender) || empty($gender))
{
alert('Please specify your gender!');
}
elseif (!isset($phone) || empty($phone) || strlen($phone) != 10)
{
alert('Please enter your correct Phone Number!');
}
elseif (!isset($user) || empty($user) || strlen($user) > 10 || strlen($user) < 5)
{
alert('Please enter a Username that is 5-10 characters long!');
}
elseif (!isset($pass) || empty($pass) || strlen($pass) > 10 || strlen($pass) < 5)
{
alert('Please enter a Password that is 5-10 characters long!');
}
elseif (!isset($repass) || empty($repass) || $pass != $repass)
{
alert('Please repeat your Password');
}
else
{
$query = mysql_query($query_send_form);
query_error($query);
}
As you have probably realised, the variables are actually equal to the $_POST values of the field in the form.
So the problem is that the onclick of the button is ALWAYS equal to onclick="
javascript:alert('Please enter your first name!');" It wouldn't change.
Please don't give me a complete javascript alternative to the system, I want to learn PHP for now.
Thanks for your help in advance.
EDIT #1
An important thing I forgot to mention was that the form target is just an iframe on the same page, so that the content the user has entered stays while he is being shown the error.
<form method="post" target="frame" action="register.php">
register.php is the same page where the form HTML and the validation PHP is.
EDIT #2
The data is being posted. Here are the declared varibles:
#$fname = $_POST['fname'];
#$lname = $_POST['lname'];
#$gender = $_POST['gender'];
#$phone = $_POST['phone'];
#$user = $_POST['user'];
#$pass = $_POST['pass'];
#$repass = $_POST['repass'];
You really shouldn't do that kind of validation like that...
Anytime you want to tell the user something is invalid because of logic rules, it is done with javascript on the front side. There are some good plugins out there written in either jquery or javascript out here. You can also make something simple on your own. This helps the user because then they don't have to submit the page to find out that their password isn't long enough.
You still need to do validation after POST and before putting things in the database because of sql injection. That kind of validation is a little different because you're just looking for things that are harmful.
This example is self-contained. The messages go to a div instead of alerts.
<?php
$message = "";
$submit = (isset($_POST['submit'])) ? $_POST['submit'] : '';
if (!empty($submit)) {
$message = "thanks for submitting the form!";
}
?><div id="errors"><?php echo $message ?></div>
<form id="my_form" name="my_form" action="" method="post">
<div style="display:inline-block;">Name<br/>
<input name="first_name" type="text" size=8 class="required"/>
<input name="last_name" type="text" size=16 class="required"/>
</div>
<div style="display:inline-block;">Gender<br/>
<select name="gender" class="required">
<option value=''></option>
<option value='M'>M</option>
<option value='F'>F</option>
</select>
</div>
<div style="display:inline-block;">Phone Number<br/><input name="phone" type="text" class="required"/></div><br/>
<div style="display:inline-block;">Username<br/><input name="username" type="text" class="required"/></div><br/>
<div style="display:inline-block;">Password<br/><input name="password" type="password" class="required"/></div>
<div style="display:inline-block;">Repeat Password<br/><input name="repeat_password" type="password" class="required"/></div><br/>
<div style="display:inline-block;">Description<br/><textarea name="description"></textarea></div><br/>
<button type="submit">Submit</button>
<input type="hidden" name="submit" value="submit"/>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<style> .invalid {border-color:red}</style>
<script>
$(document).ready(function(){
$("#my_form").submit(function(e){
var messages = perform_validation();
if (messages.length!==0) {
$("#errors").empty();
$.each(messages,function(i,msg){
$("#errors").append(msg+"<br/>");
});
e.preventDefault();
return false;
}
// else continue to submit form normally
});
function perform_validation()
{
var messages = [];
$("#my_form :input.required").removeClass("invalid");
$("#my_form :input.required").each(function(){
if ($(this).val().length===0) {
$(this).addClass("invalid");
var name = $(this).attr('name').replace('_',' ');
messages.push("Please provide a "+name+".");
}
});
var password = $("input[name='password']").val();
if (!(password.length>=5 && password.length<=10)) {
messages.push("Password length must be between 5 and 10 characters.");
}
else {
if (password!=$("input[name='repeat_password']").val()) {
messages.push("Repeat password doesn't match first password.");
}
}
return messages;
}
});
</script>
Unless you have magic quotes turned on (and I hope you don't), your values such as $fname will always be undefined. You probably want to replace those with $_POST['fname'].
On a side note, you can use just empty() without !isset() since empty() will return FALSE if the value is not set.

user invalid login

I am creating my own website just to get some experience. I've been working on it for 3 days and am at the point where I can sign up and sign in.
When signing in, if the combination of the username and password is not found in the database, my code displays an error message telling the user that either he didn't sign up yet or he is entering a wrong user email or password.
But, the message is displayed in a new page, instead of the sign in page.
I looked at some tutorials online, but didn't find a good explanation for it. Could someone please give me some advise?
I am using PHP for the database connection.
I just typed a very basic example:
<?php
//login.php
$msg = ''; //to store error messages
//check whether the user is submitting a form
if($_SERVER['REQUEST_METHOD'] == 'POST') //check if form being submitted via HTTP POST
{
//validate the POST variables submitted (ie. username and password)
//check the database for a match
if($matchfound == TRUE) //if found
{
//assign session variables and other user datas
//then redirect to the home page, since the user had successfully logged in
header('Location: index.php');
}
else
{
$msg = 'Error. No match found !'; //assign an error message
include('login_html.php'); //include the html code(ie. to display the login form and other html tags)
}
}
else //if user has not submitted the form, just display the html form
{
include('login_html.php');
}
//END of login.php
?>
login_html.php :
<html>
<body>
<?php if(!empty($msg)) echo $msg; ?> <!-- Display error message if any -->
<form action="login.php" method="post">
<input name = "username" type="text" />
<input name = "password" type="password" />
<input name = "submit" type="submit" value="Submit" />
</form>
</body>
</html>
This is not a complete code. But I just created it for you to understand how this can be done. :)
Good luck
Your opening form tag should look like this: <form action="" method="post">. The empty "action" attribute will cause the page to post back to itself. Just check the $_POST for username and password to determine whether to test for a match or just show the form.
And please be sure to hash your passwords and sanitize your inputs!
you can do it without going to a new page.
<?php session_start(); ?>
<?php
if(isset($_POST) && isset ($_POST["admin_login"])){
$user_data_row = null;
$sql="SELECT * FROM table_name WHERE <table_name.field name>='".mysql_real_escape_string($_POST['email'])."'
and <table_name.field name='".mysql_real_escape_string($_POST['password'])."'
;
$result=mysql_query($sql);
$user_data_row=mysql_fetch_assoc($result);
if(is_array($user_data_row)){
$_SESSION['user_id'] = $user_data_row['id'];
header("Location: <your page name>");
}else{
$_SESSION['message'] = "Valid email and password required";
}
}
?>
<?php if(isset($_SESSION['message'])){
echo "<li>{$message}</li>";
?>
<form action="" method="post" id="customForm">
<label>Email:</label>
<input type="text" id="email" name="email">
<label>Password:</label>
<input type="password" id="password" name="password">
<input type="submit" value="Login" id="send" name="admin_login">
</form>
may be its helps you....
Basically what you need to do, is post the form to the same page.
Once you have that, at the type just check for the $_POST: if($_SERVER['REQUEST_METHOD'] == 'POST')
If it is a post, check the username and password and either show an error or redirect to the signed in page. After this, display the login form.
So, if it's an error, they'll get the error and then the login form. If it's not posted, they'll get just the login form, and if it's a valid login, they'll get redirected to the proper page before the login form is shown.

Categories