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.
Related
I Have login page that i would like to add log file to it, meaning when user logs in it inserts user details to the database.
the first code is my working page
the second code is the statement that I want to insert in my code, but anywhere i add that code my page stops working or no data is passed to database
I would appreciate any help, thank you in advance.
<?php //http://bootsnipp.com/snippets/56A0W - shource code for login page.
require("includes/config/config.php");
$submitted_username = '';
if(!empty($_POST)){
$query = "SELECT id, username, password, salt, email FROM susers 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()); }
$login_ok = false;
$row = $stmt->fetch();
if($row){
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++){
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password']){
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
header ("Location: includes/Sales/".$_POST["username"]."/".$_POST["username"].".php");
die("Redirecting to: sales.php");
}
else {$err[]='Wrong username and/or password!'; //1
header("Location: sales.php"); //2
} if($err) //3
$_SESSION['msg']['login-err'] = implode('<br />',$err); // 1 and 2 and 3 http://tutorialzine.com/2009/10/cool-login-system-php-jquery/ - source code for Error message
exit;
} ?>
second code
$query = "INSERT INTO suserlog (username) VALUES ( :username)";
I believe the code should go somewhere in
if($login_ok)
figured it out, thanks
<?php
require("includes/config/config.php");
$submitted_username = '';
if(!empty($_POST)){
$query = "SELECT id, username, password, salt, email FROM susers WHERE username = :username;";
$query .= "INSERT INTO suserlog (username) VALUES ( :username)";
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?
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");
}
?>
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
}
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.