PHP registration form print error - php

Finished making a php/mysql login system. I've also made a registration system that works, but I need to make it print out a error in the html if the email/username is already registered or if the username or password from the inputs is missing etc.
As it is now, it will automatically die and prints out the error message on a empty page.
It looks like this:
if(empty($_POST['password']))
{
die("Please enter a password");
}
I have tried this:
$errors = array();
if(empty($_POST['password']))
{
$errors[] = 'Please enter a password';
}
And then print it out inside the html. But it will ignore the password input and just register the user account anyway (with a encrypted password, in phpmyadmin).
It looks like has to die someway, but how should i do it?
Here's the whole code:
<?php
require("*mysql_connection file*");
if(!empty($_POST))
{
if(empty($_POST['username']))
{
die("Please enter a username.");
}
$errors = array();
if(empty($_POST['password']))
{
$errors[] = 'Please enter your password';
}
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
$query = "
SELECT
1
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
die("This username is already in use");
}
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
die("Email already registered.");
}
$query = "
INSERT INTO users (
username,
password,
salt,
email
) VALUES (
:username,
:password,
:salt,
:email
)
";
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password . $salt);
}
$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt,
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
header("Location: *login page*");
die("Redirecting to *login page*");
}
?>

<?php
require("*mysql_connection file*");
if(!empty($_POST))
{
if(empty($_POST['username']))
{
die("Please enter a username.");
}
$errors = array();
if(empty($_POST['password']))
{
$errors[] = 'Please enter your password';
}
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
$query = "
SELECT
1
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
die("This username is already in use");
}
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
die("Email already registered.");
}
$query = "
INSERT INTO users (
username,
password,
salt,
email
) VALUES (
:username,
:password,
:salt,
:email
)
";
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password . $salt);
}
$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt,
':email' => $_POST['email']
);
if (empty($errors)) { /********* EDITS ***********/
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
}/********* EDITS ***********/
header("Location: *login page*");
die("Redirecting to *login page*");
}
?>
It's far from optimal, but I can't be arsed to rewrite your whole code.
Major remark is to use openssl_random_pseudo_bytes instead of your own stuff to make up for salt, or you can just take IV out of mcrypt family of functions.

Try this :-
if(""== trim($_POST['password']))
{
die("Please enter a password");
}
else //password is entered
{
//your code
}

Related

Header Location PHP not working? [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 6 years ago.
I am trying to make a login and register system in PHP and i keep getting an error code when i use header("Location: index.php")and this is the error i get:
Warning: Cannot modify header information - headers already sent by (output started at C:\Users\Omg\Desktop\XAMPP\htdocs\Websites\Social-Network\register.php:43) in C:\Users\Omg\Desktop\XAMPP\htdocs\Websites\Social-Network\register.php on line 141
index.php
Here's my PHP code:
if(!empty($_POST)) {
if(empty($_POST['username'])){
echo("Please enter a Display Name<br />");
}
if(empty($_POST['password'])){
echo("Please enter a password<br />");
}
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
echo("Please enter a valid email address<br />");
}
$query = "
SELECT
1
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
die("Failed to run query: ");
}
$row = $stmt->fetch();
if($row){
echo("This name is taken by another person<br />");
}
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
echo("Failed to run query: ");
}
$row = $stmt->fetch();
if($row){
echo("This email is already taken!<br />");
}
$query = "
INSERT INTO users (
username,
password,
salt,
email
) VALUES (
:username,
:password,
:salt,
:email
)
";
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++) {
$password = hash('sha256', $password . $salt);
}
$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt,
':email' => $_POST['email']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch(PDOException $ex) {
echo("Failed to run query: ");
}
header("Location: index.php");
die("index.php");
}
I am using a website to help me with this, i also have a database connection but it doesn't mention that. Any help would be appreciated.
Actually the error is quite explicative: the header must be the very first thing you send to the client, before the body.
All that echoes are part of a body.
Furthermore it looks like a mixture between an ajax call and a standard one. What are you exactly trying to achieve?

Php register tweeks using PDO

