Hello guys i have a sight i have built in xampp it works well that is it can log in to the dashboard without hustle and create session and the user can afterwards log out. but after I launched the site the user cannot log it the site is just not responding. the log in screen is on i tried changing the script and all i get is just a white page, if i put the right script it redirects to the same login page. my host uses linux cpanel and thats the terminal i am using. mind you the site works fine connects well to the db and it even pulls the users available in the db but they issue is in the back end. here is the code i am using..
<?php
/* Main page with two forms: sign up and log in */
require '../config/config.php';
session_start();
?>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['login'])) { //user logging in
require '../sessions/login.php';
}
elseif (isset($_POST['register'])) { //user registering
require '../sessions/register.php';
}
}
?>
<?php
// Check if form submitted with method="post"
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
if (isset($_POST['reset'])) {
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM staff WHERE email='$email'");
if ( $result->num_rows == 0 ) // User doesn't exist
{
header("location: index.php?msg=".urlencode("User with this email does not exist!"));
}
else { // User exists (num_rows != 0)
$user = $result->fetch_assoc(); // $user becomes array with user data
$email = $user['email'];
$hash = $user['hash'];
$first_name = $user['first_name'];
// Send registration confirmation link (reset.php)
$to = $email;
$subject = 'Password Reset Link (site )';
$message_body = '
Hello '.$first_name.',
You have requested password reset!
Please click this link to reset your password:
http://sitename/reset.php?email='.$email.'&hash='.$hash;
mail($to, $subject, $message_body);
header("location: reset.php?msg=".urlencode("<p>Please check your email <span>$email</span>"
. " for a confirmation link to complete your password reset!</p>"));
}
}
}
?>
this is the login script
// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM staff WHERE email='$email'");
if ( $result->num_rows == 0 ){ // User doesn't exist
header("location: index.php?msg=".urlencode("User with that email doesn't exist!"));
}
else { // User exists
$user = $result->fetch_assoc();
if ( password_verify($_POST['password'], $user['password']) ) {
$_SESSION['email'] = $user['email'];
$_SESSION['f_name'] = $user['f_name'];
$_SESSION['l_name'] = $user['l_name'];
$_SESSION['image'] = $user['image'];
$_SESSION['id'] = $user['id'];
$_SESSION['active'] = $user['active'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
header("location: home.php");
}
else {
header("location: ../index.php?msg=".urlencode('You have entered wrong password, try again!'));
}
}
?>
If anyone have a clue ?
White Screen Of Death:
If you're seeing a blank page (and view-source is empty), make sure your php.ini contains error_reporting = -1 and display_errors = On (only recommended for development). Putting: at the top of your script might have no effect if your script fails to compile such as in the case of PARSE errors.
Your error will now appear on the page. However, that's not great for a live production system.
For the best error logging experience, set error_reporting to -1, turn display_errors off, and set a custom error_log. Then in the terminal, type tail -f /path/to/error_log. Your notices, warnings and errors will now scroll past in real time, without distorting your web page's display.
Related
I have this form programmed to log a user in. I have confirmed that it does in fact set a session for a user, but for some reason, it forwards the user to the page to connect to the database. I have this page linked in the code because I obviously need to consult the database to confirm the user has an account, but I don't understand why it goes to this page and then just stays there. Help would be appreciated. Index2.php (set as that right now so users won't see it when they go to the site) is supposed to be set as the redirected page after login. The user is supposed to be able to see the homepage even without logging in, but certain content only appears in the user is logged in.
<?php
session_start();
include("db_connect.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//something was posted
$email = $_POST['email'];
$password = $_POST['password'];
if(!empty($email) && !empty($password))
{
//read from database
$query = "select * from users_listers where email = '$email' limit 1";
$result = mysqli_query($conn, $query);
if($result)
{
if($result && mysqli_num_rows($result) > 0)
{
$user_data = mysqli_fetch_assoc($result);
if($user_data['password'] === $password)
{
$_SESSION['user_lister_id'];
header("Location: ../index2.php");
die;
}
}
}
echo "wrong username or password!";
}else
{
echo "wrong username or password!";
}
}
?>
Thank you for the help!
I'm so close to completing the login/registration section of my site but I've got some bugs that don't show up in error_log or anything.
About an hour ago, the script worked for the most part. It would validate, insert into/check database, and redirect to index.php (located in user directory along with login and register forms).
Contents of index.php:
/*
If validation script is successful, continue to $destinationUrl, otherwise, go back to try
again. Ultimately, the TRUE statement's output will be the referring page's URL stored as
$_SESSION['Return_Url'] to send users back to where they were, simply as a convenience.
*/
session_start();
if(isset($_SESSION['UserData'])) {
exit(header("location:" . $destinationUrl));
} else {
exit(header("location:" . $loginUrl));
}
That's exactly what I want except one detail: it won't show any user input errors. While trying to fix that, I've managed to screw everything up again and now it still submits data and inserts into the database but doesn't insert $email, and doesn't redirect or anything. On top of that, I don't get any PHP errors so I'm at a loss.
I know the login and registration will work because it did before, but I don't know what I did to cause this issue due to know errors being thrown. I just want the input errors to show up. I'm going to post the original code I copied and edited because what I'm messing with right now is a mess but the validation section is the same.
I did not write these, they were found online after hours of trying script after script. Only this one worked. Therefore, I don't understand exactly what's going on with every part of the script, but I do understand the basic mechanics of what happens, or is supposed to happen as far as validation of input data and adding to/checking data against the database when the form is submitted. The only thing that I have absolutely no idea what and how it works is the output($var) function
Included Scripts
$db= mysqli_connect($dbhost,$dbuser,$dbpwd,$dbase); }
function safe_input($db, $data) {
return htmlspecialchars(mysqli_real_escape_string($db, trim($data)));
}
/*
Currently, I have no idea about JSON or any other languages. Only a decent
portion of PHP, and HTML, of course. Can I just forget this function and use
{return $var;} instead? Because that would make everything so much easier
and I probably wouldn't even be posting these questions... but it's a new
language to me that I couldn't tell you the first thing about.
*/
function output($Return=array()){
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
exit(json_encode($Return));
}
Validation Scripts
(Both scripts are in one file)
<?
require 'config.php';
require 'functions.php';
if(!empty($_POST) && $_POST['Action']=='login_form'){
$Return = array('result'=>array(), 'error'=>'');
$email = safe_input($db, $_POST['Email']);
$password = safe_input($db, $_POST['Password']);
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$Return['error'] = "Please enter a valid email address.";
}elseif($password===''){
$Return['error'] = "Please enter password.";
}
if($Return['error']!=''){
output($Return);
}
$result = mysqli_query($db, "SELECT * FROM tbl WHERE email='$email' AND password='".md5($password)."' LIMIT 1");
if(mysqli_num_rows($result)==1){
$row = mysqli_fetch_assoc($result);
$Return['result'] = $_SESSION['UserData'] = array('id'=>$row['id']);
} else {
$Return['error'] = 'Invalid Login Credential.';
}
output($Return);
}
if(!empty($_POST) && $_POST['Action']=='registration_form'){
$Return = array('result'=>array(), 'error'=>'');
$name = safe_input($db, $_POST['Name']);
$email = safe_input($db, $_POST['Email']);
$password = safe_input($db, $_POST['Password']);
if($name===''){
$Return['error'] = "Please enter Full name.";
}elseif (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$Return['error'] = "Please enter a valid Email address.";
}elseif($password===''){
$Return['error'] = "Please enter Password.";
}
if($Return['error']!=''){
output($Return);
}
$result = mysqli_query($db, "SELECT * FROM tbl WHERE email='$email' LIMIT 1");
if(mysqli_num_rows($result)==1){
$Return['error'] = 'The email you entered already belongs to an account, please login.';
}else{
mysqli_query($db, "INSERT INTO tbl (GUID, email, password, entry_date) values(MD5(UUID()), '$email', '".md5($password)."' ,NOW() )");
$id = mysqli_insert_id($db);
mysqli_query($db, "INSERT INTO `tbl' (id,name) VALUES('$id','$name')");
$Return['result'] = $_SESSION['UserData'] = array('id'=>$id);
}
output($Return);
}
?>
I'm not sure how I would echo the $Return array values. I tried making a function out of it like so:
function inputErr($Return) {
if($Return['error']!=''){
output($Return);
}
}
but that didn't work either. Is there a special way to echo an array value? Without the index name attached
Also, if you have any ideas why the email $var is not being added to db while everything else is, please, do share! With the script not throwing any PHP errors, I have no idea where to start.
I am trying to display the error at the end if the use doesn't enter the correct combination of their log in. However, the error message is not showing when I enter the wrong password or email. Any suggestions
<?php
include ("connect.php");
if (isset($_POST["user_login"]) && (isset($_POST["user_pass"]))){
// formatting field via reg replace to ensure email and password only conisists of letters and numbers preg_replace('#[^A-Za-z0-9]#i','',
$login_user = $_POST["user_login"];
$login_password = $_POST["user_pass"];
// password is encryted in DB (MD5) therefore user inputted password will not match encryted password in DB - we have to assign new var
$decrypted_password = md5($login_password);
// Query which finds user (if valid) from DB - Achieving authentication via username and password
$user_query = mysqli_query($connect, "SELECT * FROM users WHERE email = '$login_user' AND password = '$decrypted_password' AND closed = 'no' LIMIT 1");
$check_user = mysqli_num_rows($user_query); // checking to see if there is infact a user which those credentials in the DB
if ($check_user==1){
while ($row = mysqli_fetch_array($user_query)){
$id = $row['user_id'];
$user_type = $row['account'];
}
$_SESSION["user_login"] = $login_user;
// check the user type and redirect according to it
if($user_type == "Student"){
$student_page = "profile_student.php";
header( "Location:{$student_page}" );
} elseif ($user_type == "Landlord"){
$landlord_page = "landlord_profile.php";
header( "Location:{$landlord_page}" );
} elseif ($user_type == "Administrator"){
$admin_page = "admin_profile.php";
header( "Location:{$admin_page}" );
}else {
$refresh_page = "sign_up.php";
header( "Location:{$refresh_page}" ); // refresh page
echo "You have entered an incorrect email or password. Please try again.";
}
}
}
?>
you redirect user if input data is wrong and only after that you try to echo message, thats not how that works. read about headers in php_manual. probably the best way here, is to store error message in session and after redirect check if session error message exists
else {
$refresh_page = "sign_up.php";
$_SESSION['error'] = "your error message"
header( "Location:{$refresh_page}" ); // refresh page
}
in sign_up.php file check if error message exists in session
if(isset($_SESSION["error"])){
echo $_SESSION["error"];
unset($_SESSION["error"]);
}
maybe you should correct this code a little bit))
use unset cause' after you show the message it should be removed from session, in other case if you fail for example 5 times, it will show 5 messages)) also make sure that session is started session_start() hope it helps:)
You only display the error when $user_type doesn't match any of your expected types.
You need a second else after your if ($check_user==1){ block to handle the case where a user with that email or password doesn't exist.
I've finally got the courage to make a user login system after who knows how long of putting it off. My only problem is that when I submit the login form it reloads the page and it says that I am logged in, great.
However if I reload the page or go to another page and come back to the original page it forces me to login again. Can anyone help with this? I have a session_start() in the base file that is included in all other page files before the database connection.
I then have the following code for my user login side of things, which as I said, works the first time around, but after that any other interaction will essentially log me out. Any help with this?
The user page which logs you in and creates the session...
Please note that this isn't a live environment so security is being put on the bench for now. However I am aware I will need some security measures in place in the future though.
// Check if the user is logged in or not
if((!empty($_SESSION['loggedin'])) && (!empty($_SESSION['username']))) {
$loggedin = true; // The user IS logged in
} else {
if(isset($_POST['login'])) {
// The login form has been submitted
if((empty($_POST['username'])) || (empty($_POST['password']))) {
// If either username or password fields are blank
$loginfail = true; // If the user could not be logged in
if(empty($_POST['username'])) { $nousername = true; }
if(empty($_POST['password'])) { $nopassword = true; }
} else {
// Username and password field were filled in okay
$username = $_POST['username'];
$password = $_POST['password'];
$checklogin = mysqli_query($sql, "SELECT * FROM users WHERE username = '$username' AND password = '$password'") or die($checklogin . "<br/>" . mysqli_error($sql));
if(mysqli_num_rows($checklogin) == 1) {
// If the login details match up, log them in
$loggedin = true; // The user IS NOT logged in
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = 1;
} else {
// If the login details don't match up, don't login
$loginfail = true; // If the user could not be logged in
}
}
}
}
Thanks!
I have a slight problem with my log in script in PHP. When a user logs in, it only works after the second try, there is no error but it just looks like the user entered the wrong password on the first attempt.
Sometimes when I've been testing the site, after i try log in in the first time it sends me back to the log in page. Then I manually enter the url of the home page it will let me go there sometimes. (There's some php at the top that checks if the user is logged in already so im guessing sometimes the log in script sets the SESSION to true)
Majority of the time it doesn't do that though. It will just redirect me back to the log in with out printing the error message. I believe the problem is at the top of the home page and not with the log in script because after removing the redirect if mysql doesn't return a row with a user/password match it will direct me to the log in page anyways.
Here is my login script
<?php
session_start();
// Include required MySQL configuration file and functions
// Check if user is already logged in
if (isset($_SESSION['logged_in'])) {
// If user is already logged in, redirect to main page
redirect('home.php');
}
else {
// Make sure that the user submitted a username/password and username
// only consists of alphanumeric Chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
( !ctype_alnum($_POST['username'])) ) {
redirect('login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno()) { printf ("Unable to connect to database %s",
mysqli_connect_error());
exit();
}
//Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// construct SQL statement for query & execute
$sql = "SELECT * FROM peeps WHERE name = '" . $username . "'
AND pword = SHA1('" . $password . "') ";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid.
if ($result->num_rows == 1 ) {
// Set the session variable for login status to true
$_SESSION['logged_in'] = true;
$_SESSION['name'] = $username;
echo "successfull ";
redirect('home.php');
}
else {
echo "didnt return row<hr>";
redirect back to login page.
redirect('loginPage.php');
}
}
?>
And here is the code at the top of my home page..
<?php
// Start session
session_start();
// Include required functions file
require_once('functions.php');
// Check login status... if not logged in redirect to login screen
if (check_login_status() == false) {
redirect('loginPage.php');
}
$username = $_SESSION['name'];
?>
Any help would be appreciated, if you want to a little more clarification on what I mean you can sign up for gateKeeper and see what I'm talking about.
Also this is my first question so any comments on how I asked it would be appreciated.
Thanks!
Try debugging it by replacing
if (check_login_status() == false) {
redirect('loginPage.php');
}
with
if (!isset($_SESSION['name'])) { #could be any session variables that you like..
redirect('loginPage.php');
}
or do print_r($_SESSION) on top of your homepage.
I assume that the first page is the script that processes the form from loginPage.php (or loginPage.php itself) and the second one the page that you access after being authenticated.
If I'm not mistaken, the problem seems to be that sometimes you are not correctly identified and that's redirecting you to your login again. Can you show us how the code for the check_login_status() function?