How to validate form using another php file? - php

I am new to web designing. Now, I have created a form, and if the user input doesn't meet the requirements I display error message, and if it does I do some mysql commands to enter the info to the database. Now one way to do this is to code the php file into the html and use this command,<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> like described [here][1]
But I don't want to put the script in the same file. How do I do that in another php file such that if user input is invalid, it will return to the homepage with the error message updated?
Here is my code
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="register.css">
</head>
<h1>Register as A new user</h1>
<div id="signup">
<form id="registration_form" action="registration.php" method="post">
<p>
<label>Name</label>
<input type="text" name="name"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Email</label>
<input type="text" name="email"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Password</label>
<input type="password" name="passwd"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Repeat Password</label>
<input type="password" name="repasswd"/>
<span class="errorMessage"></span>
</p>
<input type="submit" class="button" value="sign up"/>
</form>
</div>
What should be in the registration.php? Like the link, I do everything, I set a flag to the error, Now if the flag is true I return the user to the homepage with the error messages, and if false, I show a message saying registration successful. How do I do the part,"return to homepage with the appended error message"?

All your validation and bulletproofing should be in the registration.php
stuff like this:
//both parameters are required, so make sure they were passed-in
if(!isset($_GET['name'])) {
die('Must pass \'name\');
//both parameters are required, so make sure they were passed-in
if(!isset($_GET['email'])) {
die('Must pass \'email\');
}
if(!isset($_GET['passwd'])) {
die('Must pass \'password\');
} else {
//do cool stuff here
}
Don't forget your JS validation as well for the front end. I really hope this helps and gives you a bit of direction.

put your validation codes in "validate.php" or any file name you like
then change the action to validate.php to
then in validate.php if validation matches the requirements.
header("Location: registration.php");
if not match
header("Location: back to the httml with form.php");

You can learn form validation here : http://allitstuff.com/registration-form-in-php-with-validation/

Related

how to send data from a php file to another php file?

i am making a "login and signup form" actions for my file. i searched about this many times but i cant find the answer and most of the topics are about sql which i don't use for these files.
im looking for a answer without include, sql, or session in my files
here's my codes
html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Gleacc</title>
<!-- Load external CSS styles -->
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Gleacc GG</h1>
<br>
<form action="data/signedup.php" method="get">
<label for="usn">
<input placeholder="Username" name="usn" required>
</label>
<br>
<label for="psw">
<input placeholder="Password" name="psw" required>
</label>
<br>
<input type="submit" value="Submit">
</form>
<!-- Load external JavaScript -->
<script src="scripts.js"></script>
</body>
</html>
signuped. php:
<?php
$psw = $_GET['psw'];
$usn = $_GET['usn'];
echo "<form action="data/logined.php" method="post"><input placeholder="Username" name="usn" required><br><input placeholder="Password" name="psw" required><br><input type="submit" value="Submit"></form>";
?>
logined.php: none since we cant compair the input because we cant get the $usn and $psw from signuped.php
I think you are being silly.
Are the users signing up every time they are on the website? If not, then you need to save their username and password in some sort of database.
Any other method used in signuped is exposing data that you shouldn't be exposing.
Here is one way to do what you want and make it a tad secure.
<?php
$psw = encrypt($_POST['psw']);
$usn = encrypt($_POST['usn']);
echo "<form action='data/logined.php' method='post'>
<input placeholder='Username' name='usn' required><br>
<input placeholder='Password' name='psw' required><br>
<input class='hidden' value='$usn' name='encusn'><br>
<input class='hidden' value='$psw' name='encpsw'><br>
<input type='submit' value='Submit'></form>";
?>
Where you use CSS to hide the two inputs. Be warned that it is not hard to expose them in the browser by anyone with even a little knowledge of CSS.
In your logined file you encrypt the entered values and compare them with encrypted values from the hidden inputs. I wouldn't use a two-way algorithm and try to decrypt the encrypted values.
first make sure that signuped.php is placed inside the folder data which placed same level as the html file.
then change the action in the html file from get to post and try var_dump($_POST) to see if the inputs has been submited.

Attempting to save user input via HTML form and then refer back to it later

I am currently in the process of designing a Computer Aided Learning package. The welcome screen simply requires the user to type in their name into a text field and click a button which directs them to 'subject selection' page. How would I go about storing the user input and how, if possible, could I refer to the stored value on a seperate html page?
<div id="inputbox">
<form>
<input type="text" name="field" class="textInput" />
</form>
</div>
<div id="introsubmit">
</div>
HTML:
<div id="inputbox">
<form action="script.php">
<input type="text" name="field" class="textInput" />
</form>
</div>
<div id="introsubmit">
</div>
That will send the form to script.php (if no 'action' defined, it will send the form to the very same page, if that html is inside script.php then it will work the same, and if no "method" is defined, if will use GET, you can set <form action="script.php" method="POST"> to change this):
script.php:
<?php
session_start();
$_SESSION['name'] = $_GET['name'];
?>
and then you reuse that variable in the same session, remember to always invoke session_start() before any output in your php.

PHP error display

I am new with php, but I have already made a registration script that works fine. But the problem is every time I press the submit button to check my error, I'm going to a new page.
My question is how I make that error comes on the same page?
The code I am useing for the html form.
I want the error display in the error div box that I made Any idea ?
<div id="RegistrationFormLayout">
<h1>Registration Page</h1>
<div id="ErrorMessage"></div>
<form action="script/registration.php" method="post">
<label for="Username">Username</label>
<input type="text" name="Regi_username">
<label for="FirstName">FirstName</label>
<input type="text" name="Regi_Firstname">
<label for="LastName">LastName</label>
<input type="text" name="Regi_Lastname">
<label for="EamilAddress">Regi_EmailAddres</label>
<input type="text" name="Regi_EmailAddres">
<label for="Password">Password</label>
<input type="password" name="Regi_password">
<button type="submit" value="Submit" class="Login_button">Login</button>
</form>
</div>
If I understand correctly, you want form validation errors there. This is a very common pattern, and the simple solution is to always set a form's action attribute to the same page that displays the form. This allows you to do the form processing before trying to display the form (if there are $_POST values). If the validation is successful, send a redirect header to the "next step" page (with header()).
The basic pattern looks like this (in very very simplified PHP)
<?php
if(count($_POST)) {
$errors = array();
$username = trim($_POST['Regi_username']);
if(empty($username)) {
$errors[] = 'username is required';
}
if(count($errors) == 0) {
header('Location: success.php');
die();
}
}
<ul class="errors">
<?php foreach($errors as $error) { ?>
<li><?php echo $error;?></li>
<?php } ?>
</ul>

How to do a ajax request for login

I have this in my PHP code, and it currently does the login request in the same login.php page but now i want to do it with Ajax. Basically I have this in the login.php
echo '<form method="post" ><div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" name="submitlogin" class="button" />
</div>';
I would like to still use this but have a login_request.php or something where i can send the username and password validated and then change the <div id=login> to say you are logged in!</div> I can do it the conventional way, with the form post .. but now I would like to try it with Ajax.
Any help will be much appreciated.
Regards
What have you tried so far? This is how I would start:
This should get you started:
HTML:
<form id="loginForm">
<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="button" value="Submit" id="submitlogin" class="button" />
</div>
</form>
jQuery:
$("#submitlogin").click(function() {
inputs = //grab then inputs of your form #loginform
$.ajax ({
url: "urltoyourloginphp.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
}
});
})
I wrote this a while ago, it's not quite a full ajax login (i.e. at the end it does still redirect you), but it may serve as a basis for a full ajax login. As a plus you actually don't need https (that was the whole point of this little project).
https://github.com/eberle1080/secure_http_login/blob/master/login.php
The high level steps go something like this:
Ask the server for a seed value (a salt) using an ajax request
Hash the password + seed using a sha1 sum
Ask the server to verify the username and salted + hashed password
If it's valid, the server sets a session cookie indicating that the user is logged in
The server responds to the ajax request with a success / fail message
jQuery has built in .post() and .serialize() methods for wrapping up a form.
$.post("login.php", $("#loginForm").serialize(), function(data) {
//pass information back in with data. if it's JSON, use $.parseJSON() to parse it.
alert('either logged in or errored');
);
You will also need to edit your form so it has an id, like: <form id="loginForm">...
I don't know PHP but will give you an example of how I would have done it with vbscript (classic asp) so you may try to adapt it to PHP as needed.
I, in my applications, don't use the form tag since I first used ajax. So, here we go:
login html page:
include jquery
<script type='text/javascript' src='your-jquery-url'></script>
<script type='text/javascript'>
function tryLogin() {
var inputs='userName='+$('logInUsername').val()+
'&userPassw='+$('logInPassword').val();
//notice that I changed your name= to id= in the form
//notice the '&' in the '&userPassw=
$.post('your-login-validation-page',inputs,function(data) {
eval('var json='+data);
if (json['success'] == 'true') {
$('#loginForm').html('<p>Congratulations! You\'ve been logged in successfully</p>')
} else {
alert(json['errorMessage']);
$('#logInUsername').focus();
}
});
}
</script>
<div id='loginForm' >
<label for="login">User Name</label>
<input type="text" id="logInUsername" />
<label for="Password">Password</label>
<input type="password" id="logInPassword" />
<button onClick='tryLogin(); ' >LOGIN</button>
</div>
login-validation-page
[in vbscript]
user = request.Form("userName")
passw = request.Form("userPassw")
"if is there this user" (coded as if there was a database look up...)
"if the password = passw" (coded as comparing the values)
response.write "{'sucess':'true'}"
else
response.write "{'success':'false','errorMessage':'wrong password'}"
end if
else
response.write "{'success':'false','errorMessage':'user not found'}"
end if
---> end of login-validation-page

how to submit a from with validation in PHP?

I want to submit this form through PHP. with validation for required field and validation for phone number and email field also
<form action="" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_LastName">
Last Name</label>
<input id="txt_LastName" type="text" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_Phone">
Phone</label>
<input id="txt_Phone" type="text" title="First Name. This is a required field" />
</div>
<div class="row requiredRow">
<label for="txt_Email">
Email</label>
<input id="txt_Email" type="text" class="required" title="Email. This is a required field" />
</div>
<div class="row">
<input type="submit" value="" class="button" />
</div>
</form>
In your method attribute inside your form, you need to declare either post or get.
Since your action attribute is "" it will submit to the page itself rather than redirecting to another page, so you can have your code that checks for validation in the same PHP file. First validation that is often checked is if the variable has a value by using isset:
if(isset($_POST['txt_Phone'])) { ... }
This just checks that the Phone number field does not contain empty data. I strongly suggest you perform other validation checks on the POST array so you do not have any users posting malicious code.
You can use functions like htmlspecialchars to prevent user-supplied text depending on what you plan to do with the values
Here are some references to help you along the way in the order they should be viewed.
Form Validation using PHP - PHP and MySQL Tutorial
PHP Advance Form Validation Tutorial
PHP Tutorial Part 2: Form Validation
Your form tag needs a target in the action field and a method in the method field (either GET or POST). So make the action your PHP script.
<form name="input" action="form_submit.php" method="get">
As for field validation, you will either have to parse that inside of the PHP and return a response or use Javascript in the browser to check on the fly.
Here is the shcema of such a script:
if ($_SERVER['REQUEST_METHOD']=='POST') {
//data validation:
$err="";
if (valid_phone($_POST['phone'])) $err="Wrong phone no";
if (!$err) {
//record data:
$sql="...";
query($sql);
Header("Location: ".$_SERVER['REQUEST_URI']); //redirect and exit
exit;
}
}
?>
<html>
<head></head>
<body>
<? if ($err) ?> <font color=red><b><?=$err?></b></font>
<form method="POST" id="get-protected">
here goes your form
Okay, firstly, I like to set the form action to <?=$_SERVER['REQUEST_URI']?> to submit it back to the current page, but leaving it as you have it will work fine too.
Secondly, you need to give all your <input>s a name attribute. This is the variable name that PHP will see.
When your users get an error (something doesn't validate correctly) you don't want all the data they entered to disappear. That means you have to set the value attributes of each input to what they had previously entered. Thus, your form starts to look like this:
<form action="<?=$_SERVER['REQUEST_URI']?>" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" name="first_name" value="<?=htmlspecialchars($_POST['first_name'])?>" />
</div>
...
<div class="row">
<input type="submit" name="submit" value="" class="button" />
</div>
</form>
If you didn't know <?= is a basically a shortcut for <?php echo but it will only work if your server has short tags enabled. Some people prefer to type it out the long way (in case they want to switch servers later, or for future-compatibility, or because they're nutbars), but I say screw them, I'm lazy.
This page that has the form on it, has to saved with a .php extension (well, technically it doesn't have to, but that's another story). Then you need to handle you form validation. You have to code that up yourself. It might look something like this (put it above your form somewhere)
<?php
if($_POST['submit']) {
$errors = array()
if(empty($_POST['first_name'])) $errors[] = 'please enter your first name';
if(empty($errors)) {
// save the data to database or do whatever you want with it
header('redirect:succcess.php');
} else {
foreach($errors as $e) {
echo $e;
}
}
}
?>
It's been a while since I've coded in PHP so forgive me if there are syntax errors. That's the jist of it anyway, I'm sure you can find validation libraries out there if you Google. Might take some of the grunt work out of trying to validate email addresses and such.
Using Javascript you can do the validation for this form.For each condition you can use return true and return false,based on the condition.Then you can submit the value.
Using action attribute in form tag the values will be submitted to that file.

Categories