This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm struggling to get to grasps with PDO from mysql, here is my registration form.
The error I'm receiving isn't quite making sense to me, can anyone help me complete my registration form?
<? include 'includes/overall/head.php';
include 'core/init.php';?>
<div id="page" class="container">
<div id="box1">
<h2 class="title"><? echo $welcome; ?></h2>
<div style="clear: both;"> </div>
<div class="entry">
<form method="POST" action="process_user.php">
Username*: <br/>
<input type="text" name="username" /><br/>
Password*: <br/>
<input type="password" name="password" /><br/>
Confirm Password*: <br/>
<input type="password" name="password_confirm" /><br/>
Email*: <br/>
<input type="text" name="email" /><br/>
Confirm Email*: <br/>
<input type="text" name="email_confirm" /><br/>
<?require_once('recaptchalib.php');
$publickey = "*****";
echo recaptcha_get_html($publickey);?>
<input type="submit" name="submit" value="Register">
</form>
</div>
</div>
<? include 'includes/overall/footer.php'; ?>
This is the prcess_user.php
<? include 'includes/overall/head.php';
include 'core/init.php';?>
<div id="page" class="container">
<div id="box1">
<h2 class="title"><? echo $welcome; ?></h2>
<div style="clear: both;"> </div>
<div class="entry">
<?
require_once('recaptchalib.php');
$privatekey = "*****";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again.");
} else {
if (empty($_POST) === false) {
$required_fields = array('username', 'password', 'password_confirm', 'email', 'email_confirm');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Fields marked with an asterisk are required.';
break 1;
}
}
}
if (empty($errors) === true) {
if(user_exists($_POST['username'] === true)) {
$errors[] = 'Sorry, the username \''.$_POST['username'].'\' is already taken.';
}
if (preg_match("/\\s/", $_POST['username'] == true)) {
$errors[] = 'Your username cannot contain any spaces';
}
if (strlen($_POST['password']) < 6 || strlen($_POST['password'] > 32)) {
$errors[] = 'Your password must be between 6 and 32 characters';
}
if ($_POST['password'] !== $_POST['password_confirm']) {
$errors[] = 'Your passwords did not match';
}
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valid email address.';
}
if (email_exists($_POST['email']) === true) {
$errors[] = 'The email address \''.$_POST['email'].'\' is arealdy registered.';
}
}
}
if (isset($_GET['success']) && empty($_GET['success'])) {
echo 'You\'ve been successfully registered, please check your email inbox to activate your account';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$register_data = array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'email' => $_POST['email'],
'email_code' => md5($_POST['username'] + microtime())
);
register_user($register_data);
header('location: register.php?success');
exit();
} else if(empty($errors) === false) {
echo output_errors($errors);
}
//LINK TO GO BACK AND TRY AGAIN
}
?>
</div>
</div>
<? include 'includes/overall/footer.php'; ?>
And finally, the functions to go with them
<?php
function user_exists($username) {
$username = sanitize($username);
$query = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = `$username`";
$stmt = $dbh->prepare($query);
$stmt->execute();
return ($stmt->rowCount() == 1) ? true : false;
}
function email_exists($email) {
$email = sanitize($email);
$query = "SELECT COUNT (`user_id`) FROM `users` WHERE `email` = $email";
$stmt = $dbh->prepare($query);
$stmt->execute();
return ($stmt->rowCount() == 1) ? true : false;
}
function register_user($register_data) {
array_walk($register_data, 'array_sanitize');
$register_datapw = $register_data['password'];
require ('../../includes/blowfish.class.php');
$bcrypt = new Bcrypt(4);
$register_data['password'] = $bcrypt->hash($_POST['password']);
$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = '\'' . implode('\', \'', $register_data) . '\'';
$query = "INSERT INTO `USERS` ($fields) VALUES ($data)";
$stmt->prepare($query);
$stmt->execute();
}
?>
This is the error I receive
[08-May-2013 09:44:52 America/Denver] PHP Parse error: syntax error, unexpected '$' in .../process_user.php on line 50 Which is
if (isset($_GET['success']) && empty($_GET['success'])) {
The empty() function in PHP has some really weird semantics. Per the fine manual:
Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false.
Similarly, you will need to use $_GET['success'] == false instead of empty($_GET['success']).
As an aside: You are using PDO, which is good, but you are still interpolating user input into your SQL queries, which is very, very, very bad. Learn how to use PDO correctly with bound variables before you proceed.
Related
I have this PHP login script that SHOULD be taking the entered username & password, checking it against a value in MySQL (with the password encrypted via SHA1) and then redirecting the user to the "dash.php" if login is successful or printing an error if not. However whenever I submit the form, it just reloads the login.php... Did I make a stupid error somewhere or am I missing something? Sorry about the huge post!
login.php (containing form):
//Form Action
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('scripts/mysqli_connect.php');
require ('scripts/login_functions.php');
list ($check, $data) = check_login($dbc, $_POST['username'], $_POST['password']);
if($check) {
redirect_user('dash.php');
} else {
$errors = $data;
}
mysqli_close($dbc);
}
?>
// Website HTML
//Form
<form class="contact-form" method="post" action="login.php">
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Username: </label>
<input type="text" name="username" id="username" size="15" class="form-control" required="required" placeholder="username">
</div>
<div class="form-group">
<label>Password: </label>
<input type="password" name="password" id="password" size="15" class="form-control" required="required" placeholder="password">
</div>
<div class="form-group">
<input type="submit" name="submit" value="Login" />
</div>
</div>
</form>
login_functions.php:
<?php
function redirect_user ($page = '../login.php') {
$url = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
$url = rtrim($url, '/\\');
$url .= '/' . $page;
//Redirect User
header("Location: $url");
exit(); //Quit the script.
}
function check_login($dbc, $username = '', $password = '') {
$errors = array();
if(empty($username)) {
$errors[] = 'You forgot to enter your username.';
} else {
$u = mysqli_real_escape_string($dbc, trim($username));
}
if(empty($password)) {
$errors[] = 'you forgot to enter your passord.';
} else {
$p = mysqli_real_escape_string($dbc, trim($password));
}
if (empty($errors)) {
$q = "SELECT username, password FROM users WHERE username='$u' AND password=sha1('$p')";
$r = #mysqli_query ($dbc, $q);
//Check Results
if(mysqli_num_rows($r) == 1) {
$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
return array(true, $row);
} else {
$errors[] = 'The username/password combination is incorrect.';
}
}
}
?>
You are not returning you errors:
return array(true, $row);
} else {
$errors[] = 'The username/password combination is incorrect.';
$return array(false, $errors);
}
And you are not displaying your errors:
// Website HTML
<?php if ($errors):?>
<?php echo '<p>' . implode('</p><p>', $errors) . '<p>';?>
<?php endif;?>
//Form
<form class="contact-form" method="post" action="login.php">
http://170.178.197.250/~devdegree/index.php
Using a form from phpacademy and feel free to visit the temp url and hopefully help me out here.
The problem is that there is a valid database connecting to this website, I enter the fields and it just stays on the register.php file.
Same applies when I create a user from the database itself then use that info to login and again the same problem applies.
This is about 2 years old and it worked for me last year and if there's any files you need to look at I'll reply with the script on here if need be but hopefully it's simply enough.
register.php
<?php
include 'core/init.php';
logged_in_redirect();
include 'includes/overall/header.php';
if (empty($_POST) === false) {
$required_fields = array('username', 'password', 'password_again', 'first_name', 'email');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Fields marked with an asterisk are required';
break 1;
}
}
if (empty($errors) === true) {
if (user_exists($_POST['username']) === true) {
$errors[] = 'Sorry, the username \'' . $_POST['username'] . '\' is already taken';
}
if (preg_match("/\\s/", $_POST['username']) == true) {
$errors[] = 'Your username must not contain any spaces.';
}
if (strlen($_POST['password']) < 6) {
$errors[] = 'Your password must be at least 6 characters';
}
if ($_POST['password'] !== $_POST['password_again']) {
$errors[] = 'Your passwords do not match';
}
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'A valid email address is required';
}
if (email_exists($_POST['email']) === true) {
$errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already in use';
}
}
}
?>
<h1>Register</h1>
<?php
if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
echo 'You\'ve been registered successfully! Please check your email to activate your account.';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$register_data = array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'email_code' => md5($_POST['username'] + microtime())
);
register_user($register_data);
header('Location: register.php?success');
exit();
} else if (empty($errors) === false) {
echo output_errors($errors);
}
?>
<form action="" method="post">
<ul>
<li>
Username*:<br>
<input type="text" name="username">
</li>
<li>
Password*:<br>
<input type="password" name="password">
</li>
<li>
Password again*:<br>
<input type="password" name="password_again">
</li>
<li>
First name*:<br>
<input type="text" name="first_name">
</li>
<li>
Last name:<br>
<input type="text" name="last_name">
</li>
<li>
Email*:<br>
<input type="text" name="email">
</li>
<li>
<input type="submit" value="Register">
</li>
</ul>
</form>
<?php
}
include 'includes/overall/footer.php'; ?>
Again, any other files (there's around 20+) then I'll have a look into showing you if it means you can understand and help me out.
Big thanks,
Dev.
I cant see an action on your form to the register.php. Try adding one like "action="register.php""
Look from the current website you linked the form post correctly to register.php.
Nothing is not working.
You should check your machine for httpd ( or whatever are you using ) logs.
Maybe some warning or some fatalerror of php can explain the problem.
From this code and the website nothing looks wrong.
Okay.. so to start off I only have Php 5.3 so I can't use bcrypt, I am not familiar with salt but an completely willing to do it if someone can help me out. I also would like to know if this script is bad or good for sql injections. My biggest problems is when I use something like crypt and try to get my passwords to match, it won't. I've been working on this for days and can't seem to find the right solution to my problem. the code is not done yet, but its able to run. I'm just doing this on wamp so i dunno if thats a problem? but i cant imagine it is.
REGISTER . PHP
if ((strlen($username)) < 6 || (preg_match("/[^\w-.]/", $username)) ) {
header('Location: Register.php?fail=1');
die();
}
if ((strlen($password)) < 8) {
header('Location: Register.php?fail=2');
die();
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header('Location: Register.php?fail=3');
die();
}
/*
TRIED METHODS
$salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$salt = base64_encode($salt);
$salt = str_replace('+', '.', $salt);
$hash = crypt('rasmuslerdorf', '$2y$10$'.$salt.'$');
$password = $hash;
echo "<script>alert('$password');</script>";
$salt = '$2a$07$usesomadasdsadsadsadasdasdasdsadesillystringfors';
$digest = crypt($password, $salt);
if (crypt($password, $digest) == $digest){
echo "<script>alert('logged in');</script>";
}else{
header('Location: Login.php?fail=3');
die();
}
*/
//PDO CONNECTION
function pdo_connect() {
try {
$db = new PDO("mysql:host=localhost;dbname=XXX", "XXX", "XXX");
return $db;
} catch (PDOException $e) {
//echo $e->getMessage();
//return false;
header('Location: Register.php?fail=6');
}
}
//CHECK IF USERNAME EXISTS
function usernameCheck($username) {
$con = pdo_connect();
$ustmt = $con->prepare("SELECT u_users FROM users WHERE u_users = :name");
$ustmt->bindParam(':name', $username);
$ustmt->execute();
if($ustmt->rowCount() > 0){
header('Location: Register.php?fail=4');
die();
}
$con = null;
}
echo usernameCheck($username);
//CHECK IF EMAIL EXISTS
function emailCheck($email) {
$con = pdo_connect();
$estmt = $con->prepare("SELECT u_email FROM users WHERE u_email = :name");
$estmt->bindParam(':name', $email);
$estmt->execute();
if($estmt->rowCount() > 0){
header('Location: Register.php?fail=5');
die();
}
$con = null;
}
echo emailCheck($email);
//INSERT EMAIL TO NEWSLETTER
function emailnewsletterCheck($email) {
$con = pdo_connect();
$nstmt = $con->prepare("SELECT n_email FROM newsletter WHERE n_email = :email");
$nstmt->bindParam(':email', $email);
$nstmt->execute();
if($nstmt->rowCount() < 1){
$addstmt = $con->prepare('INSERT INTO newsletter (n_email) VALUES (:email)');
$addstmt->bindParam(':email', $email);
$addstmt->execute();
}
$con = null;
}
echo emailnewsletterCheck($email);
//INSERT
function insert($username,$password,$email,$type) {
$con = pdo_connect();
$password = md5($password);
$istmt = $con->prepare('INSERT INTO users (u_users, u_private, u_email, u_type) VALUES (:username, :password, :email, :type)');
$istmt->execute(array(
':username' => $username,
':password' => $password,
':email' => $email,
':type' => $type
));
$con = null;
header('Location: Login.php?success=1');
}
echo insert($username,$password,$email,$type);
}//end submit
?>
<?php
$page_title = "NS : Web Development : Register";
$page_desc = "Register with us for great deals on website development.";
$services = 0;
include_once 'header.php';
?>
<script type="text/javascript">
// This function checks if the username field is at least 6 characters long.
function checkUsernameForLength(whatYouTyped) {
var fieldset = whatYouTyped.parentNode.parentNode.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 5) {
$("span.hint").hide();
}
}
// If the password is at least 4 characters long
function checkPassword(whatYouTyped) {
var fieldset = whatYouTyped.parentNode.parentNode.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 7) {
$("span.hint").hide();
}
}
// This function checks the email address blah#blah.blah
function checkEmail(whatYouTyped) {
var fieldset = whatYouTyped.parentNode.parentNode.parentNode;
var txt = whatYouTyped.value;
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt)) {
$("span.hint").hide();
}
}
// this part is for the form field hints to display
// only on the condition that the text input has focus.otherwise, it stays hidden.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function prepareInputsForHints() {
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++){
inputs[i].onfocus = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
inputs[i].onblur = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
addLoadEvent(prepareInputsForHints);
</script>
<div class="jumbotron">
<div class="container">
<h1>Register for <font color="fb1576">great</font> opportunities</h1>
<p>Get full quotes, package <font color="fb1576">deals</font>, news and updates on the latest themes and scripts, and even <font color="fb1576">win</font> free prizes<font color="fb1576">!</font>
</div>
</div>
<div class="container">
<!-- row of columns -->
<div class="row">
<?php
if ( isset($_GET['fail']) && $_GET['fail'] == 1 ){
echo "<div class='alert alert-danger'>Username must be at least 6 characters in length and can only contain characters matching (a-z) (A-Z) (0-9) and '_' Please try again. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 2 ){
echo "<div class='alert alert-danger'>Password must be at least 8 characters in length and cannot exceed 25. Please try again. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 3 ){
echo "<div class='alert alert-danger'>E-mail is not valid. Please try again. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 4 ){
echo "<div class='alert alert-danger'>Username you chose already exists. Please try again. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 5 ){
echo "<div class='alert alert-danger'>E-mail you entered is already in use. Please try again. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 6 ){
echo "<div class='alert alert-danger'>Something went wrong, we couldn't submit your registration. Please try again later. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
?>
<form name="basicform" id="basicform" method="POST">
<fieldset>
<div class="input-group">
<label for="username">Choose a Username:</label><br>
<input type="text" id="username" name="username" onkeyup="checkUsernameForLength(this);" required class="form-control" maxlength="25" pattern=".{6,}"/>
<span class="hint">Usernames must be a least 6 characters in length and cannot exceed 25. Characters must match (a-z) (A-Z) (0-9) and '_'</span>
</div>
</fieldset>
<fieldset>
<div class="input-group">
<label for="password">Enter a password:</label><br>
<input type="password" id="password" name="password" onkeyup="checkPassword(this);" required class="form-control" maxlength="25" pattern=".{7,}"/>
<span class="hint">The password can be any combination of <strong>characters</strong>, and must be at least 8 characters in length and cannot exceed 25.</span>
</div>
</fieldset>
<fieldset>
<div class="input-group">
<label for="email">Enter your email address:</label><br>
<input type="text" id="email" name="email" onkeyup="checkEmail(this);" required class="form-control" maxlength="30" />
<span class="hint">Please enter your real email address (ie: you#emailprovider.com)</span>
</div>
</fieldset>
<fieldset>
<label for="type">Pick your position of registration:</label><br>
<select name="type">
<option name="type" value="Client">I am a client looking for work to be done</option>
<option name="type" value="Employer">I am an employer looking for a potential hire</option>
<option name="type" value="Employee">I am an employee looking to be hired</option>
</select>
</fieldset>
<fieldset>
<button type="submit" class="btn btn-primary" name="submit" value="submit">Register Now</button>
</fieldset>
</form>
</div>
<!-- //row of columns -->
<?php
include_once 'footer.php';
?>
LOGIN . PHP
$username = $_POST['username'];
$password = $_POST['password'];
//before we even bother connecting to the db start validating
if ( (empty($username)) || (empty($password)) ) {
header('Location: Login.php?fail=1');
die();
}
if ( ((strlen($username)) >25) || ((strlen($password)) >25) ) {
header('Location: Login.php?fail=2');
die();
}
if ( (preg_match("/[^\w-.]/", $username)) ) {
header('Location: Login.php?fail=3');
die();
}
/*
TRIED METHODS
$salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$salt = base64_encode($salt);
$salt = str_replace('+', '.', $salt);
$hash = crypt('rasmuslerdorf', '$2y$10$'.$salt.'$');
$password = $hash;
echo "<script>alert('$password');</script>";
$salt = '$2a$07$usesomadasdsadsadsadasdasdasdsadesillystringfors';
$digest = crypt($password, $salt);
if (crypt($password, $digest) == $digest){
echo "<script>alert('logged in');</script>";
}else{
header('Location: Login.php?fail=3');
die();
}
*/
//PDO CONNECTION
function pdo_connect() {
try {
$db = new PDO("mysql:host=localhost;dbname=XXX", "XXX", "XXX");
return $db;
} catch (PDOException $e) {
//echo $e->getMessage();
//return false;
header('Location: Register.php?fail=6');
}
}
//CHECK IF USERNAME EXISTS
function checkLogin($username,$password) {
$con = pdo_connect();
//$getlogin = $con->query
$getlogin = $con->prepare("SELECT u_users,u_private FROM users WHERE u_users = :username AND u_private = :password");
$getlogin->bindValue(':username', $username, PDO::PARAM_STR);
$getlogin->bindValue(':password', $password, PDO::PARAM_STR);
$getlogin->execute();
if($getlogin->rowCount() > 0){
echo "<script>alert('yes');</script>";
}
$con = null;
}
echo checkLogin($username,$password);
echo "<script>alert('success');</script>";
}
?>
<?php
$page_title = "NS : Web Development : Register";
$page_desc = "Register with us for great deals on website development.";
$services = 0;
include_once 'header.php';
?>
<div class="jumbotron">
<div class="container">
<h1><font color="fb1576">Members</font> log in</h1>
<p> Not yet a member? <font color="fb1576">Sign up today!</font>
</div>
</div>
<div class="container">
<?php
if ( isset($_GET['success']) && $_GET['success'] == 1 ){
echo "<div class='alert alert-success'>Registration successful. Please log in.</div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 1 ){
echo "<div class='alert alert-danger'>Username or Password cannot be left blank.</div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 2 ){
echo "<div class='alert alert-danger'>Sorry, this is not a valid Username or Password.</div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 3 ){
echo "<div class='alert alert-danger'>Username or Password incorrect, please try again.</div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 5 ){
echo "<div class='alert alert-danger'>E-mail you entered is already in use. Please try again. <a href='Register.php'><span class='glyphicon glyphicon-remove'></span> Close</a></div>";
}
if ( isset($_GET['fail']) && $_GET['fail'] == 6 ){
echo "<div class='alert alert-danger'>Something went wrong. Please try again later. </div>";
}
?>
<form class="form-signin" role="form" method="POST">
<h2 class="form-signin-heading">Please sign in</h2>
<p>
<input type="text" class="form-control" placeholder="Username" name="username" required autofocus>
</p>
<br>
<p>
<input type="password" class="form-control" placeholder="Password" name="password" required>
</p>
<label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit" name="submit" value="submit">Sign in</button>
</form>
<?php
include_once 'footer.php';
?>
I REALLLLLYY need to get it so it is secure for my server on launch and can login a user safely.
With PHP version 5.3 you can and should use BCrypt.
For PHP version 5.5 and higher it is recommended to use the new password functions password_hash() and password_verify():
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
For PHP version 5.3.7 and higher there exists a compatibility pack, so you can use the functions above in exactly the same way.
For PHP versions earlier than 5.3.7 you could use the compatibility pack and change the crypt parameter from "$2y$%02d$" to "$2a$%02d$", this generates a BCrypt hash as well. It is the best you can do with older versions, the hashes will be compatible when you update to a newer PHP version.
When you want to verify the password, you cannot do this in the SQL statement directly. In a first step you have to get the stored password-hash from the database (with the username), then you can use this hash in the function password_verify(). The password_verify() function needs to extract the salt from the stored hash.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I have a simple registration form set up, on sending the details to my function to put the data in the database I want the page to redirect to a success page...
This works brilliantly on my local server but when I uploaded it to my live server its just not redirecting
The redirect that is not working is on line 65 :) it just redirects to register.php?success
Any help would be gratefully received. I've seen a few people have had the same problem but their solution would not work for me :(
ALL other header locations work. just this one won't :#
<?php
include 'core/init.php';
//check if logged in
logged_in_redirect();
include 'includes/overall/header.php';
if (empty($_POST) === FALSE) {
$required_fields = array('username', 'password', 'password_again', 'first_name', 'last_name', 'email');
foreach ($_POST as $key => $value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'You appear to have missed something out, all fields are required.';
break 1;
}
}
if (empty($errors) === true) {
if (user_exists($_POST['username']) === true ) {
$errors[] = 'Sorry, the username \'' . $_POST['username'] . '\' is already taken.';
}
if (strlen($_POST['username']) < 6) {
$errors[] = 'Sorry, your username must be at least 6 characters.';
}
if (strlen($_POST['username']) > 25) {
$errors[] = 'Sorry, your username must be under 25 characters.';
}
if (preg_match("/\\s/", $_POST['username']) == true) {
$errors[] = 'Your username must not contain any spaces.';
}
if (strlen($_POST['password']) < 6) {
$errors[] = 'Sorry, your password must be at least 6 characters.';
}
if ($_POST['password'] !== $_POST['password_again']) {
$errors[] = 'Sorry, your passwords do not match.';
}
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false ) {
$errors[] = 'Sorry, you did not provide a valid email address.';
}
if (email_exists($_POST['email']) === true ) {
$errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already registered to an account.';
}
}
}
?>
<h1>Register</h1>
<?php
if (isset($_GET['success']) && empty($_GET['success'])) {
echo "You have been registered successfully.";
} else {
if (empty($_POST) === false && empty($errors) === true) {
// register user
$register_data = array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'email_code' => md5($_POST['username'] + microtime())
);
register_user($register_data);
//header location not working *********************
header('Location: register.php?success');
exit();
} else if (empty($errors) === false) {
//error output
echo output_errors($errors);
}
?>
<form action="" method="post">
Register your account here, all fields are required.
<ul>
<li>
Username: </br>
<input type="text" name="username"/>
</li>
<li>
Password: </br>
<input type="password" name="password"/>
</li>
<li>
Repeat Password: </br>
<input type="password" name="password_again"/>
</li>
<li>
First Name: </br>
<input type="text" name="first_name"/>
</li>
<li>
Last Name: </br>
<input type="text" name="last_name"/>
</li>
<li>
Email: </br>
<input type="text" name="email"/>
</li>
<li>
<input type="submit" value="Register"/>
</li>
</ul>
</form>
<?php
}
include 'includes/overall/footer.php';
?>
Most likely, output buffers are on in the development environment and off in the live environment. Also, displaying errors to users must be off in the live environment or the exact error (output started before headers) would have shown up in the browser.
Check you ini file for this stuff: http://php.net/manual/en/outcontrol.configuration.php
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
UPDATE:
Code is written as is and will stay that way. However, now it doesn't submit the data the user wrote in the form to the database. What's wrong.
Here is the first file. It contains the XML HTTP REQUEST and html form. This file also contains the wild .
<!DOCTYPE html>
<html>
<head>
<?php
require_once 'core/init.php';
?>
<meta charset="utf-8" />
<title></title>
<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js">
//directly below is that wild script tag
</script>
<script type="text/javascript">
function load(thefile, thediv) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject ('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
parameters1 = 'username='+document.getElementById('username').value;
parameters2 = 'email='+document.getElementById('email').value;
parameters3 = 'password='+document.getElementById('password').value;
parameters4 = 'password_again='+document.getElementById('password_again').value;
parameters5 = 'first_name='+document.getElementById('first_name').value;
parameters6 = 'last_name='+document.getElementById('last_name').value;
xmlhttp.open('POST', thefile, true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters1 + '&' + parameters2 + '&' + parameters3 + '&' +
parameters4 + '&' + parameters5 + '&' +parameters6);
}
</script>
</script>
<title>Pop Up Sign Up</title>
</head>
<body>
<div id="popupbox">
<form name="signup" action="" method="post">
Desired Username:
<input id="username" placeholder="Username" value="<?php echo
(isset($desired_username) ? strip_tags($desired_username) : '');?>" type="text"
placeholder="Bob123" name="username" size="14" />
<br /> <br />
Your Email:
Register
<input id="email" placeholder="jasontanner328#gmail.com" value="<?php echo
(isset($desired_email) ? strip_tags($desired_email) : '');?>" type="email"
name="email" size="14" />
<br /> <br />
Your Password:
<input id="password" placeholder="Password" name="password" type="password"
size="14" />
<br /> <br />
Your Password Again:
<input id="password_again" placeholder="Password Again"
name="password_again" type="password" size="14" />
<br /> <br />
First Name:
<input id="first_name" placeholder="Jason" value="<?php echo
(isset($desired_first_name) ? strip_tags($desired_first_name) : '');?>"
name="first_name" type="text" size="14" />
<br /> <br />
Last Name:
<input id="last_name" placeholder="Tanner" name="last_name" value="<?php echo
(isset($desired_last_name) ? strip_tags($desired_last_name) : '');?>" type="text"
size="14" />
<br /> <br />
<center><input type="button" name="submit" value="Register"
onclick="load('register.php', 'popupbox');" /></center>
</form>
</div>
<span id="result">
</span>
</body>
</html>
Here is the second file that deals with inserting the data into the server and what I want to return after the submit button has been clicked on.
<?php
require_once 'core/init.php';
logged_in_redirect();
if (empty($_POST) === false) {
$desired_username = $_POST['username'];
$desired_email = $_POST['email'];
$desired_first_name = $_POST['first_name'];
$desired_last_name = $_POST['last_name'];
$required_fields = array
('username','email','password','password_again','first_name','last_name');
foreach ($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Fields marked with an asterisk are required.';
break 1;
}
}
if (empty($errors) === true) {
if (user_exists($_POST['username']) === true || strlen($_POST ['username']) < 6) {
$errors[] = 'Sorry, the username \'' . $_POST['username'] . '\' is already taken
or is too short. 6 characters are the minimum.';
}
if (preg_match("/\\s/", $_POST ['username']) == true) {
$errors[] = 'Sorry there is a space in your username.';
}
if (strlen($_POST ['password']) < 6) {
$errors[] = 'Your password must be at least 6 characters';
}
if ($_POST ['password'] !== $_POST['password_again']) {
$errors[] = 'Make sure both passwords submitted are the same.';
}
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'A valid email address is required.';
}
if (email_exists($_POST['email']) === true) {
$errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already in use.';
}
if (strlen($_POST ['first_name']) < 2) {
$errors[] = 'Your first name must contain at least two characters.';
}
if (strlen($_POST ['last_name']) < 2) {
$errors[] = 'Your last name must contain at least two characters.';
} }
} else {
//if (isset($_GET['success']) && empty($_GET['success'])) {
//echo 'You have successfully registered. Please check your email to activate your
account.';
// } else {
if (empty ($_POST) === false && empty($errors) === true){
$register_data = array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'email_code' => md5($_POST['username'] + microtime())
);
register_user($register_data);
echo 'WIN';
// header('Location: register.php?success');
// exit();
// } else
if (empty($errors) === false){
echo output_errors($errors);
}
}}
?>
The button on your form is type="submit"; This will submit the form and redirect the page, unless you have it return false; in the onclick attribute. I would suggest, rather, to change the button to a regular button instead of a submit-button:
<input type="button" name="submit" value="Register" onclick="load('register.php', 'result');" />
This change will stop your page from redirecting after submitting the form.
EDIT: After reviewing the full code, the POST-page looks like it has a logic error in the processing (and a few syntax errors; see my comment on the question regarding closing curly braces).
The if (empty($errors) === true) { block ends with an } else { and inside the else-block you output that the user has successfully registered. Translated, this means "if there is an initial error, tell the user they successfully registered." Instead, change everything after (and including) the } else { to:
if (!empty($_POST) && empty($errors)) {
// the form has been submitted and there are no errors
echo 'You have successfully registered. Please check your email to activate your account.';
$register_data = array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'email_code' => md5($_POST['username'] + microtime())
);
register_user($register_data);
} else if (!empty($errors)) {
// there are errors =[
echo output_errors($errors);
}