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
Related
Below is my login page code in php.
<?php
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = $_POST['username'];
$mypassword = $_POST['password'];
$f_password = md5($mypassword);
$sql = "SELECT id,user_name FROM users WHERE user_name = '$myusername' and password = '$f_password'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_assoc($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
$_SESSION['us_name'] = $row['user_name'];
header("Location: /main-page.php");
}else {
$error = "<script>alert('Incorrect Credentials.Please login again');</script>";
echo $error;
}
}
?>
When i use another header in else block it throws me some error .
But i want user to redirect to same login page when he enters wrong credentials.
How can I do it in php??
Please don't tell me to use js method window.location.
First to answer your question: I assume the error comes from sending data - the echo you do in the else block - and then trying to add headers. You must send all headers before sending the first data, which includes printing stuff with echo.
Your problem should go away if you put the header() line right in the beginning of the else block and make sure you have no other output before (e.g. with a var_dump()).
Additionally there is a number of security issues in your script:
You use md5() to encode the password which is highly insecure. Modern php has a function password_hash() (available since PHP 5.5) which you should use instead
Your username and password are used without filtering the input. This opens you up to SQL injection as they are reused in an unsafe manner in your SQL query. You should look at prepared statements or at least filter and quote the user input
Another question related as to why you need the header: If you want to redirect to the login page, why do you have the <script>-snippet on the page? When changing the location it will not take affect anyway, right?
And final question, your question is tagged with laravel. So I'm curious why you don't use it's Authentication mechanism instead?
I've tried doing my research and it doesn't look like I'm coming up successful. I made sure there is no content being printed out to the screen before my header tags.
This page is taking information given from the form in the previous login page and using that information to determine which page the user should be redirected to. Unfortunately, it doesn't look like any of my header tags are redirecting to anything, it just stays on this php page.
To debug, I have echo'd each scenario (logged in, out, wrong pw) and each scenario works, but obviously when I echo'd the redirect wouldn't work. I just wanted to test that the information was being transmitted correctly.
Can anyone else help and give me an outsider's perspective?
<?php
session_start();
include('dbconnect.php');
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$query = "SELECT password FROM artists WHERE email='$email'";
$passwordMatch = mysqli_query($db, $query);
$row = mysqli_fetch_array($passwordMatch);
if($row[0] == $password){
$query = "SELECT active FROM artists WHERE email = '$email'";
$active = mysqli_query($db, $query);
$active = mysqli_fetch_array($active);
$active = $active[0];
if ( $active == 0 ){
header('Location: validate.php');
}
else{
header('Location: artistHome.php'); //redirect to user home page and update session
$_SESSION['user']= $email;
unset($_SESSION['error']);
}
}
else{
header("Location: login.php");
$_SESSION['error']= 'Invalid Password';
}
?>
There were about thousands of posts like this one over here.Get rid of php closing tag ?> and whitespaces, html, blank lines before php opening tag <?php. Also check if there is no output before :
header("Location:");
Like print,var_dump, echo and so on.
Also check your if condition, maybe you are just skipping it.
If you include,include_once,require_once or require check all the things above in the included files too.
To narrow a circle of the things to correct look into your php error_log and provide us with error description.
header("Location: login.php"); will always fail if anything is returned to the browser before it. That includes whitespace, or even errors PHP are returning. Make sure nothing is being returned before the header function is used.
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 :)
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.