I have a user login page with a form that's action is "auth.php"
auth.php looks like this :
<?php
session_start();
require_once('database.php');
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM access_getaccountswithinfo WHERE username='".$username."' AND password='".$password."'";
$run = mysql_query($sql);
$row = mysql_fetch_array($run);
if (mysql_num_rows($run) == 1) {
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['password'] = $row['password'];
$_SESSION['packagename'] = $row['packagename'];
$_SESSION['creation-date'] = $row['creation-date'];
$_SESSION['cap'] = $row['cap'];
$_SESSION['total'] = $row['total'];
$_SESSION['remainingtopup'] = $row['remainingtopup'];
header("location: usage.php");
} else {
header("location: user_login.php");
$message = MSG_INVALID_USERPW;
}
mysql_close($link);
?>
Then this auth.php has a Require_once to : database.php
database.php as follow :
<?php
$link = mysql_connect('localhost', 'testdatabase', '123456');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// make testdatabase the current db
$db_selected = mysql_select_db('testdatabase', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
echo 'Connected successfully';
?>
So in short...you login on login page , action then checks with auth.php if user can authenticate whilst requiring database.php to connect , if user authenticates , it takes them to page usage.php as set by header("location: usage.php"); in auth.php.
NOW this works 100% on my local machine , with a xampp Apache and SQL server.
But when I uploaded this to the webserver, I login on login page and the it takes me to the page "auth.php" and stops there and shows "connected Successfully" as per echo in database.php. and nothing further , it is suppose to authenticate and then take me to usage.php. Ive checked database name , table ect , all correct , any ideas pleas?
You are not allowed to write anything to the output-stream before you use header(...). It might work on some servers but you should not expect it to.
Remove all the echo and print statements in your code and you should be redirected.
Additionally, you should really use mysql_real_escape_string(..) [http://php.net/manual/en/function.mysql-real-escape-string.php], or even change from the deprecated mysql_ commands to PDO. Right now I could login to your website by using the username ' OR 1=1 LIMIT 0,1; --
NOW this works 100% on my local machine
That's some really bad code. Bypassing the authentication is trivial.
You don't do any further error checking after establishing the connection.
Once you echo something, you can no longer set any headers. Try removing the echo statements.
Source: http://php.net/manual/en/function.header.php
Quote: "Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file."
try adding
error_reporting(E_ALL);
ini_set('display_errors', '1');
in the top of your code
and see if there are errors or not, usually errors are hidden in a hosting server
Just try to delete the echo 'connected successfully'; from the code and try to omit any blank line , because header function is too sensitive it needs that you have not send any output before using them so any echoing or any simple html is considered as output and the header function will not functions properly due the error that headr is already sent and if the level of error reporting is to hide error you will not notice this error
please try to omit any space or any echoing before the header function calling then tell me the result :)
Related
New code
$count= mysqli_num_rows($result);
if ($count==1){
$row=mysqli_fetch_row($result);
if(($row[1]==$username) && ($row[2]==$password))
{
echo $row[1];
$_SESSION["myusername"]= $username;
$_SESSION["mypassword"]= $password;
header("location: login_success.php");
exit();
} else {
echo "No user found";
}
} else {
echo "No rows selected";
//}
mysqli_close($dbc); // Closing Connection
}
}
?>
I modified the code but the header statement is causing it to stop. If I delete the header it works as expected.
$username = stripslashes($sent_username); is the culprit since you are saving the fetched username in $sent_user and not $sent_username. Since that is what you're using in your query:
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
Where $username does not make any sense if you roll back and see what it really holds i.e. $username = stripslashes($sent_username);, Now you see the culprit $sent_username, Where is it? No where, a typo indeed.
Instead of this:
$sent_user=$_POST['myusername'];
$sent_password=$_POST['mypassword'];
$username = stripslashes($sent_username);
$password = stripslashes($sent_password);
Try this:
$sent_user=$_POST['myusername'];
$sent_password=$_POST['mypassword'];
$username = stripslashes($sent_user);
$password = stripslashes($sent_password);
EDIT:
This should solve your problem, however there are a couple things you should re-check.
1) Proper syntax for header:
Instead of this:
header("location:login_success.php");
use this:
header("Location: login_success.php");
2) echo your query to see what really is happening, correct table with proper column and the proper values are being sent.
3) How could I forget the most important part, No matter what you do regarding sessions, ALWAYS write session_start(); in the beginning of your code in every file you intend to use sessions in.
^An Example:
<?php
session_start();
$host="localhost"; // Host name
$db_username=""; // Mysql username
$db_password=""; // Mysql password
$db_name="test_db_connection"; // Database name
$tbl_name="logintable"; // Table name
$error=''; // Variable To Store Error Message
if (isset($_POST['submit']))
//
Remove the:
echo $row[1];
Above the header command. Headers must always happen before any other output is provided to the client. This is because in the HTTP spec, headers come first and must be in the right format.
If you attempt to use Header in PHP after you have sent other content to the client then it will trigger a warning because you have tried to violate the HTTP specification. This is what the documentation says:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
http://php.net/manual/en/function.header.php
When someone logs in on my website, it will output information just for that user and so on. But there is a problem as it seems it doesn't recognise different users. If I log in two users on the website, first one will become second one... here is my code at the start of each page
?php
session_start();
require_once 'loginDetails.php';
$db_server = mysql_connect("$db_hostname", "$db_username",
"$db_password");
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
if (isset($_SESSION['username']))
{
$user = $_SESSION['username'];
$query = mysql_query("SELECT * FROM cssh_students_table WHERE StudentUserName = '$user'");
$query1 = mysql_fetch_row($query);
$course = $query1[10];
$year = $query1[6];
$email = $query1[4];
$loggedin = TRUE;
}
else
{
$loggedin = FALSE;
}
if ($loggedin == FALSE)
{
session_unset();
session_destroy();
header('Location: ../index.html');
}
?>
session_destroy() is not guaranteed to kill your session cookie. Your problem is probably because your original session cookie still exists.
See this related question.
Additional (Not Related)
Doing a SELECT * and then accessing the results using integer indexes is a bad practice that will eventually cause you problems some day when the database structure is changed. Either SELECT the items you need, or use mysql_fetch_assoc and access the values by name.
There can be many solutions for that.
For us, we need to do that kind of thing in development. For each user we want to open, we use an anonymous browser window. Another solution could be to use a different domain name for each user you want to login (with a dns wildcard).
please help i have the following php code for my login session but i am trying to get the $_session['user_id'] instead of the $_session['email']. i tried print_f function to see what i can use but user_id array says 0 which cannot be right unless i read it wrong.
session_start();
$email = strip_tags($_POST['login']);
$pass = strip_tags($_POST['password']);
if ($email&&$password) {
$connect = mysql_connect("xammp","root"," ") or die (" ");
mysql_select_db("dbrun") or die ("db not found");
$query = mysql_query("SELECT email,pass FROM members WHERE login='$email'");
$numrows = mysql_num_rows($query);
if ($numrows!=0) {
// login code password check
while ($row = mysql_fetch_assoc($query)) {
$dbemail = $row['login'];
$dbpass = $row['password'];
}
// check to see if they match!
if ($login==$dbemail&&$password==$dbpass) {
echo "welcome <a href='member.php'>click to enter</a>";
$_SESSION['login']=$email;
} else {
echo (login_fail.php);
}
} else {
die ("user don't exist!");
}
//use if needed ==> echo $numrows;
} else {
die ("Please enter a valid login");
}
i am trying to get the $_session['user_id'] instead how can get this to use instead of $_session['email']. tried using $_session['user_id'] but instead i got undefined error msg.
Well, you don't define $_session['user_id'] anywhere in this script, so it's no surprise that it's not defined. You have to assign it a value before you can refer to it.
Also, note that there all kinds of security problems with this code.
You're running your MySQL connection as the root user. This is NOT a good idea.
You're trusting user input, which opens your script up to a SQL injection attack. Stripping HTML tags from the user input does not make it safe. Suppose that I came to your site, and filled in the "email" field with this:
bob#example.com'; GRANT ALL PRIVILEGES ON *.* TO 'evil_bob' IDENTIFIED BY '0wned_joo';
As currently written, your script would happily run its query as normal, and also create an account called "evil_bob" with full privileges to all the information in all of the databases on your server.
To avoid this, NEVER assume that user input is safe. Validate it. And to be extra sure, don't stick variables straight into SQL you've written. Use bound parameters instead. There are a few cases where it's hard to avoid -- for example, if you need to specify the name of a column rather than a piece of data, a bound parameter will not help and you'll have to do it some other way. However, for any piece of data you're using as part of a query, bind it.
I am hosting a website from a local computer (using MAMP Pro on a Mac), and need to switch the hosting to another local Mac. I have copied across all of the files for my website, and the MySQL tables, and checked that the server and MySQL are running OK. Everything seems to be fine, except that the login system is returning "Invalid User" when I try to log in, even though I am entering the correct user info (I have tried a few users just to be sure).
The log.php that handles the login looks like this:
<?
session_name("MyLogin");
session_start();
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","root","password"); // your MySQL connection data
$db = mysql_select_db("nick"); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM USERS WHERE login='$name'");
if(mysql_num_rows($q_user) == 1) {
$query = mysql_query("SELECT * FROM USERS WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) {
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/may.php"); // success page. put the URL you want
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}
// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}
?>
I have temporarily removed the password in the above code.
I wonder what steps I can take to troubleshoot this issue, and would be grateful for any help.
Thanks,
Nick
A few common techniques when I encounter this issue.
Output the generated SQL and test it by hand - echo $query;
See if mysql_error() outputs anything after you run your queries.
Use var_dump() and print_r() on your data objects to ensure they are as expected.
Comment out your redirects and exit() lines so you can determine where the script is breaking.
Fix or comment back with anything determined by the above.
Your code does a query to find a user with the given username, and then checks if the number of rows with that username is exactly 1.
The only way you could see the 'Invalid User' error is if there are 0 users with that username or more than 1 user with that username.
Have a look at the contents of the table and check which of these is the case (I recommend http://sequelpro.com for viewing database contents on a Mac). You can also use sequel pro to test your queries.
I am using sessions to pass user information from one page to another. However, I think I may be using the wrong concept for my particular need. Here is what I'm trying to do:
When a user logs in, the form action is sent to login.php, which I've provided below:
login.php
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$con = mysql_connect("xxxx","database","pass");
if (!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
session_start();
$_SESSION['loggedin'] = 1; // store session data
$_SESSION['loginemail'] = fldEmail;
header("Location: main.php"); }
}
mysql_close($con);
Now to use the $_SESSION['loggedin'] throughout the website for pages that require authorization, I made an 'auth.php', which will check if the user is logged in.
The 'auth.php' is provided below:
session_start();
if($_SESSION['loggedin'] != 1){
header("Location: index.php"); }
Now the point is, when you log in, you are directed BY login.php TO main.php via header. How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php? Will I have to connect again just like I did in login.php? or is there another way I can simply echo out the user's name from the MySQL table? This is what I'm trying to do in main.php as of now, but the user's name does not come up:
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
$row = mysql_fetch_array($result);
echo '<span class="backgroundcolor">' . $row['fldFullName'] . '</span><br />' ;
Will I have to connect again just like I did in login.php?
Yes. This is the way PHP and mysql works
or is there another way I can simply echo out the user's name from the MySQL table?
No. To get something from mysql table you have to connect first.
You can put connect statement into some config file and include it into all your scripts.
How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php?
You will need some identifier to get proper row from database. email may work but it's strongly recommended to use autoincrement id field instead, which to be stored in the session.
And at this moment you don't have no $loginemail nor $loginpassword in your latter code snippet, do you?
And some notes on your code
any header("Location: "); statement must be followed by exit;. Or there would be no protection at all.
Any data you're going to put into query in quotes, must be escaped with mysql_real_escape_string() function. No exceptions.
so, it going to be like this
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$loginemail = mysql_real_escape_string($loginemail);
$loginpassword = mysql_real_escape_string($loginpassword);
$query = "SELECT * FROM Members WHERE fldEmail='$loginemail' and Password='$loginpassword'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if($row = mysql_fetch_assoc($result)) {
session_start();
$_SESSION['userid'] = $row['id']; // store session data
header("Location: main.php");
exit;
}
and main.php part
session_start();
if(!$_SESSION['userid']) {
header("Location: index.php");
exit;
}
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$query = "SELECT * FROM Members WHERE id='$sess_userid'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_assoc($result));
include 'template.php';
Let me point out that the technique you're using has some nasty security holes, but in the interest of avoiding serious argument about security the quick fix is to just store the $row from login.php in a session variable, and then it's yours to access. I'm surprised this works without a session_start() call at the top of login.php.
I'd highly recommend considering a paradigm shift, however. Instead of keeping a variable to indicate logged-in state, you should hang on to the username and an encrypted version of the password in the session state. Then, at the top of main.php you'd ask for the user data each time from the database and you'd have all the fields you need as well as verification the user is in fact logged in.
Yes, you do have to reconnect to the database for every pageload. Just put that code in a separate file and use PHP's require_once() function to include it.
Another problem you're having is that the variables $loginemail and $loginpassword would not exist in main.php. You are storing the user's e-mail address in the $_SESSION array, so just reload the user's info:
$safe_email = mysql_real_escape_string($_SESSION['loginemail']);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$safe_email'");
Also, your code allows SQL Injection attacks. Before inserting any variable into an SQL query, always use the mysql_real_escape_string() function and wrap the variable in quotes (as in the snippet above).