I want to make register form for my website. But I faced error and this is my code:
<?php
/* Registration process, inserts user info into the database
and sends account confirmation email message
*/
// Set session variables to be used on profile.php page
$_SESSION['email'] = $_POST['email'];
$_SESSION['first_name'] = $_POST['firstname'];
$_SESSION['last_name'] = $_POST['lastname'];
$mysqli = mysqli_connect("localhost","root","","data");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Escape all $_POST variables to protect against SQL injections
$first_name = $mysqli->escape_string($_POST['firstname']);
$last_name = $mysqli->escape_string($_POST['lastname']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'],
PASSWORD_BCRYPT));
$hash = $mysqli->escape_string( md5( rand(0,1000) ) );
// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM login WHERE email='$email'") or
die($mysqli->error());
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'User with this email already exists!';
header("location: error.php");
}
else { // Email doesn't already exist in a database, proceed...
// active is 0 by DEFAULT (no need to include it here)
$sql = "INSERT INTO login (first_name, last_name, email, password, hash)"
."VALUES ('$first_name','$last_name','$email','$password', '
$hash')";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['active'] = 0; //0 until user activates their account with
verify.php
$_SESSION['logged_in'] = true; // So we know the user has logged in
$_SESSION['message'] =
"Confirmation link has been sent to $email, please verify
your account by clicking on the link in the message!";
// Send registration confirmation link (verify.php)
$to = $email;
$subject = 'Account Verification ( clevertechie.com )';
$message_body = '
Hello '.$first_name.',
Thank you for signing up!
Please click this link to activate your account:
http://localhost/login-system/verify.php?email='.$email.'&
hash='.$hash;
mail( $to, $subject, $message_body );
header("location: profile.php");
}
else {
$_SESSION['message'] = 'Registration failed!';
header("location: error.php");
exit();
}
}
The error state that:
Undefined index: firstname, lastname, email, password
at line set session variables and line for escape all $_POST variables to protect SQL injection. Anyone know how to fix this error. Thank you.
You are missing session_start() at the start of your code, this needs to be called before you echo/output anything to the browser.
You'll also need to add session_start to your error.php to read from the session there.
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers...
The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling.
See: http://php.net/manual/en/function.session-start.php
If(isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email'])){
// Escape all $_POST variables to protect against SQL injections
$first_name = $mysqli->escape_string($_POST['firstname']);
$last_name = $mysqli- >escape_string($_POST['lastname']);
}
In PHP, a variable or array element which has never been set is different from one whose value is null; attempting to access such an unset value is a runtime error.
That's what you're running into: the array $_POST does not have any element at the index "username", so the interpreter aborts your program before it ever gets to the nullity test.
Related
I've been developing a secure login page for users but somehow the password verification seems not to work when logging in.
The code below seems to locate the username in the database I've created in MySql, but mainly the password doesn't match every time.
I've made all possible changes, tried all advices but still, no success. If anyone has any solutions for this issue it would be greatly appreciated.
Error always displays that the password is not the right one.
Login Page:
<?php
/* User login process, checks if user exists and password is correct */
// Escape email to protect against SQL injections
$username = $mysqli->escape_string($_POST['username']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$result = $mysqli->query("SELECT * FROM `users` WHERE `username`='$username'");
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that username doesn't exist!";
header("location: error.php");
}
else { // User exists
$user = $result->fetch_assoc();
if ( password_verify($_POST['password'], $user['password']) ) {
$_SESSION['email'] = $user['email'];
$_SESSION['first_name'] = $user['first_name'];
$_SESSION['last_name'] = $user['last_name'];
$_SESSION['username'] = $user['username'];
$_SESSION['active'] = $user['active'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
header("location: dashboard.html");
}
else {
$_SESSION['message'] = "You have entered wrong password, try again!";
header("location: error.php");
}
}
Registration Page:
<?php
/* Registration process, inserts user info into the database
and sends account confirmation email message
*/
// Set session variables to be used on profile.php page
$_SESSION['email'] = $_POST['email'];
$_SESSION['first_name'] = $_POST['firstname'];
$_SESSION['last_name'] = $_POST['lastname'];
// Escape all $_POST variables to protect against SQL injections
$first_name = $mysqli->escape_string($_POST['firstname']);
$last_name = $mysqli->escape_string($_POST['lastname']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$hash = $mysqli->escape_string( md5( rand(0,1000) ) );
// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM users WHERE email='$email'") or die($mysqli->error());
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'User with this email already exists!';
header("location: error.php");
}
else { // Email doesn't already exist in a database, proceed...
// active is 0 by DEFAULT (no need to include it here)
$sql = "INSERT INTO users (first_name, last_name, email, password, hash, active) "
. "VALUES ('$first_name','$last_name','$email','$password', '$hash', 1)";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['active'] = 0; //0 until user activates their account with verify.php
$_SESSION['logged_in'] = true; // So we know the user has logged in
$_SESSION['message'] =
"Confirmation link has been sent to $email, please verify
your account by clicking on the link in the message!";
header("location: profile.html");
}
else {
$_SESSION['message'] = 'Registration failed!';
header("location: error.php");
}
}
Here's the login/signup form the user utilizes to sign in into the system: "http://riselamagana.byethost4.com/projects/webdev3/production/index.php"
and the database would be:
table "users"
The password hash that was generated for "password_28" was: " $2y$10$W3bOAG0BP/DExr/qpiT0ueVS3YHb2NVeSC3.oMAaVQbHlodJVudK.".
It still gives me the error that the password isn't correct, my guess is that the password when compared don't match, but I'm not sure why.
Any further suggestions would surely be appreciated.
The password hash that was generated for "password_28" was: " $2y$10$W3bOAG0BP/DExr/qpiT0ueVS3YHb2NVeSC3.oMAaVQbHlodJVudK.".
Story checks out.
It still gives me the error that the password isn't correct, my guess is that the password when compared don't match, but I'm not sure why.
// ...
$user = $result->fetch_assoc();
// ...
if ( password_verify($_POST['password'], $user['password']) ) {
// ...
Are multiple rows being returned for $result? Is it possible that you're comparing the wrong hash in this location?
To troubleshoot this, hard-code $_POST['password'] to be "password_28" and see if it still fails. Then revert your change and hard-code your password hash. Does it still fail?
If it fails the first time, you're probably altering $_POST somewhere else in your application and that's causing the validation to fail.
If it fails the second time, first check that you're only getting one row back (otherwise, this is a trivial fix: make sure you use the correct password hahs for the correct user). If you are, you're probably running into an encoding issue with how your password hashes are being stored. Is the database column too short for the password hash? (Generally you want varchar(255) or TEXT for MySQL, since MySQL truncates by default unless you're running in strict mode.)
Finally, I'd like to recommend not using $mysqli->escape_string() and instead adopting prepared statements. Prepared statements are a much more robust strategy for preventing SQL injection in PHP software than escaping.
You're not comparing to the hashed password, you're comparing the raw post password...
//In your code, line 6, you hash the password
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
//On line 16 you don't
if ( password_verify($_POST['password'], $user['password']) ) {
//So try this instead...
if ( password_verify($password, $user['password']) ) {
Basically I set up a self signed SSL certificate and all of a sudden my register forum stopped working, it almost feels as if it goes into a redirect loop but it doesn't, the way my register works is that you need to verify you account by email. When you click the register, the page doesn't load for a couple of minutes and then it eventually gives you the notification that the verification sent but it doesn't send to your email address. Also before I set up the self signed SSL it did work, I believe it's because SSL doesn't see my register.php forum as secure therefor it doesn't send it because it's uncrypted, if there is a bypass or a way to fix this it would be greatly appreciated.
<?php
define('DIRECT', TRUE);
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
/* Registration process, inserts user info into the database
and sends account confirmation email message
*/
// Set session variables to be used on activate.php page
$_SESSION['email'] = $_POST['email'];
$_SESSION['username'] = $_POST['firstname'];
// Escape all $_POST variables to protect against SQL injections
$username = $mysqli->escape_string($_POST['firstname']);
$ip=$_SERVER['REMOTE_ADDR'] = getRealIpAddr();
$dateTime = date('Y/m/d G:i:s');
$email = $mysqli->escape_string($_POST['email']);
$uncryptpass = $mysqli->escape_string($_POST['password']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$hash = $mysqli->escape_string( md5( rand(0,1000) ) );
// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM users WHERE email='$email'") or die($mysqli->error());
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'An account with ' .$email. ' already exists!';
header("location: /login/index.php");
}
else { // Email doesn't already exist in a database, proceed...
// active is 0 by DEFAULT (no need to include it here)
$sql = "INSERT INTO users (username, email, uncryptpass, password, hash, ip, date) "
. "VALUES ('$username','$email','$uncryptpass','$password', '$hash', '$ip', '$dateTime')";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['active'] = 0; //0 until user activates their account with verify.php
$_SESSION['logged_in'] = true; // So we know the user has logged in
$_SESSION['message'] =
"Confirmation link has been sent to $email, please verify
your account by clicking on the link in the message!";
// Send registration confirmation link (verify.php)
$to = $email;
$subject = 'Account Verification';
$message_body = '
'.$username.',
***DO NOT RESPOND BACK TO THIS EMAIL***
https://example.com/login/verify.php?email='.$email.'&hash='.$hash;
mail( $to, $subject, $message_body );
header("location: activate.php");
}
else {
$_SESSION['message'] = 'Registration failed!';
header("location: /login/index.php");
}
}
This question already has answers here:
Fatal error: Call to undefined method mysqli::error() [duplicate]
(2 answers)
Closed 5 years ago.
I am trying to do a simple connection with XAMPP and sql server. but when ever I try to enter data or connect to the database, I get this error.what is the error? I badly need it for my project. I don't know why php line 9 is error.
Fatal error: Uncaught Error: Call to undefined method mysqli::error() in C:\xampp\htdocs\last1\new\register.php:19
<?php
/* Registration process, inserts user info into the database
and sends account confirmation email message
*/
// Set session variables to be used on profile.php page
$_SESSION['email'] = $_POST['email'];
$_SESSION['first_name'] = $_POST['firstname'];
$_SESSION['last_name'] = $_POST['lastname'];
// Escape all $_POST variables to protect against SQL injections
$first_name = $mysqli->escape_string($_POST['firstname']);
$last_name = $mysqli->escape_string($_POST['lastname']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$hash = $mysqli->escape_string( md5( rand(0,1000) ) );
// Check if user with that email already exists
**$result = $mysqli->query("SELECT * FROM users WHERE email='$email'") or die($mysqli->error());**
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'User with this email already exists!';
header("location: error.php");
}
else { // Email doesn't already exist in a database, proceed...
// active is 0 by DEFAULT (no need to include it here)
$sql = "INSERT INTO users (first_name, last_name, email, password, hash) "
. "VALUES ('$first_name','$last_name','$email','$password', '$hash')";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['active'] = 0; //0 until user activates their account with verify.php
$_SESSION['logged_in'] = true; // So we know the user has logged in
$_SESSION['message'] =
"Confirmation link has been sent to $email, please verify
your account by clicking on the link in the message!";
// Send registration confirmation link (verify.php)
$to = $email;
$subject = 'Account Verification ( clevertechie.com )';
$message_body = '
Hello '.$first_name.',
Thank you for signing up!
Please click this link to activate your account:
http://localhost/login-system/verify.php?email='.$email.'&hash='.$hash;
mail( $to, $subject, $message_body );
header("location: profile.php");
}
else {
$_SESSION['message'] = 'Registration failed!';
header("location: error.php");
}
}
Please help me :( Thank you guys ;*
$mysqli->error() should be $mysqli->error because error is a property, not a method.
It should be
$mysqli->error
and not $mysqli->error()
I think you should use $mysqli->error instead of $mysqli->error()
Source: http://php.net/manual/en/mysqli.error.php
I've been stuck trying to block access to an admin page using PHP. The PHP is below but I can't figure out which combination of statement I need to use for the permission to be selected.
When I dump my session it's always null but the email session is there. It's a simple login requiring email and password. I basically want it to also get their permission from the DB.
<?php
session_start();
include ('../config/config.php');
/* basic field validation */
$email = trim($_POST["email"]);
$password = trim ($_POST["password"]);
/* check if details are empty, redirect if they are */
if (empty($email) or empty($password)) {
$_SESSION["message"] = "You must enter your email and password";
//Redirect to index
header("Location: ../index.php");
exit;
}
/* sanitise the input */
$email = strip_tags($email);
$password = strip_tags($password);
/* SQL user selection query, with error handling for the SQL */
$query = "SELECT email, permission FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($mysqli,$query) or exit("Error in query: $query. " . mysqli_error());
/* on query success, set sessions for email and userid */
if ($row = mysqli_fetch_assoc($result)) {
$_SESSION["authemail"] = $email;
$_SESSION["permission"] = $permission;
/* redirect the user to the secured page */
header("Location: ../loggedin.php");
} else {
/* display error if login was not successful and redirect to index */
$_SESSION["message"] = "Could not log in as $email - $query";
header("index.php");
}
?>
Feel free to edit some of the text out if it isn't relavent.
I'd like to create an includes file which sends an email to user when he logs in. This is how my users get authenticated:
1- my authenticate include file chooses users password in the database based on the user email the login.php passes.
2- if the user is authenticated i just create 2 session variables user_id and user_name
So what I'd like to do is, once the user is authenticated I would like to call my send_login_email function within my email_function include file.
I'm also planning to create more email functions whereby I send an email to user for other notifications, so it's important for the user_email to be saved in a session variable.
This is what my send email includes file lookslike at the moment:
<?php
require_once('../includes/authenticate.inc.php');
function login_mail($_SESSION['uemail'])
{
$to = $_SESSION['uemail'];
$subject = "login";
$message = <?php $user_name ?>, You have logged in.";
$from = "example#email.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
}
?>
In my authenticate file I select user details as shown below:
$sql = 'SELECT salt, user_password, user_role, user_name, person_id FROM users WHERE user_email = ?';
$stmt = $conn->stmt_init();
$stmt->prepare($sql);
// bind the input parameter
$stmt->bind_param('s', $user_email);
// bind the result, using a new variable for the password
$stmt->bind_result($salt, $storedPwd, $user_role, $user_name, $person_id);
$stmt->execute();
$stmt->fetch();
and within the if statement that checks if the password is correct i have the following code-I'm also calling the email function here:
$_SESSION['start'] = time();
session_regenerate_id();
header("Location: $redirect");
// get the user's name and id
$_SESSION['name'] = $user_name;
$_SESSION['id'] = $person_id;
$_SESSION['uemail'] = $user_email;
require_once('../includes/email_func.inc.php'); //new stuff
login_mail($_SESSION['uemail']);
When I login sucessfully I do not receive an email.
I'm new to using functions and emails within php and Id really appreciate some help please.
Thank you
Change the function as follows:
function login_mail($to, $user_name)
{
$subject = "login";
$message = "$user_name, You have logged in.";
$from = "example#email.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
}
Then call it as:
login_mail($_SESSION['uemail'], $user_name);
The arguments of a function must be ordinary variables, not array elements. You were trying to reference $user_name, which didn't exist in the function. And <?php ...?> is not used in ordinary assignments, it's used when switching from HTML output to PHP code.
Make sure you have error reporting enabled, you should have gotten errors from those mistakes.