I've looked everywhere and tried all solutions but it's still not getting me anywhere. Here's my code:
<?php
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
header('Location: /public_html/index.php');
exit;
}
elseif(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
if(mysql_num_rows($checklogin) == 1)
{
$row = mysql_fetch_array($checklogin);
$email = $row['EmailAddress'];
$_SESSION['Username'] = $username;
$_SESSION['EmailAddress'] = $email;
$_SESSION['LoggedIn'] = 1;
header('Location: /public_html/index.php');
exit;
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
?>
When I upload this into my server and login it brings me to a blank php page. What am I doing wrong with this code? I've tried using " instead of ' . I'm trying to redirect the user to a page outside of the folder hence the "/public_html/". Any help would be much appreciated.
if outside the folder than use
header("Location:../public_html/index.php");
Starting your URL with / and followed with the folder name means, you want to go to the top/root directory, and followed with the folder name you've specified.
For example:
Getting to /public_html means you're redirecting to http://www.example.com/public_html which I believe to be non-existance in your case
To get around this problem, do this:
add a double dot: ..
Getting to ../public_html means you're redirecting from http://www.example.com/some_project/some_folder/ to http://www.example.com/some_project/public_html/ (for example).
refer to Vicky's answer,
header("Location:../public_html/index.php");
exit();
and do not forget to add the exit(); in the end.
edit: Please cease using the ancient PHP-MySQL. There's a better alternative for you to use, for your own safety:
PHP MySQLi
PHP PDO MySQL
Related
So what I'm trying to do here is have my users login in.
This is the script I am using to do that.
I have just used an converter found here: https://wikis.oracle.com/display/mysql/Converting+to+MySQLi to convert my Mysql to mysqli because I am a beginner and had no idea how to do that.
Now when the users puts in an correct password and username.
It goed exactly how I want it and the user gets redirected to 'dashboard.php'
However, when user enters incorrect data, the users ends up on a black 'login.php' (which is the code I am showing here) instead of 'loginerror.php' which is what I want.
I hope some people here can help me out because I am pretty lost.
PS: Yes I know the passwords are in plain text right now but don't worry about that because I will fix that later.
<?php
session_start();
if(!$_SERVER['REQUEST_METHOD'] == 'POST') {
echo "Please leave.<br /><br />";
echo "<a href='index'>Click to go back</a>";
exit();
}
if(($GLOBALS["___mysqli_ston"] = mysqli_connect('localhost', 'root', ''))) {
if(((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE users"))) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$zoekresultaat = mysqli_query($GLOBALS["___mysqli_ston"], $query);
if($zoekresultaat = mysqli_affected_rows($GLOBALS["___mysqli_ston"]) > 0) {
$record = mysqli_fetch_assoc($zoekresultaat);
$zoekresultaat = mysqli_query($GLOBALS["___mysqli_ston"], $query);
if($zoekresultaat = mysqli_affected_rows($GLOBALS["___mysqli_ston"]) > 0) {
$record = mysqli_fetch_assoc($zoekresultaat);
$_SESSION['login'] = true;
$_SESSION['username'] = $record['username'];
header('location: dashboard.php');
} else {
header('location: loginerror.php');
}
exit();
} else {
echo "<br /><br />Could not find Database";
}
} else {
echo "<br /><br />Could not connect to Database";
}
}
?>
You cannot redirect using the header method after anything has been outputted. In this case, you use Echo before your header redirection, so it will not work.
See this thread for reference : How to fix "Headers already sent" error in PHP
What you should do define redirection before outputting anything in your application, if it seems difficult, your application might need to be restructured.
Here are some alternatives if you don't want to do that, but they are bad practice :
HTML
<meta http-equiv="Location" content="http://example.com/">
Javascript
<script> location.replace("target.html"); </script>
Also as usual, defend yourself against MySQL injections : How can I prevent SQL injection in PHP?.
Okai, so I attempted to post this a bit earlier, although my question has changed slightly.
I have identified the problem to be in between my login.php (where I assign the $_SESSION value) and my members.php page (where I try to pick up the $_SESSION variable again, but fail to recover it). The way I identified this problem was by running a var dump on session in my members.php file which gave me 0. I also did this after I asign the value in login.php and I got the asigned value as an outcome.
If you help me out I will really appreciate it!
This is my login.php page:
<?php
session_start();
require('connect.php');
$username = $_POST['username'];
$password = $_POST['password'];
if (isset($username) && isset($password))
{
$query = mysql_query("SELECT * FROM login WHERE username='$username' AND password='$password'");
$result = mysql_num_rows($query);
if($result > 0)
{
echo "You have been logged in. <a href='members.php'>Go to the members page</a>";
$username = $_SESSION['login'];
}
else
{
echo "Password is incorrect. Try again.";
}
}
else
{
echo "You have to enter your username and password. Try again";
}
?>
This is my members.php page:
<?php
session_start();
if (isset($_SESSION['login']))
{
echo "Welcome " . $login . " | <a href='logout.php'>Logout</a>";
}
else
{
header('Location: index.php');
}
?>
Solved in Chat:
Turns out var_dump(is_writable(session_save_path())); returned bool(false).
The session_save_path() was /var/php_sessions/.
realpath(dirname(__FILE__)); was /hermes/bosoraweb124/b185/dom.gjertgjersundcom/public_html.
I tried moving the session save path -- however for some reason the folder within public_html couldn't be written, same with read (couldn't read). In any case, it's a bad idea to have sessions in the public folder for everyone to see anyway.
I recommended the OP contact their host provider to run the command of chmod 766 -R /var/php_sessions/.
Solved: The staff at his webhost applied the permissions and it works fine now.
Your session "login" variable is not set because you never set it in your login file...
You should specifically set it with $_SESSION['login'] = "blah";
I assume your problem is you meant to set login and not the username when you log in the user...
swap
if($result > 0)
{
echo "You have been logged in. <a href='members.php'>Go to the members page</a>";
$username = $_SESSION['login'];
}
with
if($result > 0)
{
echo "You have been logged in. <a href='members.php'>Go to the members page</a>";
$_SESSION['login'] = $username;
}
Then you should be able to access your "login" session variable from your member page.
Also on your member page I do not see you set your $login variable. So I assume that would be a blank space and you meant to echo your session login variable with $_SESSION['login'].
I know this subject has been covered a ton, and I have looked and searched so I think I am missing something basic.
I have a Username Password log in system that is setup as:
Login page: set to Action - checklogin.php
checklogin.php - checks against the database for username and password, and then in the header brings them to their custom URL, which is in column 3 of the database. So user1 goes to folder1/, user2 goes to folder2/, etc.
It seems to work fine, but lets say I am logged in as user1 (URL /folder1/), it allows me to enter '/folder2/' in the URL window, and that folders index file comes up.
So basically if I am logged in any username, I can pull up the other users folder/index.php file.
So I think somehow the code on the index.php page is not validating the users correctly.
CODE (top is fine, connecting to DB, etc, so I left that out) :
checklogin.php:
// Define $username and $password
$username=$_POST['username'];
$password= $_POST['password'];
// To protect MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1){
// Register $username, $password and redirect to file "index.php"
session_start();
$_SESSION[$username];
$_SESSION[$password];
$_SESSION['loggedin'] = true;
$_SESSION[$id];
$row = mysql_fetch_assoc($result);
$result = mysql_query("SELECT folder FROM users2");
$_SESSION['folder'] = $row['folder'];
if( isset($username) ) {
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
header('Location: clients/'. $row['folder'].'/index.php');
exit();
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
}
?>
On the receiving URL index.php page:
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
// not logged in, move to login page
header("location:../../login.php");
exit;
}
I have tried many other variations of the receiving "Protect Page" code, but none seem to work correctly. Is it the receiving code or the checklogin code??? I feel I am missing something obvious.
Thanks in advance, any take on this will be appreciated. - Randy
You need to add additional checks in the protected pages; not only do you need a logged-in user, you also need to check the requested path and see if the user has access to that.
Something like (for example...):
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true
|| stripos($_SERVER['REQUEST_URI'], $_SESSION['folder']) === false) {
// not logged in, move to login page
header("location:../../login.php");
exit;
}
Apart from that you should never store plain-text passwords and you should really switch to PDO (or mysqli) and prepared statements with bound variables.
Edit: Another solution to make clear what is happening:
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
// not logged in, move to login page
header("location:../../login.php");
exit();
}
elseif (stripos($_SERVER['REQUEST_URI'], $_SESSION['folder']) === false)
{
// $_SESSION['folder'] is not found in the path,
// not user's folder, go to own folder
header('Location: /clients/'. $_SESSION['folder'].'/index.php');
exit();
}
else
{
// show page of user
}
your using a lot of unnecessary !==
replace most of those with !=
also change
if($count==1){
to
while($count>=1){
change
if( isset($username) ) {
to
if( isset($username) && $username != "" && $username != NULL ) {
Var_dump $result, make sure it contains what you want, you've got it listed two times.
when you reference a variable inside a session I'd recommend double/single quoting it.
Do yourself a favor and avoid magic quotes and mssql() entirely. Switch to pdo or MYSQLI
if (!isset($_SESSION['loggedin']) |$_SESSION['loggedin'] !== true)
if (stripos($_SERVER['REQUEST_URI'], $_SESSION['folder']) === false)
{
// not logged in, move to login page
header("location:../../login.php"); exit; } – RandyS just now edit
<?php
session_start();
include 'db.php';
include 'header.html';
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['email'])) {
header("location:profile.php");
} elseif(!empty($_POST['email']) && !empty($_POST['pass'])) {
$email = mysql_real_escape_string($_POST['email']);
$pass = md5(mysql_real_escape_string($_POST['pass']));
$sql = mysql_query("SELECT id, name, email, pass FROM users WHERE email='$email' AND pass='$pass'");
$row = mysql_fetch_array($sql);
$id = $row['id'];
$email1 = $row['email'];
$name = $row['name'];
$num = mysql_num_rows($sql);
if($num == 1) {
$_SESSION['id'] = $id;
$_SESSION['email'] = $email1;
$_SESSION['name'] = $name;
$_SESSION['LoggedIn'] = 1;
$update = mysql_query("UPDATE users SET lastlogin=NOW() WHERE email='$email1'");
header("location:profile.php");
} else {
echo "<h1>Error</h1>";
echo "<p>Sorry! Either your account could not be found or you have entered the wrong email or password. Please try again.</p>";
}
}
?>
This script works perfectly in my localhost environment but when uploaded to host, it does not go to the profile.php after logging in. Also, it doesn't redirect to profile.php if the session is set or not empty. Any ideas?
And second question, is my code correct for updating the 'lastlogin' to the current time? What does the database structure have to be for this? It is not updating in my database.
Thank you for your help.
your code is very ok for updating the lastlogin, but what is the error you get? please give what type of error you get on this. logically your code seems to be right, it may be some syntax error. add error_reporting(E_ALL) on top of your page and see what error is occurred actually.
header("location: profile.php");
^ //space should present because in some host environment it creates problem
If you are redirecting to the login script from a form using most likely POST, shouldn't you use $_POST[''] instead of $_SESSION?
Just a thought.
Always use exit(); after header redirection
Ok figured it out with an extensive search. The headers were already being sent with the
include header.html
line so it could not perform the
header(location: profile.php)
line. I had never heard of this issue before until now. So to resolve this issue, I just moved
<?php
...
include header.html
?>
to the bottom of the php code right before the HTML starts. Now the include header line can do it's thing and then the header will still be loaded for the page.
Thanks for all your help with this.
I am trying to log in using this code :
session_start();
require "connect.php";
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrow = mysql_num_rows($query);
if($numrow!=0)
{
while($row = mysql_fetch_assoc($query))
{
$db_username = $row['username'];
$db_password = $row['password'];
}
if($username==$db_username&&$password==$db_password)
{
//echo 1;
header("Location: members.php");
$_SESSION['username']=$db_username;
}
else echo 0;
}
else die("That user doesn't exist");
}
else die("Please enter a username and password");
upon successful log in it should take me to members.php :
session_start();
if($_SESSION['username']) <------ this is line 5
{
echo "20730312";
echo " You are logged in as: ".$_SESSION['username'];
echo "<p><a href='logout.php'>Click here to logout</a>";
}
but when i request members.php in my application it gives me :
Notice: Undefined index: username in E:\Program Files\xampp\htdocs\adddrop\members.php on line 5
note that i am using android webview to request members.php after successful log in, is this right ? what am i doing wrong ?
On a side note: you have an SQL injection there. Might want to read more: http://en.wikipedia.org/wiki/SQL_injection
The problem you are facing is that the username is not always POST'd (when you just load the page first time):
$username = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
That should fix it. Basically, I check if the POST index is set, and only if it is I try to access it, otherwise I set it to null.
Also, you might want to do it like this:
$query = mysql_query("SELECT * FROM users WHERE username='" . mysql_real_escape_string($username) . "'");
That prevents the SQL injection vulnerability.
And also add exit;:
header("Location: members.php");
$_SESSION['username']=$db_username;
exit; // Add this.
Same as always. You're not POSTing to the URL. Verify the URL you're attempting to POST to.
perhaps this:
header("Location: members.php");
$_SESSION['username']=$db_username;
should be changed to (reverse):
$_SESSION['username']=$db_username;
header("Location: members.php");
As it says, you don't have the specified data from POST. Make sure your form action is right and you're filling out the username.
Also, you might want to consider hashing your passwords. From what I can see here you compare plain text passwords (or you're already getting hashed passwords to your script, which would be ok).