So ive got my connection to my database and ive got a nice little register script working using PDO. In my code it will die if; a username is not input into a field, the username is taken, the passwords do not match etc. I would not like it to die i would like it to echo out the "Please enter a username" so the user can correct the information and continue with the for.
<?php
if(!empty($_POST))
{
if(empty($_POST['Username']))
{
die("Please enter a username.");
}
if(empty($_POST['Password']))
{
die("Please enter a password.");
}
if(!filter_var($_POST['Email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
$query = "
SELECT
1
FROM users
WHERE
Username = :Username
";
$query_params = array(
':Username' => $_POST['Username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
die("This username is already in use");
}
$query = "
SELECT
1
FROM users
WHERE
Email = :Email
";
$query_params = array(
':Email' => $_POST['Email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
die("This email address is already registered");
}
$query = "
INSERT INTO users (
Username,
Password,
salt,
Email
) VALUES (
:Username,
:Password,
:salt,
:Email
)
";
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$Password = hash('sha256', $_POST['Password'] . $salt);
for($round = 0; $round < 65536; $round++)
{
$Password = hash('sha256', $Password . $salt);
}
$query_params = array(
':Username' => $_POST['Username'],
':Password' => $Password,
':salt' => $salt,
':Email' => $_POST['Email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
header("Location: login.php");
die("Redirecting to login.php");
}
?>

insert user id in another table during registration

I have a registration form that captures email and password. Once the form is submitted it will add an AUTO_INCREMENT userid, email, and password into my users table. During this same submit process I would like to add the ID that was created in my users table to a users_preferences table.
Here is what I currently have:
require("config.php");
if(!empty($_POST))
{
// Ensure that the user fills out fields
if(empty($_POST['username']))
{ die("Please enter a username."); }
if(!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL))
{ die("Invalid E-Mail Address"); }
if(empty($_POST['password']))
{ die("Please enter a password."); }
// Check if the username is already taken
$query = "
SELECT
1
FROM users
WHERE
username = :username
";
$query_params = array( ':username' => $_POST['username'] );
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
$row = $stmt->fetch();
if($row){ die("This email address is already registered"); }
// Add row to database
$query = "
BEGIN;
INSERT INTO users (
username,
password,
salt
) VALUES (
:username,
:password,
:salt
) ;
INSERT INTO user_preferences (
user_id
) VALUES (
$user_id
);
COMMIT;
";
$user_id = mysql_insert_id();
// Security measures
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++){ $password = hash('sha256', $password . $salt); }
$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
header("Location: index.php");
die("Redirecting to index.php");
}
The registration of the user will go through and add the data to the database, but no data is added to the user_preferences table. How do I get this to add the last user id to the second table?
The problem as I see it is that you are trying to put the value of $user_id into the query, yet it would only receive a value in the next command row (although you're not actually running the first query, you're just trying to fetch the last inserted id).
You should first run the INSERT INTO users... query, then retrieve the last inserted id, then run the second query (INSERT INTO user_preferences...).
Also assuming you're using PDO, last inserted id should be $db->lastInsertId() in your context.
** Update
Alright, without changing your code, just mostly refactoring it a tad bit, you should try something like this:
function checkDataValidity(){
if(empty($_POST['username'])){
throw new Exception("Please enter a username.");
}
if(!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL)){
throw new Exception("Invalid E-Mail Address");
}
if(empty($_POST['password'])){
throw new Exception("Please enter a password.");
}
}
function doesUserExist($dbHandler){
$query = " SELECT 1 FROM users WHERE username = :username;";
$query_params = array( ':username' => $_POST['username'] );
$stmt = $dbHandler->prepare($query);
$result = $stmt->execute($query_params);
if ($stmt->rowCount() > 0){
throw new Exception('This email address is already registered');
}
}
function insertNewUser($dbHandler){
try{
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++){
$password = hash('sha256', $password . $salt);
}
$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt
);
$dbHandler->beginTransaction();
$query = "INSERT INTO users (username, password, salt) VALUES ( :username, :password, :salt );";
$stmt = $dbHandler->prepare($query);
$result = $stmt->execute($query_params);
$newUserId = $dbHandler->lastInsertId();
$dbHandler->commit();
}catch(Exception $dbException){
$dbHandler->rollback();
$newUserId = NULL;
}
return $newUserId;
}
function insertUserPreference($dbHandler, $userId){
$query_params = array(
':user_id' => $userId
);
try{
$dbHandler->beginTransaction();
$query = "INSERT INTO user_preferences ( user_id ) VALUES ( :user_id );";
$stmt = $dbHandler->prepare($query);
$result = $stmt->execute($query_params);
$dbHandler->commit();
}catch(Exception $dbException){
$dbHandler->rollback();
}
}
require("config.php");
if(!empty($_POST))
{
try{
checkDataValidity();
doesUserExist($db);
$newUserId = insertNewUser($db);
if (!is_null($newUserId)){
insertUserPreference($db, $newUserId);
}else{
throw new Exception('Error inserting user');
}
header("Location: index.php");
die("Redirecting to index.php");
} catch (Exception $e){
echo 'The following error occured: <br/>'.$e->getMessage();
}
}
Don't let the changes baffle you - I've only rearranged your code to be more easily readable. The above solves the original problem by moving the "user insert" into one function where we return the new ID if the insert was successful, otherwise null value, and we also move the second half of the query into its own function.

How to display message when a user submits the form

Hi I have the following code. I was just wondering how to add a message/popup to say "thanks for registering" if everything is successful. Here is the code and btw i am new the php. Thanks for your help
<?php
require("config.php");
if(!empty($_POST))
{
// Ensure that the user fills out fields
if(empty($_POST['username']))
{ die("Please enter a username."); }
if(empty($_POST['password']))
{ die("Please enter a password."); }
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{ die("Invalid E-Mail Address"); }
// Check if the username is already taken
$query = "
SELECT
1
FROM users
WHERE
username = :username
";
$query_params = array( ':username' => $_POST['username'] );
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
$row = $stmt->fetch();
if($row){ die("This username is already in use"); }
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage());}
$row = $stmt->fetch();
if($row){ die("This email address is already registered"); }
// Add row to database
$query = "
INSERT INTO users (
username,
password,
salt,
email
) VALUES (
:username,
:password,
:salt,
:email
)
";
// Security measures
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++){ $password = hash('sha256', $password . $salt); }
$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt,
':email' => $_POST['email']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
header("Location: index.php");
die("Redirecting to index.php");
}
?>
Try this -- insert instead of the header( Location:index.php); and die() lines:
Following will display Thanks message for FIVE (content=5) seconds before redirecting to index.php
echo '<h1>Thanks for registering</h1>';
echo '<meta HTTP-EQUIV="REFRESH" content="5; url=index.php">';
Did you consider using jquery?
You can use the "$("#id").submit(function(event)){} with one alert, it will give you a popup with a personalized message.

PHP password change script

I'm trying to make a script that changes an encrypted password inside a MySQL table. I think the code is correct, but the script isnt changing the password. It does detect when the old password is wrong and when the new password doesnt match the conformation password. When everything checks out, it doesnt give an error and just redirects.
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
if(!empty($_SESSION['user']))
unset ($_SESSION['user']);
if(!empty($_POST))
{
$query = "
SELECT
username,
password,
salt
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$pass = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $_POST['old'] . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password !== $row['password'])
{
die("Incorrect old password!");
}
if($_POST['new'] !== $_POST['confirm'])
{
die("Password does not match!");
}
$pass = true;
}
if($pass)
{
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['new'] . $salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password . $salt);
}
$query1 = " UPDATE users SET password = ':password', salt = ':salt' WHERE username = ':username' ";
$query_params1 = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt
);
try
{
$stmt1 = $db->prepare($query1);
$result1 = $stmt1->execute($query_params1);
}
catch(PDOException $e)
{
die("Failed to run query: " . $e->getMessage());
}
header("Location: index.php");
die;
}
else
{
print("Password change failed.");
}
}
You don't quote bound variables:
$query1 = 'UPDATE users SET password = :password, salt = :salt WHERE username = :username";

Categories