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.
Related
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
}
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.
I am creating a website for a university assignment and i have run into a snag while writing some PHP for email address and password change and this error has come up and i can't for the life of me figure out what the issue is.
Error code:
Failed to run query3: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE username = chris' at line 1
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: login.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to login.php");
}
$username = $_SESSION['user']['username'];
if(!empty($_POST))
{
//check for valid email
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$emailInvalid = true;
$emailInvalidAmmount = 1;
goto here;
}
//Check if the new E-mail matches existing E-mail address, if it does no action is needed
if($_POST['email'] !=$_SESSION['user']['email'])
{
$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 query1: " . $ex->getMessage());
}
//retrieve results and check if new E-mail address exists in the database
$row = $stmt->fetch();
if($row)
{
$emailExists = true;
$emailExistsAmmount = 1;
}
}
$query ="SELECT password, salt FROM users WHERE username = :username";
$query_params = array(':username' => $username);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query2: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $_POST['currentPassword'] . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password == $row['password'])
{
$password_ok = true;
}
if($password_ok = true)
{
$newPassword = $_POST['newPassword'];
$confirmPassword = $_POST['confirmPassword'];
if($newPassword == $confirmPassword)
{
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_newPassword . $salt);
for($round = 0; $round <65536; $round++)
{
$password = hash('sha256', $password . $salt);
}
$query ="INSERT INTO users (password, salt) VALUES (:password, :salt)";
$query .= "WHERE username = $username";
$query_params = array(':password' => $password, ':salt' => $salt);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query3: " . $ex->getMessage());
}
}
$passwordChanged = true;
}
}
}
?>
Any help would be much appreciated. Thanks
Since this is for an assignment, I'll be vague. Make sure you're properly parameterizing all of the variables you're including in all of your queries.