I am doing a project on two different servers, my code works perfectly on one server and refuses to work on the other.
The purpose of the code is for a user to login on the login.php page, and be redirected to the dashboard.php page, if their login credentials are correct. The header.php file simply contains information for the nav bar for different people logging in.
Please let me know where the error could be.
I'm not sure whether these are two distinct problems but both the Header redirect is not working, and neither are the session variables being stored. I made sure I didn't echo out anything before the header redirect.
Login.php
<?php include('header.php');?>
<?php
session_start();
$dbusername = $_SESSION['username'];
$dbfName = $_SESSION['fName'];
$dblName = $_SESSION['lName'];
$sessiontype = $_SESSION['type'];
if($dbusername && $dbfName && $dblName && $sessiontype){
header('Location: ./dashboard.php');
}
if(isset($_POST['login_button'])){
session_start();
$getuser = $_POST['username'];
$getpass = $_POST['password'];
$getpassmd5 = md5(md5($getpass));
if($getuser && $getpass){
require('connect.php');
$query1 = "SELECT * FROM students WHERE StudentNum='$getuser'";
$exequery1 = mysql_query($query1);
if(mysql_num_rows($exequery1) > 0){
while ($row = mysql_fetch_assoc($exequery1)){
$dbusername = $row['StudentNum'];
$dbpass = $row['password'];
$dbDOB = $row['DOB'];
$dbfName = $row['FirstName'];
$dblName = $row['LastName'];
}
if($dbpass){
if($getuser === $dbusername && $dbpass === $getpassmd5){
$_SESSION['username'] = $dbusername;
$_SESSION['fName'] = $dbfName;
$_SESSION['lName'] = $dblName;
$_SESSION['type'] = "student";
header('Location: ./dashboard.php');
}
else{
echo("<h4><center>You have entered incorrect login credentials</h4></center>");
}
}
else{
if($getuser === $dbusername && $getpass === $dbDOB){
$_SESSION['username'] = $dbusername;
$_SESSION['fName'] = $dbfName;
$_SESSION['lName'] = $dblName;
$_SESSION['type'] = "student";
header('Location: ./dashboard.php');
}
else{
echo("<h4><center>You have entered incorrect login credentials</h4></center>");
}
}
}
else{
$query2 = "SELECT * FROM teachers WHERE username='$getuser'";
$exequery2 = mysql_query($query2);
if(mysql_num_rows($exequery2) > 0){
while ($row = mysql_fetch_assoc($exequery2)){
$dbusername = $row['username'];
$dbpass = $row['password'];
$dbfName = $row['FirstName'];
$dblName = $row['LastName'];
$dbtype = $row['type'];
}
if($getuser === $dbusername && $dbpass === $getpassmd5){
$_SESSION['username'] = $dbusername;
$_SESSION['fName'] = $dbfName;
$_SESSION['lName'] = $dblName;
$_SESSION['type'] = $dbtype;
header('Location: ./dashboard.php');
}
else{
echo("<h4><center>You have entered incorrect login credentials</h4></center>");
}
}
else{
echo("<h4><center>You have entered login credentials that do not exist</center></h4>");
}
}
}
else{
echo("<h4><center>Please enter both a username and password</center></h4>");
}
}
?>
Firstly, You should not have different <?php and ?> tags.
As its counted as a space.
<?php include('header.php');?>
<?php
session_start();
Should be:
<?php
session_start();
include('header.php');
Its adding a space in the file, hence redirection is not taking place.
Sounds like an Apache server or PHP configuration issue. On both servers, run a script with:
phpinfo();
Compare them for discrepancies. Also, check the PHP version, loaded extensions, and configurations in the .ini. It could be Apache httpd.conf, but I'm guessing on it being a php.ini issue or a PHP version issue.
Recommendation: create an autoloader to be a PHP include on line 1 of every file. Autoload your session and db and constants in there. This will ensure the session is loaded prior to outputting HTML, which seems to be where others are seeing an issue.
line 1: require_once('config.php');
Do session_start(); into your page first line
<?php
session_start();
Related
From index.php I get the values of the username and password fileds with $_POST
index.php
if(isset($_POST["username"]) && isset($_POST["password"])){
$username = mysql_real_escape_string(strtolower($_POST['username']));
$password = mysql_real_escape_string($_POST['password']);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
checkUser($_SESSION['username'], $_SESSION['password']);
}
Then I store these $username and $password variables inside the $_SESSION and call a function checkUser($_SESSION['username'], $_SESSION['password'])); which sends two parameters. The checkUser() function executes inside lib.php
lib.php
session_start();
function checkUser($username, $password){
include "connection.php";
$result = mysqli_query($conn, "SELECT * FROM `data` WHERE `username` = '$username' AND `password` = '$password'") or die("No result".mysqli_error());
$row = mysqli_fetch_array($result);
$logic = false;
if (($row['username'] == $username) && ($row['password'] == $password)) {
$logic = true;
echo "HI,".$username;
?>
<a href='logout.php'>Log Out</a>
<?php
$file = $row['file'];
echo "<img src='images/users/".$file."' >";
}
else{
echo "Failed to login. Username or password is incorrect. Try again.";
}
}
This part is for showing the name of the user and the image according to it.
logout.php works
logout.php
unset($_SESSION["username"]);
unset($_SESSION["password"]);
unset($_SESSION["file"]);
header("Location: index.php");
session_destroy();
The problem is when I navigate from one page to another, the $_SESSION variable becomes empty. Something is wrong with session. Please help me.
in the php pages you need to access session variable add session_start() after the starting <?php code
I am having an issue with 2 files: login_config.php and profile.php.
login_config.php consists of a log in system, which sets $_SESSION['key'] true upon the completion of several forms of authentication.
profile.php is the page the user is redirected to after success.
I want data on profile.php to only be accessible with $_SESSION['key'] set (upon successful login).
My question: What is incorrect with my code? Furthermore, why am I presented with the error upon login submission that is only supposed to return if $_SESSION['key'] is false/not set, as opposed to the targeted profile.php page?
CODE: (login_config.php)
<?php
// POST VARIABLES
$submit = $_POST['login_submit'];
$username = $_POST['login_username'];
$password = $_POST['login_password'];
$email = $_POST['login_email'];
require 'password_config.php';
if(isset($submit)){
require 'db/connect.php';
// PASSWORD VERIFYING
$pass_query = "SELECT password FROM users WHERE email='$email'";
$queried = mysql_query($pass_query);
while($row = mysql_fetch_array($queried)){
$user_pass = $row['password'];
$veri_password = password_verify($password, $user_pass);
}
if(!$veri_password === true){$errors[] = '-Account does not exist ';}
// CHECKING NUM ROWS
$sql = "SELECT id, username FROM users WHERE password='$user_pass' AND email='$email'";
$entered_user = mysql_query($sql);
$num_rows = mysql_num_rows($entered_user);
// ERRS ARRAY ESTABLISHED
$errors = array();
// FURTHER VERIFYING
if( empty($password) || empty($email) )
{
$errors[] = 'Please do not leave fields empty';
}
elseif( $num_rows != 1 )
{
$errors[] = '-Account does not exist ';
}
elseif( $num_rows == 1 )
{
session_start();
$_SESSION['key'] === true;
while($row = mysql_fetch_array($entered_user)){
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $email;
$_SESSION['user'] = $row['username'];
$_SESSION['pass'] = $password;
header('Location: profile.php');
exit();
}
}
}
CODE: (profile.php)
<?php
session_start();
if($_SESSION['key'] !== true){
die ("please <a href='login.php'>log in</a> to view this page");
}
?>
<html>
<head>
<title>Profile</title>
<link href='css/main.css' rel='stylesheet' />
</head>
<body>
<div id='container'>
<?php require 'include/header.php'; ?>
<?= 'NJM ID # ==>'.$_SESSION['id'].'<br />'.'Username ==>'.$_SESSION['user'].'<br/>'.'Password ==>'.$_SESSION['pass'].'<br/>'.'<br />' ?>
<a href='logout.php'>Log out!</a>
<br />
-OR-
<br />
<p>Try our beta mode<a href='forum.php'> forum</a></p>
<?php require 'include/footer.php'; ?>
</div>
</body>
</html>
Note: I am aware I am vulnerable to SQL attacks at the current state of code, I will be fixing this later, also I am stuck with the deprecated version of MySQL.
In profile.php you have to call session_start(); before using $_SESSION. session_start() doesn't just start a new session, but will also continue an existing session (it will 'start' the session handling functionality, if you will). Without calling it, you cannot use $_SESSION.
1st: I would use termary operators for checking the existence of the values I need, for avoiding the "undefined index 'login_username'" error. Like this:
$username = isset($_POST['login_username']) ? $_POST['login_username'] : '';
$password = isset($_POST['login_password']) ? $_POST['login_password']) : '';
$email = isset($_POST['login_email']) ? $_POST['login_email'] : '';
2nd: I would use PDO for connecting with the MySQL server, for security reasons, and not only.
session_start();
if (isset($submit)){
// select all data from db for the current user
$st = $db->prepare('SELECT * FROM users WHERE email=?');
$st->execute([$email]);
//$rows = count_rows_here
if($rows == 1){
$row = $stmt->fetch();
if(password_verify($password, $row['pass'])){
$_SESSION['key'] = true; // notice the '=', and not '==='
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $row['email'];
$_SESSION['user'] = $row['username'];
$_SESSION['pass'] = $row['password'];
header('Location: profile.php');
} else {
echo 'Error!';
}
}
}
I have fixed this by assigning the $_SESSION['key'] a variable with a value.
$_SESSION['key'] = $check = 'check';
Then to test this in profile.php, I have entered the following code:
if(isset(!$_SESSION['key'])){die ('example')}
I would try first to remove the exit() call after you have headered to the next PHP page. It isn't necessary as you have no code below it and it might be affecting the session (I don't think so though)
If this doesn't work (probably wont) add to profile.php after you have started the session var_dump($_SESSION) and have a look/post its contents.
I've looked at lots of answers to redirect to a different page after submitting a form, but haven't been able to get it to work thus far, probably because I have no idea where to actually put the code. Can anyone help? The rest of this code is working fine, i just need to know where to place header():
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//connects to database, checks username & password against database to see is user exists
if($username && $password)
{
include ("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows !==0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
//if username and password are correct
if($username==$dbusername&&md5($password)==$dbpassword)
{
echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
}
//if password is incorrect
else
echo "Your password is incorrect.";
}
//if username is incorrect
else
die("Username does not exist.");
}
//if no information is submitted
else
die("Please enter your login details.");
//prevents errors from displaying on page
error_reporting(0);
?>
I also need to know where it goes for this page:
<?php
//Check if register button was pressed
$button = $_POST['button'];
//if button was pressed,
if ($button)
{
//get data from form,
$username = $_POST['username'];
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
}
//check if all information has been entered,
if ($username && $password && $retype_password && $first_name && $last_name)
{
//check if password and retype_password are the same
if($password==$retype_password)
{
//check if username already exists
include("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username = '$username'");
$numrows = mysql_num_rows($query);
if($numrows == 0)
{
//encrypt password
$password = md5($password);
//sends data from form to database - creates new user
$register = mysql_query("INSERT INTO users VALUES ('', '$username', '$password', '$first_name', '$last_name')");
echo "You are now registered. <a href='main.php'>Continue to site.</a>";
}
else
echo "Username is unavailable.";
}
else
echo "Password did not match.";
}
//prevents errors from displaying on page
error_reporting(0);
?>
Thanks in advance!
if($username==$dbusername&&md5($password)==$dbpassword)
{
$_SESSION['username'] = $username;
header( 'Location: http://www.yoursite.com/new_page.html' ) ;
}
You should put it once the job is done : that is after
//echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
header('Location: your url');
exit;
Don't forget the "exit" or what follow will be executed.
That said, you cannot echo something before a doing redirection, that's logical because the echo can't be seen.
So, either you do not echo :
$_SESSION['username'] = $username;
header('Location: your url');
exit;
Or you do a HTML (or javascript) redirection, with a 5 seconds delay:
echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
exit;
In which case you have to put it in the < head > section, to do the HTML redirection:
<meta http-equiv="refresh" content="0; url=http://example.com/main.php" />
Also
error_reporting(0);
Should be put at the beginning of the page, unless you want errors for previous lines to be shown.
BUT : error_reporting(0); should NEVER be used on a development site (and always on a production site).
You should turn on display_errors('on') and error_reporting(E_ALL) to see errors - errors are very useful for a developer.
hi in my script i have it logging in users , but i want to have the script also check if the user is an admin by seeing if the account_type is a,b,c account type "c" is the admin and i would like it to redirect the admin to the admin page ...
<?php // Start Session to enable creating the session variables below when they log in
// Force script errors and warnings to show on page in case php.ini file is set to not display them
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once("security/checkuserlog.php");
if (isset($_SESSION['idx'])) {
echo '<script language="Javascript">';
echo 'window.location="home.php"';
echo '</script>';
}
//-----------------------------------------------------------------------------------------------------------------------------------
// Initialize some vars
$errorMsg = '';
$username = '';
$pass = '';
$remember = '';
if (isset($_POST['username'])) {
$username = $_POST['username'];
$pass = $_POST['pass'];
if (isset($_POST['remember'])) {
$remember = $_POST['remember'];
}
$username = stripslashes($username);
$pass = stripslashes($pass);
$username = strip_tags($username);
$pass = strip_tags($pass);
// error handling conditional checks go here
if ((!$username) || (!$pass)) {
$errorMsg = '<font color="red">Please fill in both fields</font>';
} else { // Error handling is complete so process the info if no errors
include 'connect_to_mysql.php'; // Connect to the database
$username = mysql_real_escape_string($username); // After we connect, we secure the string before adding to query
//$pass = mysql_real_escape_string($pass); // After we connect, we secure the string before adding to query
$pass = md5($pass); // Add MD5 Hash to the password variable they supplied after filtering it
// Make the SQL query
$sql = mysql_query("SELECT * FROM members WHERE username='$username' AND password='$pass'");
$login_check = mysql_num_rows($sql);
// If login check number is greater than 0 (meaning they do exist and are activated)
if($login_check > 0){
while($row = mysql_fetch_array($sql)){
// Create session var for their raw id
$id = $row["id"];
$_SESSION['id'] = $id;
// Create the idx session var
$_SESSION['idx'] = base64_encode("g4p3h9xfn8sq03hs2234$id");
$username = $row["username"];
$_SESSION['username'] = $username;
} // close while
// Remember Me Section
// All good they are logged in, send them to homepage then exit script
header("location: home.php");
exit();
} else { // Run this code if login_check is equal to 0 meaning they do not exist
$errorMsg = '<font color="red">The Username And Password did not match.</font>';
}
} // Close else after error checks
} //Close if (isset ($_POST['uname'])){
?>
if ($row["account_type"] == "c") { header("Location: admin.php"); }; in your while loop should do it.
This will basically set the "Location" header to "admin.php" or whatever admin page you want, however don't forget to check in your admin page if the user is actually logged in, to avoid users simply going manually to "admin.php" and bypassing the permission check.
$account_type= $row["account_type"];
$_SESSION['account_type'] = $account_type;
then change header("location: home.php"); into
if($account_type=='admin')
{
header("location: adminpanel.php");
}
else
{
header("location: home.php");
}
Here is my code for some reason, it is always returning that the password is incorrect. I'm not sure if I just forgot a bracket somewhere, also how can I make it more secure because right now I'm using the _post function.
<?php
include 'config.php';
session_start();
session_destroy();
session_start();
$UserName = $_POST['UserName'];
$PassWord = $_POST['PassWord'];
if ($UserName&&$PassWord)
{
mysql_select_db("SegmentMath") or die ("Couldn't find database sorry.");
$query = mysql_query("SELECT * FROM Users WHERE UserName='$UserName'");
$numrows = mysql_num_rows($query);
if ($numrows!=0)
{
// code to login
while ($row = mysql_fetch_assoc($query))
{
$dbUserName = $row['UserName'];
$dbPassWord = $row['PassWord'];
}
//check to see if they match!
if ($UserName==$dbUsername&&$PassWord==$dbPassWord)
{
$_SESSION['UserName']=$dbUsername;
$_SESSION['PassWord']=$dbPassWord;
echo "<p>Finished Software</p>";
}
else
{
echo "Incorrect Password";
}
}
else die("Sorry username not found!");
}
else die("Please Enter A Valid Username And Password!");
?>
So I'm almost positive I'm doing something stupid wrong and it has had me stumped for almost 30 minutes. This file is just the login.php so basically if the user enters there username and password on the login.html page, it pushes that data to this page Login.Php.
I'm confused why it says incorrect password no matter what even if the login is correct and in the database.
I would say, it's better to use this, i mean create query which find the username and password
$login = mysql_query("SELECT * FROM users WHERE ID='". $UserName ."' AND PASSWORD='". md5($PassWord) ."');
$row=mysql_fetch_array($login); // fetch row
if($row!=null) // if found row
{
$_SESSION['UserName'] = $row['UserName']; // store in session
$_SESSION['PassWord'] = $row['PassWord'];
} %>
instead of
if (($UserName==$dbUsername)&&($PassWord==$dbPassWord))
{
$_SESSION['UserName']=$dbUsername;
$_SESSION['PassWord']=$dbPassWord;
echo "<p>Finished Software</p>";
}
You have a typo in your code. Variables in PHP are case-sensitive...
19. while ($row = mysql_fetch_assoc($query))
20. {
21. $dbUserName = $row['UserName'];
22. $dbPassWord = $row['PassWord'];
23. }
24.
25. //check to see if they match!
26. if ($UserName==$dbUsername&&$PassWord==$dbPassWord)
The variable on line 21 doesn't match that on line 26.
$dbUserName is not the same as $dbUsername
You are probably using some encryption when the password are stored. For example if you are using md5()(just an example, md5 is not the best for passwords) you should check this way:
if ($UserName == $dbUsername && md5($PassWord) == $dbPassWord)
{
if ($UserName==$dbUsername&&$PassWord==$dbPassWord)
{
$_SESSION['UserName']=$dbUsername;
$_SESSION['PassWord']=$dbPassWord;
echo "<p>Finished Software</p>";
}
else
{
echo "Incorrect Password";
}
1).it goes in else condition .. so can you echo these four $variables to me ?
2).remove spaces from the $_post with str_replace
if ($UserName==$dbUsername <= capitalize $dbUserName)
{
//YOUR LOGIC
}
I think you code it wrong way. You should not put session destroy after session start. First of all, let start the session by session_start();
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM table_name WHERE username = '$username'";
$result = mysql_query($query);
$count = mysql_num_rows($query);
$row = mysql_fetch_assoc($result);
if($count == 0)
{
//if there is no result
}
$dbpassword = $row['password'];
if($dbpassword == $password)
{
//put some session here
}
else
{
//if the password is not match
}
I hope this might help
You need to connect to the database first. Use mysql_connect()
Also note that this function is being depreciated and the use of mysqli is or PDO is recommended. There is a link to these in the link above.