I have a PHP login page that works perfectly locally, but when in server always come out with "Invalid Username or Password". I tried it in two different servers and the result was the same.
login.php
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password']))
{
$error = "Username or Password is invalid";
}
else
{
// Define $username1 and $password1
$username1 = $_POST['username'];
$password1 = $_POST['password'];
include_once ('lib/db.php');
$connection = new mysqli($servername, $username, $password, $dbname);
$username1 = stripslashes($username1);
$password1 = stripslashes($password1);
$username1 = mysql_real_escape_string($username1);
$password1 = mysql_real_escape_string($password1);
// SQL query to fetch information of registerd users and finds user match.
$query = "select * from login where PASSWORD='$password1' AND USERNAME='$username1'";
$result = $connection->query($query);
$rows = mysqli_num_rows($result);
if ($rows == 1)
{
$_SESSION['user']=$username1; // Initializing Session
$_SESSION['pppv'] = 10;
header("Location: logged-in.php"); // Redirecting To Other Page
}
else
{
$error = "Username or Password is invalid";
}
}
}
EDIT
Try printing the query after submission gives me this:
Local:
select * from login where PASSWORD='test' AND USERNAME='test'
Server:
select * from login where PASSWORD='' AND USERNAME=''
Use isset($_POST['username']) ||isset($_POST['password'])instead of empty($_POST['username']) || empty($_POST['password']).
Read this to know the difference between isset and empty.
There's no context, but check these things:
Does your database contain the same credentials as local?
Does your requested page return http status such as 200? If it's 404, there's something wrong with your path's. If it's 500, there's an internal error (right permissions set?)
Did you check your log files?
Did you clear your browser cookies and history?
Did you print the full query (including filled parameters) to the window and did you execute this query in your database management tool? And did you get result?
Related
I am building a study planner that features just a single welcome area, after logging in. I am currently trying to obtain the user ID of the currently logged in user for use in an SQL update query in this welcome area, as well as the user’s first name for use in the welcome message.
I have tried putting $_SESSION['user_id'] = userid; and $_SESSION['user_firstname'] = firstname; after $_SESSION['login_user'] = $username; ($_SESSION['login_user'] = $username; works fine by the way) but upon logging into the page, I get these errors: Notice: Use of undefined constant userid - assumed 'userid' in C:\wamp64\www\justread\session.php on line 11 and Notice: Use of undefined constant firstname - assumed 'firstname' in C:\wamp64\www\justread\session.php on line 12.
Now, I know the errors want me to do some sort of initialisation for ‘userid’ and ‘firstname’ first before using them to set up a session variable but I am not sure how to go about it, so I am wondering if someone could help me, please.
Thanking you in advance.
I can post more codes if required but the codes I believe are concerned are:
login.php:
<?php
// Start session
session_start();
// Variable to store error message
$error ="";
// If the login form (Note that the 'submit' refers to the 'name' attribute of the login form) has been submitted...
if (isset($_POST['submit'])) {
// If username or password is not provided...
if (empty($_POST['username']) || empty($_POST['password'])) {
// ...tell user that login details are invalid.
$error = "Please fill in both your username and your password";
// Else...
} else {
// ...put the provided username and password in variables $username and $password, respectively
$username = $_POST['username'];
$password = $_POST['password'];
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// set up measures to counter potential MySQL injections
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($mysqli, $username);
$password = mysqli_real_escape_string($mysqli, $password);
// Select Database
$db = mysqli_select_db($mysqli, "p00702");
// SQL query to fetch information of registerd users and find user match.
$query = mysqli_query($mysqli, "SELECT * from logins WHERE password='$password' AND username='$username'");
// Return the number of rows of the query result and put it in $rows variable
$rows = mysqli_num_rows($query);
// If rows are equal to one...
if ($rows == 1) {
unset($_SESSION['error']);
// Initialize session with the username of the user...
$_SESSION['login_user'] = $username;
// Set the user ID of the user
$_SESSION['user_id'] = userid;
// Set the user first name of the user
$_SESSION['user_firstname'] = firstname;
// ...and redirect to the homepage.
header("Location: welcome.php");
// Make sure that codes below do not execut upon redirection.
exit;
// Else,
} else {
// and tell user that the login credentials are invalid.
$error = "Your username or password is invalid";
$_SESSION['error'] = $error;
// redirect user to the home page (index.php)
header("Location: index.php");
}
// ...and close connection
mysqli_close($mysqli);
}
}
session.php
<?php
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// Selecting Database
$db = mysqli_select_db($mysqli, "p00702");
// Starting session
session_start();
// Storing Session
$user_check = $_SESSION['login_user'];
$_SESSION['user_id'] = userid;
$_SESSION['user_firstname'] = firstname;
// Test to see the content of the global session variable
print_r($_SESSION);
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysqli_query($mysqli, "SELECT username FROM logins WHERE username='$user_check'");
$row = mysqli_fetch_assoc($ses_sql);
$login_session = $row['username'];
if (!isset($login_session)) {
// Closing Connection
mysqli_close($mysqli);
// Redirecting To Home Page
header('Location: index.php');
// Make sure that codes below do not execut upon redirection.
exit;
}
In PHP, variable name starts with '$' sign. Also, in login.php, you have to fetch the data using mysqli_fetch_row or any similar function. Am assuming you are redirecting to session.php after logging in. In that case, you don't have to assign anything to the session variables. It will be there already. All you have to do is to access it.
login.php
<?php
// Start session
session_start();
// Variable to store error message
$error ="";
// If the login form (Note that the 'submit' refers to the 'name' attribute of the login form) has been submitted...
if (isset($_POST['submit'])) {
// If username or password is not provided...
if (empty($_POST['username']) || empty($_POST['password'])) {
// ...tell user that login details are invalid.
$error = "Please fill in both your username and your password";
// Else...
} else {
// ...put the provided username and password in variables $username and $password, respectively
$username = $_POST['username'];
$password = $_POST['password'];
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// set up measures to counter potential MySQL injections
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($mysqli, $username);
$password = mysqli_real_escape_string($mysqli, $password);
// Select Database
$db = mysqli_select_db($mysqli, "p00702");
// SQL query to fetch information of registerd users and find user match.
$query = mysqli_query($mysqli, "SELECT * from logins WHERE password='$password' AND username='$username'");
// Return the number of rows of the query result and put it in $rows variable
$rows = mysqli_num_rows($query);
// If rows are equal to one...
if ($rows == 1) {
$row = mysql_fetch_object($query);
unset($_SESSION['error']);
// Initialize session with the username of the user...
$_SESSION['login_user'] = $username;
// Set the user ID of the user
$_SESSION['user_id'] = $row->userid;
// Set the user first name of the user
$_SESSION['user_firstname'] = $row->firstname;
// ...and redirect to the homepage.
header("Location: welcome.php");
// Make sure that codes below do not execut upon redirection.
exit;
// Else,
} else {
// and tell user that the login credentials are invalid.
$error = "Your username or password is invalid";
$_SESSION['error'] = $error;
// redirect user to the home page (index.php)
header("Location: index.php");
}
// ...and close connection
mysqli_close($mysqli);
}
}
session.php
<?php
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// Selecting Database
$db = mysqli_select_db($mysqli, "p00702");
// Starting session
session_start();
if (!isset($_SESSION['user_id'])) {
// Closing Connection
// Redirecting To Home Page
header('Location: index.php');
// Make sure that codes below do not execut upon redirection.
exit;
}
print_r($_SESSION);
Also, move the connection part to a seperate file and include it in all scripts, so that when your credentials change, you don't have to change it in all the files.
I am trying to use the below code to create a login form. The problem being after registration when I am trying to login, getting an error message "Username or Password don't match" even though email & password are correct. I tried "$num <=1" and allows me to log in but obviously it is not authenticating the login details in that case. Any help will be appreciated.Most importantly this code is working fine on a local server like XAMPP but problem starts when using a host server like hostgator (no issue to connect with the server).
<?php
session_start(); // Starting Session
#Database connection
include('../config/connection.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit']))
{
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = '<p class="alert alert-danger">One or either field is missing</p>';
}
else
{
// Define $username and $password
$email=$_POST['email'];
$password = $_POST['password'];
// To protect MySQL injection for Security purpose
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
// SQL query to fetch information of registerd users and finds user match.
$q = "SELECT * FROM users WHERE email = '$email' AND password = md5(SHA1('$password'))";
$r = mysqli_query($dbc, $q)or die(mysqli_error());
$num = mysqli_num_rows($r);
if($num ==1){
$_SESSION['username'] = $email;
header('Location:Index.php');
} else {
$error = '<p class="alert alert-danger">Username or Password don\'t match</p>';
}
mysqli_close($dbc); // Closing Connection
}
}
?>
in your query the $password should not be between the quotes, cause then it will seek for the string instead of the value of the variable.
$q = "SELECT * FROM users WHERE email = '$email' AND password = 'md5(SHA1($password))'";
make sure your password is hashed in your database
Please help me. I got this error everytime I tried to login. - "This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS"
Please help me and I'll appreciate your help very much. thanks.
This is my index.php
<?php
include('login.php'); // Includes Login Script
?>
This is my login.php
<?php
session_start();
$error = "";
if (isset($_POST['submit'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$usernameLogin = $_POST['email'];
$passwordLogin = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "apple", "Apple318992");
// To protect MySQL injection for Security purpose
$username = stripslashes($usernameLogin);
$password = stripslashes($passwordLogin);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("TS", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from Users where password='$password' AND email='$usernameLogin'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user'] = $usernameLogin; // Initializing Session
} else {
$error = "Username or Password is invalid";
}
}
}
if (isset($_SESSION["login_user"])) {
header("Location:timesheets.php");
}
?>
This is my session.php
<?php
include ('DBConnect.php');
session_start(); // Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysql_query("select email from Users where email='$user_check'", $conn);
$row = mysql_fetch_assoc($ses_sql);
$login_session = $row['email'];
if (!isset($login_session)) {
mysql_close($conn); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
instead of : header('Location: index.php');
try to do it with javascript :
echo '< script> document.location.href="index.php"< /script>';
In your session.php you have to destroy the session because it might be set still but without that the query can find a existing user?
To unset sessions do this:
unset(); for all the session variables unset($_SESSION['login_user']); for a specific session
Please put that before redirecting to index.php.
Otherwise I don't know how to help you sorry.
Also do you have php error / debug enabled? Normally session_start(); should be at very first line in your php file if I am correct, or it throws error.
I wrote custom login script for users to login to the main control page. I found out that even when users are not login they can still visit the main control of which I want someone to help me to write a restrict access to page().
Please look through my php login script and based on that code help me write the restrict access to the main control page. assume that my main crontrol page is: cecontrolpage.php
I know we use $_SESSION to that but I have little idea of it.
this is my login.php code which is working fine:
<?php
Session_start();
$Email = $_POST["email"];
$Password = $_POST["password"];
$cn = "localhost";
$db_username = "root";
$pas = "***";
$db_name = "cemembers";
//Open a connection to a MySQL Server
if ($Email && $Password) {
$connect = mysqli_connect($cn, $db_username, $pas, $db_name) or die("Could not connect to database");
//sending MySqli query
$query = mysqli_query($connect, "SELECT * FROM users WHERE Email= '$Email'");
$numrows = mysqli_num_rows($query);
//After PHP declaration we are going to create index file[form]
if ($numrows !== 0) {
while ($row = mysqli_fetch_array($query)) {
$dbEmail = $row["Email"];
$dbPassword = $row["Password"];
}
if ($Email == $dbEmail && $Password == $dbPassword) {
header("location:ce membership birthday system control_pannel.php");
#$_SESSION("Email") == $Email;
} else
header("location:index.php?login_attempt=1");
} else
header("location:index.php?login_attempt=2");
} else
header("Location:index.php?login_attempt=0");
?>
please can someone help me write the php code to restrict access to cecontrol.php ??
Please STEP by STEP with php comments on each part.
First you need to check if the user is logged in:
you do that by checking if the session has been set.
//Check if the user is logged in
function userlogged_in()
{
return(isset($_SESSION['userid']))?true:false;
}
Then you need to redirect the user to a page that says the access to is not authorised, they need to be logged in to view that page:
You do this by checking if the userlogged_in function returned a true or false
function user_restricted()
{
if (userlogged_in()=== false)
{
header('Location: permission.php ');
exit();
}
}
Then you need to call the user_restricted() function on each page, just after starting the session.
First you have to save user values in session after authentication from database like
$_SESSION['username'] = "name"; $_SESSION['user_id'] = 1;
function check_session() {
session_start();
if ($_SESSION['user_id']=='')
{
// redirect to login
}
}
On every page that you want to restrict access you can call check_session().
I'm trying to log in to my site, I'm looking at the database and the username/password are correct. When logging in I should be greeted by ja message that says "Welcome Ryemck" as "Ryemck" is my username, but this could be replaced by any username that is logged in. Here's the code to show that:
<td>Welcome </td>
<td><i><?php echo $username ['username']; ?></i></td>
However, instead of that nice message I get "Notice: Undefined variable: username ", I assume this is because the username isn't being set as the variable as it should in this code.
$username=$_POST['username'];
I also have this code that SHOULD give me the error if no username/password are entered, but it doesn't, so this doesn't work. is "session_start();" not the correct session code?
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
EDIT
<?php
session_start(); // Starting Session
echo "hello";
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
echo "hello";
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "root", "");
// Selecting Database
$db = mysqli_select_db("game", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query("select * from login where password='$password' AND username='$username'", $connection);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: header.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}
?>
Change it to:
<td><i><?php echo $username; ?></i></td>
$username is not an array , gli must write :
<td>Welcome </td>
<td><i><?php echo $username ; ?></i></td>
I am not sure if i am reading this right are you looking to start a new session at the top of the page and the store values in that session?.
if you place something like the following at the top of your page it will remember sessions variables
if(!isset($_SESSION)){session_start());
You would then assign to a session variable using
$_SESSION["userName"] = $_POST["userName"];
To tell if its be set to grant access to a admin console you could do something like
if(isset($_SESSION["userName"]) && $_SESSION["userName"] != '')
the above means that the variable has been set but you would probably wrap the session userName in a db function to check for valid logins.
The button I was clicking was set to "login" whereas the isset was set to "submit".
Simply changing the words solved it.