The POST form works fine and all the data is submitted properly, $captcha_code is returning the correct output and so is $captcha. However, when I check if $captcha == $captcha_code it always returns failure. Can someone please explain as to why this happens?
include 'inc/simple-php-captcha/simple-php-captcha.php';
$_SESSION['captcha'] = simple_php_captcha();
$captcha_code = $_SESSION['captcha']['code'];
if(isset($_POST['register'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$captcha = $_POST['captcha'];
if($captcha == $captcha_code) {
echo 'captcha success';
} else {
echo 'captcha failure';
}
}
You need to generate the captcha before itself in login.php
login-form.php
<?php
// start session and generate captcha and it's image
session_start();
include 'inc/simple-php-captcha/simple-php-captcha.php';
$_SESSION['captcha'] = simple_php_captcha();
// render the form
?>
<input type="text" name="email">
<input type="text" name="password">
..
..
<input type="text" name="captcha">
<img src="<?php $_SESSION['captcha']['image_src']; ?>">
<input type="submit">
login-submit.php
$captcha_code = $_SESSION['captcha']['code']; //retrive what code was generated before
if(isset($_POST['register'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$captcha = $_POST['captcha'];
if($captcha == $captcha_code) { // try matching
echo 'captcha success';
} else {
echo 'capture failure';
}
}
Related
registration_from.php
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Name:
<input type="text" name="name">
<br/> <br/>
Username:
<input type="text" name="username">
<br/> <br/>
Password:
<input type="password" name="password">
<br/> <br/>
Email:
<input type="text" name="email">
<br/> <br/>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
<?php
require('connect.php');
require('validation.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users
(`id`,`name`,`username`, `password`, `email`) VALUES ('','".$name."',
'".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
validation.php
<?php
// define variables and set to empty values
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
connect.php
<?php
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
?>
I'm developing a simple Registration from with four inputs i.e., Name, username, password, email.when the user fills out the form and click submit button then all the filled data should go n save in data base which is working fine in my case, but when the user wont fill any data and if user simply clicks a submit button then error message should be shown like "ALL FIELDS ARE NECESSARY", but where in my case even if i click submit button without entering any values the mesage i'm getting as success and all the null values are getting stored in the data base which should not happen, my output should be if i fill the forms n click submit button then all the data should be stored in database and if i click submit button without filling out any value then error should throw that "all field to be filled" and no null value should be stored in data base, please can any one guide me what changes i should do so that to get my desired output.
If you don't mind adding a little more code, you code do like:
In your registration_form.php
<?php
require('validation.php'); // Require first to do validation before queries
require('connect.php');
// Remove the part where you set variables to $_POST params
// Variables are already set inside validation.php
/**
* Then, I recommend moving queries to **connect.php**
* to have all your sql functions inside one file.
* Also moving the inserting of data to a function for easy grouping/calling
*/
if (isset($_POST["submit"]) {
// Check if validation does not fail
if ($emailErr == "" || $nameErr == "" || $userErr == "" || $passwordErr == "") {
// Call to insert function
doInsert($name, $email, $username, $password);
} else {
echo $emailErr . " " . $nameErr . " " . $userErr . " " . $passwordErr;
}
}
?>
In your connect.php
function doInsert($name, $email, $username, $password) {
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
$sql = "INSERT INTO users(`id`,`name`,`username`, `password`, `email`)
VALUES ('','".$name."', '".$username."', '".$password."', '".$email."')";
$query = mysqli_query($connect, $sql);
if ($query) {
echo "Success";
} else {
echo "Failure " . mysqli_error($connect);
}
}
Please add error in session and print session in form file.
In validation.php
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
$name = $_POST["name"];
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
if($name == '' || $email == '' || $username == '' || $password == "")
{
echo "ALL FIELDS ARE NECESSARY";
exit();
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
registration_from.php
if(isset($_SESSION['error]) && !empty($_SESSION['error])){
echo $_SESSION["error"]
}
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$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>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
I am trying to reset password but after I submit new password it takes me back to login without changing it. I think this happens because it doesn't remember the email and token. It shows me the form but after I click submit doesn't do anything.
Code:
<?php
if (isset($_GET['email']) && isset($_GET['token'])) {
include('databaze.php');
$conn = new mysqli($servername, $username, $password, $dbname);
$email = $conn->real_escape_string($_GET['email']);
$token = $conn->real_escape_string($_GET['token']);
$data = $conn->query("SELECT did FROM tbldoc WHERE email='$email' AND
token='$token'");
if ($data->num_rows > 0) {
include('reset-form.php');
if (isset($_POST['resetPass'])) {
$password = $_POST["password"];
$password_conf = $_POST['password-conf'];
$email = $_POST["email"];
$token = $_POST["token"];
if (empty($password) || empty($password_conf)) {
echo "<br><br>Fill the form";
} elseif ($password !== $password_conf) {
echo "<br><br>Password doesn't match Password Confirmation";
}
$password = md5($password);
$conn->query("UPDATE tbldoc SET hashedpwd='$password', token='' WHERE email='$email'");
}
} else {
echo "Please check your link!";
}
} else {
header("Location: login.php");
exit();
}
?>
form:
<form method="post" action="resetpassword.php" class="form-signin">
<h2 class="form-signin-heading">Reset Password</h2>
Password <input type="password" class="form-control" name="password" placeholder="Password">
<br>
Password Confirmation <input type="password" class="form-control" name="password-conf"
placeholder="Password Confirmation">
<br>
<input type="hidden" class="form-control" name="email" value="<?php echo $email;?>">
<input type="hidden" class="form-control" name="token" value="<?php echo $token;?>">
<input type="submit" class="btn btn-lg btn-primary btn-block" name="resetPass" value="Reset your Password">
Could you help me?
Your form is type POST and you are expecting GET
isset($_POST['email']) && isset($_POST['token'])
Could be?
May be because of this line, your SQL is not able to search email
$email = $conn->real_escape_string($_GET['email']);
Add this to your form. It will remember the email and token:
<input type="hidden" name="email" value="<?php echo #$email; ?>">
<input type="hidden" name="token" value="<?php echo #$token; ?>">
Your form method is POST and you are checking the data in GET. So every time else part will be called. change this line in your code
if (isset($_GET['email']) && isset($_GET['token'])) {
with
if (isset($_POST['email']) && isset($_POST['token'])) {
Your form action is post method so you need to check the condition as
if (isset($_POST['email']) && isset($_POST['token']))
This is full code. you use some place GET and some place POST method so it will work for POST method...
<?php
if (isset($_POST['email']) && isset($_POST['token'])) {
include('databaze.php');
$conn = new mysqli($servername, $username, $password, $dbname);
$email = $conn->real_escape_string($_POST['email']);
$token = $conn->real_escape_string($_POST['token']);
$data = $conn->query("SELECT did FROM tbldoc WHERE email='$email' AND
token='$token'");
if ($data->num_rows > 0) {
include('reset-form.php');
if (isset($_POST['resetPass'])) {
$password = $_POST["password"];
$password_conf = $_POST['password-conf'];
$email = $_POST["email"];
$token = $_POST["token"];
if (empty($password) || empty($password_conf)) {
echo "<br><br>Fill the form";
} elseif ($password !== $password_conf) {
echo "<br><br>Password doesn't match Password Confirmation";
}
$password = md5($password);
$conn->query("UPDATE tbldoc SET hashedpwd='$password', token='' WHERE email='$email'");
}
} else {
echo "Please check your link!";
}
} else {
header("Location: login.php");
exit();
}
?>
or change your form like <form method="GET" action="resetpassword.php" class="form-signin">
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color:red;}
</style>
</head>
<body>
<?php
$username = $password = $email = "";
$usernameerr = $passworderr = $emailerr = "";
if ($_SERVER["REQUEST_METHOD"]=="POST") {
if (empty($_POST["username"])) {
$usernameerr = "Please fill username";
} else {
$username = test_input($_POST["username"]);
if(!preg_match("/^[a-zA-Z]*$/",$username)) {
$usernameerr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailerr = "Please fill e-mail";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$emailerr = "not a valid e-mail";
}
}
if (empty($_POST["password"])) {
$passworderr = "Cannot be blank";
} else {
$password = test_input($_POST["password"]);
if(!preg_match("/^[a-zA-Z]*$/",$password)) {
$pasworderr = "Must be Letters";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con = mysqli_connect('localhost','root','','my_db');
if (mysqli_connect_errno()) {
echo "Fail to connect :".mysqli_connect_error();
}
$username = mysqli_real_escape_string($con, $_POST["username"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$sql = "INSERT INTO register(Username, Password, Email)
VALUES ('$username','$password','$email')";
if (!mysqli_query($con,$sql)) {
die ('Error: '.mysqli_error($con));
}
echo "Registration successful";
mysqli_close($con);
?>
<h2>Register</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username :<input type="text" name="username" value="<?php echo $username;?>">
<span class="error">*<?php echo $usernameerr;?></span>
<br><br>
Password :<input type="text" name="password" value="<?php echo $password;?>">
<span class="error">*<?php echo $passworderr;?></span>
<br><br>
E-mail :<input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailerr;?></span>
<br><br>
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
Hi, I am a newbie, and I need advice on making registration form. So here is the code for my registration form, the validation code works and it submit data to mysql database too. But, the problem is, it will submit data to database every time it loads (even if it is blank). What line of codes should I add to prevent the form submitting data when it is not filled completely / filled with the right format.
Thx in advance.
You have to check if there's any data in the fields.
Just add this line before your sql executes, after $email = mysqli_real_escape_string($con, $_POST["email"]); :
if ($username != "" && $password != "" && $email != "")
{
//your sql and rest of the script goes here
}
else
{
//don't save the data if it's not completed well
//do whatever you want in that case no valid data was completed
}
Notes: I answered only to your question but be careful, you have some implementation mistakes. You should just use a flag that by default is 1 and, if an error is found in any of your validation functions, the falg should be set to 0 and you should check the value of the flag before the sql instead of checking the content of the $_POST variables again.
Edit: BETTER SOLUTION FOR YOUR CODE
Add this block before the sql:
if ($usernameerr == "" && $passworderr == "" && $emailerr == "")
{
//no errors, all fine we can add to the database
}
else
{
//we have errors, do something but don't add the data
}
Please outsource your DB-Connection and your DB-Insert in some seperate files and speak to them per ajax-request..
your db-insert-query should be taken place after you validation and at the end of the
if ($_SERVER["REQUEST_METHOD"]=="POST") {
block
You did not close the $_SERVER["REQUEST_METHOD"]=="POST" block properly.
Also inside the if ($_SERVER["REQUEST_METHOD"]=="POST") { block you can add another
if condition as if(!empty($_POST["username"] && !empty($_POST["email"] && !empty($_POST["password"]) {....}
I am very new to PHP and I cannot get this if statement to echo when you click submit. My editor isn't showing any errors with the code and it seems to work fine, except for it not echoing the errors.
<html>
<LINK rel='stylesheet' href='style.css' type='text/css'>
<?php
$submit = $_POST['submit'];
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$repeatpassword = md5(strip_tags($_POST['repeatpassword']));
$date = date('Y-m-d');
echo $date;
if ($sumbit)
{
if ($username&&$password&&$repeatpassword)
{
$password = md5($password);
$repeatpassword = md5($repeatpassword);
if ($password==$repeatpassword)
{
if(strlen($username)>25)
{
echo 'Length of username must be less than 25 charcters';
}
else
{
if (strlen($password)>25||strlen($password)<6)
{
echo 'Your password must be 6 to 25 characters long';
}
else
{
echo 'Success!';
}
}
}
else
{
echo 'Passwords do not match';
}
}
else
echo 'Fill in all the fields';
}
?>
<form action='register.php' method='POST'>
<table>
<tr>
<td>Username</td><br />
</tr>
<tr>
<td><input type='text' name='username'></td><br />
</tr>
<tr>
<td>Password</td><br />
</tr>
<tr>
<td><input type='password' name='password'></td><br />
</tr>
<tr>
<td>Repeat Password</td><br />
</tr>
<tr>
<td><input type='password' name='repeatpassword'></td><br />
</tr>
</table>
<p>
<input type='submit' name='submit' value='Register'>
</form>
</html>
There is a typo
its
if ($sumbit)
should be
if ($submit)
Add this at the beginning of your code:
ini_set("display_errors", true);
error_reporting(E_ALL);
You have to enable error reporting, its turned off by default afaik. Anyways:
if ($sumbit)
I suppose you want to check if its set. The function in php for that is called isset(), so your code would be:
if(isset($submit)) {}
Try this one, it may help you.
if (isset($_POST['submit']))
{
$submit = $_POST['submit'];
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$repeatpassword = md5(strip_tags($_POST['repeatpassword']));
$date = date('Y-m-d');
echo $date;
if ((isset($username))&&(isset($password))&&(isset($repeatpassword)))
{
$password = md5($password);
$repeatpassword = md5($repeatpassword);
if ($password==$repeatpassword)
{
if(strlen($username)>25)
{
echo 'Length of username must be less than 25 charcters';
}
else
{
if (strlen($password)>25||strlen($password)<6)
{
echo 'Your password must be 6 to 25 characters long';
}
else
{
echo 'Success!';
}
}
}
else
{
echo 'Passwords do not match';
}
}
else
echo 'Fill in all the fields';
}
AND For Form use :
<form action='' method='POST'>
<input type='submit' name='submit' value='Register'>
</form>
try this
if(isset($_POST['submit']))
{
if (isset($_POST['username'], $_POST['password'], $_POST['repeatpassword']))
{
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$repeatpassword = md5(strip_tags($_POST['repeatpassword']));
instead of
if ($sumbit)
{
if ($username&&$password&&$repeatpassword)
{
your are using sumbit and use submit
if ( !empty($submit) ){
{
there is a md5 of repeatpassword being done twice and md5 of password being done once. so the if condition fails
if ($password==$repeatpassword)
Before if submit condition
$password = strip_tags($_POST['password']);
$repeatpassword = md5(strip_tags($_POST['repeatpassword']));
Inside if submit condition
$password = md5($password);
$repeatpassword = md5($repeatpassword);
I have a form submitting to intself. If the post variables are set, then I want them to be redirected to employee_profile.php. Currently the header location does not work even when the post variables are set. Any ideas?
<?php
$email_error = $password_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$email_error = "Missing Email";
} else {
$email = $_POST["email"];
}
if (empty($_POST["password"])) {
$password_error = "Missing Password";
} else {
$email = $_POST["email"];
$password = $_POST["password"];
header ('Location: employee_profile.php');
}
}
?>
The form:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
Email: <input type="text" name="email" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $email_error;?></span><br />
Password: <input type="password" name="password">
<span class="error"><?php echo $password_error;?></span><br />
<input type="submit" value="Submit">
</form>
The PHP header (using HTTP/1.1) redirect requires an absolute URL.
Try the following:
<?php
// from PHP documentation, see http://php.net/manual/de/function.header.php
$host = $_SERVER['HTTP_HOST'];
// or:
// $host = $_SERVER['SERVER_NAME'];
$email_error = $password_error = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["email"])) {
$email_error = "Missing Email";
} else {
$email = $_POST["email"];
}
if(empty($_POST["password"])) {
$password_error = "Missing Password";
} else {
$password = $_POST["password"];
}
// some additional fixes: finally check if both is valid
if($email_error == $password_error) {
header("Location: http://$host/employee_profile.php");
}
}
?>
you can try some thing like this. currently in your script even when the email is not set but password is set, header function is called.
$email = (isset($_POST['email']) && !empty($_POST['email'])) ? $_POST['email'] : "Missing Email";
$password = (isset($_POST['password']) && !empty($_POST['password'])) ? $_POST['password'] : "Missing Password";
if($email != "Missing Email" && $password != "Missing Password"){
header ('Location: employee_profile.php');
}
(warning: here any values passed as email and password will get the user to employee_profile)
also see if you are printing some thing or some htmls before calling header.
is it throwing any error, if so can you also print the error here?