For some apparent reason, a portion of my PHP code is being shown in the header section of my page.
I am completely stumped as to why this is occurring. I have rechecked all the variables and have tested how to page renders on IE and Firefox, but the same problem occurs.
reg.php:
<?
$registration = #$_POST[`submitReg`];
// Getting all other info from form and assigning it to variables
$firstname = strip_tags(#$_POST[`fname`]);
$lastname = strip_tags(#$_POST[`lname`]);
$username = strip_tags(#$_POST[`username`]);
$email = strip_tags(#$_POST[`email`]);
$email2 = strip_tags(#$_POST[`email2`]);
$password = strip_tags(#$_POST[`password`]);
$password2 = strip_tags(#$_POST[`password2`]);
$DOBDay = strip_tags(#$_POST[`DOBDay`]);
$DOBMonth = strip_tags(#$_POST[`DOBMonth`]);
$DOBYear = strip_tags(#$_POST[`DOBYear`]);
$gender = strip_tags(#$_POST[`gender`]);
$sign_up_date = date("d-m-Y"); // Sign up date is not getting any data from the form
if ($registration) {
if ($email==$email2) {
// If both emails match, then check if user already exists:
$u_check = mysqli_query("SELECT username FROM users WHERE username='$username'"); // Count the amount of rows where username = $username
$e_check = mysqli_query("SELECT email FROM users WHERE email='$email'"); //Check whether Email already exists in the database
// checking the amount of rows where username is equal to $username - avoid two users with same username - same idea for email
$check = mysqli_num_rows($u_check);
$email_check = mysqli_num_rows($e_check);
if ($check == 0) {
if ($email_check == 0) {
// If no matches found then: 1. check all fields are completed correctly:
if ($firstname && $lastname && $username && $email && $email2 && $password && $password2 && $DOBDay && $DOBMonth && $DOBYear && $gender) {
// 1.2. check that passwords match:
if ($password==$password2) {
-------------------- CODE WHICH IS APPEARING IN THE HEADER ---------------------
// 1.2.1. Check fields are of valid length
if (strlen($username) > 25 || strlen($firstname) > 25 || strlen($lastname) > 25 || strlen($password) > 25) {
echo "The maximum character limit is 25.";
}
else
{
// check the maximum length of password does not exceed 25 characters and is not less than 6 characters
if (strlen($password)>25||strlen($password)<6) {
echo "Your password must be between 6 and 25 characters long!";
}
else
{
// if everything correct, encrypt passwords using MD5 before sending it to server.
$password = md5($password);
$password2 = md5($password2);
$query = mysqli_query("INSERT INTO users VALUES (``, `$firstname`, `$lastname`, `$username`, `$email`, `$password`, `$sign_up_date`)");
die("<h2>Welcome to Aston Unified</h2> Login to your account to get started ...");
}
}
}
else {
echo "Your passwords don't match!";
}
}
else
{
echo "Please fill in all of the fields";
}
}
else
{
echo "Sorry, but it looks like someone has already used that email!";
}
}
else
{
echo "Username already taken ...";
}
}
else {
echo "Your E-mails don't match!";
}
}
_______________________________________________________________________
?>
Any ideas as to why this behavior is occurring?
Seems php short tags <? is off and you have used that. Try to use <?php and then check.
If you need to use that then set
short_open_tag=On
in php.ini and restart your Apache server.
you should enable short tag in php.ini (add short_open_tag=On in your php.ini) or use <?php in place of <?
Related
The following code should be straight forward and simple, the insert into the db on signup creates a hash, but later when I try to login with the same password the hash it is creating isn't matching up to what is in the database (I had print_r's throughout to verify). Can someone see if I'm just overlooking something dumb?
session_start();
require_once("login.php");
$error = "";
$email = "";
$password = "";
if (isset($_GET['logout'])) {
unset($_SESSION['id']);
setcookie('id', '', time() - 60*60);
$_COOKIE['id'] = "";
} else {
if (isset($_SESSION['id']) or isset($_COOKIE['id'])) {
header("Location: loggedinpage.php");
}
}
if (isset($_POST["submit"])) {
$link = mysqli_connect($hn, $un,$pw,$db);
if($link->connect_error) die("Fatal Errror.");
if (!$_POST["email"]) {
$error .="An email address is required<br>";
}
if (!$_POST["password"]) {
$error .="A password address is required<br>";
}
if ($error != "") {
$error= "<p>There were error(s) in your form:</p>".$error;
} else {
if ($_POST['signup'] == 1) {
$email = mysqli_real_escape_string($link, $_POST['email']);
$password = mysqli_real_escape_string($link,$_POST['password']);
$query = "SELECT id FROM `users` WHERE email = '".$email."' LIMIT 1";
$result=$link->query($query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is taken.";
} else {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO `users`(`email`,`password`) VALUES ('".$email."', '".$hashedPassword."')";
if (!mysqli_query($link,$query)) {
$error = "<p>Could not sign you up, please try again later</p>";
} else {
$_SESSION['id'] = mysqli_insert_id($link);
if(isset($_POST['stayLoggedIn']) and $_POST['stayLoggedIn'] == 1) {
setcookie('id', mysqli_insert_id($link), time()+60*60*24);
}
header("Location: loggedinpage.php");
}
}
} else {
$email = mysqli_real_escape_string($link, $_POST['email']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$hashedPassword = password_hash($password,PASSWORD_DEFAULT);
$query = "SELECT * FROM users WHERE email = '".$email."' LIMIT 1";
$result = $link->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if ($email == $row['email'] and password_verify($password,$row['password'])) {
if (isset($_POST['stayLoggedIn']) and $_POST['stayLoggedIn'] == 1) {
setcookie('id', $row['id'], time()+60*60*24);
header("Location: loggedinpage.php");
}
} else {
$error = "Incorrect Username/Password combination";
}
}
}
}
}
Although it's tucked away at the end of a paragraph, PHP documentation does say that "it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice)."
The current default algorithm, bcrypt, generates hashes that are 60 characters long. If your database column cannot hold at least this many characters, your hashes will be truncated and verification will fail.
You've got a few other problems as well:
You're modifying the password before generating the hash (with mysqli_real_escape_string())
You're not using prepared statements
You appear to be relying on cookies for authentication. Cookies are user-generated data, they are not to be trusted! This is why PHP provides session support, because the data is stored on the server.
You should not be checking for an existing email address using a query, instead you should have a unique index set on the email column in the database.
try
if(password_verify($password, (string)$row->password)){
//Your Code
}
because of password_verify function return Boolean only true or false
And
$hashedPassword = password_hash($password,PASSWORD_DEFAULT);
Only add once when you Insert to Sql (new user)
I'm trying to make a login system (already have registration system complete) with password_hash() and password_verify() but it isn't working for me. I've been trying to find an answer this whole morning and yet can't seem to make it work, I've watched codecourse tutorials, read blog posts and nothing. The tutorial I've been following the most is this one.
<!-- login -->
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$errors = array();
error_reporting(E_ALL);
ini_set('display_errors', 1);
//Basic validation
if(empty($_POST['username'])){
$errors[] = "Please enter your username";
}else{
$username = $mysqli->real_escape_string($_POST['username']);
}
if(empty($_POST['password'])){
$errors[] = "Please enter your password";
}else{
$password = trim($_POST['password']);
}
if (empty($errors)) {
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $mysqli->query($sql);
if ($result->num_rows === 1) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if(password_verify($password, $row['password'])) {
echo 'test';
$_SESSION['user']['user_id'] = $row['user'];
header("Location: google.com");
exit();
}else{
$errors[] = "The username or password do not match";
}
}else{
$errors[] = "The username or password do not match";
}
}
}
?>
<!-- register -->
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = $_POST['password'];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$confirm_password = mysqli_real_escape_string($conn, $password);
$ip = $_SERVER['REMOTE_ADDR'];
if(empty($username) || empty($password) || empty($confirm_password)) {
$error = "Fill in the missing fields";
} else {
$sql = "INSERT INTO users VALUES('', '$username', '$hashed_password', '$ip', 'User')";
if($conn->query($sql) === TRUE) {
$error = "Your account has been created.";
} else {
$error = "Your account has not been created, please try again later.";
}
}
}
?>
The end result product is supposed to login in successfully and redirect, I'm using PHP 5.6 and running on localhost XAMPP.
You'll never get a match because you're using
$password =mysqli_real_escape_string($conn, $_POST['password']);
to store the password and then not using it on verification. Instead you use
$password = trim($_POST['password']);
Make sure you don't escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding. The password_hash() function can generate some very lengthy text (the current default is 60 characters), so make sure the field in your database is large enough to accommodate the hash. Setting the field larger now will allow for the length needed. The PHP team is adding more algorithms to the method which means the hash can and will grow.
I'm having some problems with this login script, I've already had someone else look it over for me and we cannot seem to figure out what the issue is.
What's happening is when a user tries to login, if the the username is correct it will check if the password is correct and if the password is correct it updates the last access date and redirects like it is supposed to. However if the username is correct and the password is incorrect. It should empty out the password, and let the user know the password they entered is incorrect.
What actually happens when the password is incorrect, is it is skipping to the outermost else statement, and emptying out the username and password and saying there is an issue...whether or not the username entered is correct (regardless of whether or not the password is right).
I have no idea what is happening here, and hopefully someone can help me shed some light on it.
Thank you!
$selectUser = pg_prepare($dbConnection, "selectuser_query", 'SELECT * FROM users WHERE user_id = $1 AND password = $2');
<?php
$error = "";
$username_error = "";
$password_error = "";
if($_SERVER["REQUEST_METHOD"] == "GET")
{
$login = "";
$password = "";
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
$login = trim($_POST["login"]);
$password = trim($_POST["password"]);
if(!isset($login) || $login == "")
{
$username_error = "You must enter your user name to login!";
}
if (!isset($password) || $password == "")
{
$password_error = "You must enter your password to login!";
}
if(($error == "") && ($password_error == "") && ($username_error == ""))
{
$selectUser = pg_execute($dbConnection, "selectuser_query", array("$login", "$password"));
if($login == pg_fetch_result($selectUser, "user_id"))
{
if($password == pg_fetch_result($selectUser, "password"))
{
$date = date("n-j-Y");
$updateDateAccess = pg_execute($dbConnection, "updatedate_query", array("'$date'", "$login"));
header('Location: ./welcome.php');
}
else
{
$password = "";
$error = "The password is incorrect. Please try again.";
}
}
else
{
$login = "";
$password = "";
$error = "The username/password is incorrect. Please try again.";
}
}
}
?>
Your problem is your query:
SELECT * FROM users WHERE user_id = $1 AND password = $2
It checks both the username and password, which results in no records being returned if the password is incorrect. Thus, the next if condition isn't satisfied:
$selectUser = pg_execute($dbConnection, "selectuser_query", array("$login", "$password")); // no records
if($login == pg_fetch_result($selectUser, "user_id")) // not satisfied, because there are no records
{
// ...
}
else // this runs
{
$login = "";
$password = "";
$error = "The username/password is incorrect. Please try again.";
}
What you want to do is run a query that retrieves the (salted and hashed) password for a given username, then check the password in your application logic.
Also, as others have pointed out in the comments, this is not a good way to store passwords or respond to incorrect info. It looks like the passwords are in plain text, but they should be hashed and salted. Also, you should not tell the user which part of the information was incorrect; otherwise, you let an attacker determine valid usernames and then focus on brute-forcing those.
if(!empty($username) && !empty($email) && !empty($password) && !empty($confirm_password)){
$username = htmlentities($username);
$username = stripslashes($username);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$username = preg_replace("[^A-Za-z0-9]", "", $username);
$email = htmlentities($email);
$email = stripslashes($email);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$email = preg_replace("[^A-Za-z0-9]", "", $email);
if(strstr($email, "#") && strstr($email, ".")) {
require("$baseURL/scripts/connect.php");
$checkemail = mysql_query("SELECT * FROM users WHERE email='$email'") or die(mysql_error());
$numrows_checkemail = mysql_num_rows($checkemail);
if($numrows_checkemail > 0) {
require("$baseURL/scripts/connect.php");
$checkusername = mysql_query("SELECT * FROM users WHERE username='$username'") or die(mysql_error());
$numrows_checkusername = mysql_num_rows($checkusername);
if($numrows_checkusername > 0) {
if($password == $confirm_password) {
$hashpass = md5(md5($password));
//All set to insert into the db
require("$baseURL/scripts/connect.php");
mysql_query("INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$hashpass')") or die(mysql_error());
$this->noticeMsg = "You have been signed up successfully!";
} else {
$this->errorMsg = "Uh-oh, looks like your passwords do not match!";
}
} else {
$this->errorMsg = "Oops, looks like that username is already in use! Please pick a different username.";
}
} else {
$this->errorMsg = "That email is already in use, please sign up with another email.";
}
} else {
$this->errorMsg = "Please enter a valid email address!";
}
} else {
$this->errorMsg = "Please fill in all the fields!";
}
The error I keep getting is "That email is already in use, please sign up with another email." even though the right file is being "required" and is connected to the database properly. The problem is most likely at the $numrows_checkemail part because when I use if($numrows_checkemail == 0) it works just fine. Why won't the ">" symbol work?
Am I doing something wrong?
Thank you
if($numrows_checkemail > 0) will return true only if $numrows_checkemail is bigger than 0.
You need to check for $numrows_checkemail == 0 or empty($numrows_checkemail)
The > is reversing your logic;
$numrows_checkemail > 0 is true if at least one user with that email already exists in the database (ie if there is more than zero rows in the database with that email)
$numrows_checkemail == 0 is true if no user with that email already exists in the database (ie if there isn't any row in the database with that email)
This script seems to get hung up when it hits the series of "if" statements checking the email and password length. If I remove these statements, it properly inserts the data into the db.
<?php
ob_start();
session_start();
if (!empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['confirmpassword'])) {
$email = strip_tags($_POST['email']);
$password = md5(strip_tags($_POST['password']));
$confirmpassword = md5(strip_tags($_POST['confirmpassword']));
$errors = array();
if (strlen($email) < 6) {
$errors[] = "Email too short.";
}
if (strlen($email) > 25) {
$errors[] = "Email too long.";
}
if (strlen($password) < 2) {
$errors[] = "Password too short.";
}
if (strlen($password) > 25) {
$errors[] = "Password too short.";
}
if ($password !== $confirmpassword) {
$errors[] = "Passwords do not match.";
}
if (count($errors) == 0) {
// Include database config file then connect to database
require('db_config.php');
$connection = mysql_connect(DB_HOST,DB_USERNAME,DB_PASSWORD) or die("Database Connection Error");
$database = mysql_select_db(DB_NAME) or die("No Database");
// Create query
$query = "INSERT INTO bah_register VALUES ('','$email','$password')";
// Query database and
mysql_query($query);
// Success message
echo "Thanks for signing up!";
} else {
foreach ($errors as $error) {
echo $error . "<br />";
}
}
}
?>
Your issue is that you are md5ing the password before you check the length. This puts the password at 32 characters, which is greater than your limit and producing an error.
You are checking strlen($password) > 25 and your password is md5 hashsum which is longer than 25 symbols. You probably wanted to check original value of password
i don't know what is wrong with your code, but for your email you might consider using something like this :
if(!preg_match('/^[^#]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $email)){
$errors[] = "Email is not valid.";
}
many emails are longer than 25 characters.
The foreach with the error array can easly be replaced with following code
echo implode('<br />', $errors);
Proper email validation can be done with the filter_var function
The strip_tags function can have undesired effects on the password, probably parts of it will be deleted. Think of the following password: «<my>super!password»