PHP link to page.php from another file - php

Im creating my first page in PHP with login form.
Here is my question,
I have this kind of structure:
MAINFILE:
-index.php
-asstes(file)
-config(file)
-includes(file) (with header.php)
-user(file) with user.php
and after loggin from index.php i want to direct user to user.php but after using header("Location: user/user.php"); i get ERROR 404.
Does anybody knows how to redirect to page in another file?
Thanks!
<?php
$error = "Email or password was incorrect<br>";
if(isset($_POST['login_button'])) {
$login = $_POST['log_login']; //sanitize email
$_SESSION['username'] = $login; //Store email into session variable
$password = md5($_POST['log_password']); //Get password
$check_database_query = mysqli_query($con, "SELECT * FROM users WHERE login='$login' AND password='$password'");
$check_login_query = mysqli_num_rows($check_database_query);
if($check_login_query == 1) {
$row = mysqli_fetch_array($check_database_query);
$username = $row['login'];
$role =$row['role'];
$_SESSION['username'] = $username;
if(role == "admin"){
header("Location: admin.php");
$_SESSION['role'] = true;
}
else {
header("Location: /user/user.php");
$_SESSION['role'] = false;
}
exit(0);
}
else {
echo $error;
}
$_SESSION['log_login'] = "";
$_SESSION['log_password'] = "";
}

Actually if in your index.php you have a login form which sends a POST request then, after a successful sign-in you can redirect user using:
header('Location: /user.php');
exit(0);
Path passed in location is relative to user's current position so if your file user.php is in the root folder then use /user.php; if in user so that the filename is user/user.php then use:
header('Location: /user/user.php');
exit(0);
Yet a lot of that may be caused by the way you actually sign in your user and how you manage the session creation so would be great and helpful if you have shared the code.

Related

php how to redirect user to index.html when sucessfully logging in

hi i am having problems with a login script for my website i need the script to redrect the user to index.html if the login details are correct. if you could help me at all it would be greatly appreciated.. thank you...
here is my script for checking the details ==>
<?php
include('config.php');
?>
$ousername = '';
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password']))
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$ousername = stripslashes($_POST['username']);
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = stripslashes($_POST['password']);
}
else
{
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
}
//We get the password of the user
$req = mysql_query('select password,id from users where username="'.$username.'"');
$dn = mysql_fetch_array($req);
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
?>
<?php
}
else
{
//Otherwise, we say the password is incorrect.
$form = true;
$message = 'The username or password is incorrect.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
any help would be greatly appreciated.. thank you.
UPDATE: As #Dagon corrected me..
To redirect user back to index.html, you can use the following:
header('Location: http://example.com/index.html');
exit;
after successful login.
So your source code is not preferly the best to this way of login, but even in this way you should make a redirection after login.
It you can do with JavaScript, exactly i recomend you tu use jQuery API, which will help you to improve many things on your site.
So in your situation i recomend you this way of solution:
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
echo "<script>$('#idofelement2reload').load('php.php?login=1');</script>";
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
}
So if you noticed, this line
echo "<script>$('#idofelement2reload').load('php.php?login=1');</script>";
writes a line into html document which call a function to load through jQuery a file with parameter that the user is logged in.
Don`t forget to include jQueries source code in head
Use the header() function after setting the user information in $_SESSION.
// If the password is good, we don't show the form
$form = false;
// We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
header('Location: http://example.com/index.html');
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
header('Location:http://sitename.com/index.php');
?>

Php Session Redirect Page

Okay, What I have here is a simple php login session. Sometimes session destroy even I don't destroy the session. In my Index.php, there's a link for editing record. My problem is, if session destroy and I click edit, the page open's in modal or fancybox and shows login.php and after I login it's goes to index.html. What I need to do is instead of going into index.html, I need to redirect to edit.php with GET value to continue the edit process. Any help?
Index.php
<a class="fancybox" href="edit.php?pn='.$row["id"].'"><img src="images/edit.png"></a>
Edit.php
<?php
session_start();
include('connect.php');
$tbl_name="login_admin";
if(! isset($_SESSION['id'])){
header('location:login.php');
exit;
}
$id = $_SESSION['id'];
$sql = $mysqli->query("SELECT * FROM $tbl_name WHERE username='$id'");
$accounts = $sql->fetch_assoc();
$term= $mysqli->real_escape_string($_GET["pn"]);
?>
Login.php
<?php
require_once('connect2.php');
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$submit = $_POST['submit'];
if($username && $password){
$sql = sprintf("SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'");
$result = #mysql_query($sql);
$accounts = #mysql_fetch_array($result);
}
if($accounts){
$_SESSION['id'] = $accounts['username'];
header("location:index.html");
exit;
}elseif($submit){
$msg = 'Invalid Username or Password';
}
?>
Unfortunately you can't continue the edit process, but you can redirect user to edit page after login.
There are more ways how to to it, I will show one of them.
before redirecting user to login script, save his original URL to session (another way would be to pass it to login.php as GET parameter - don't forget validation in that way):
Edit.php:
<?php
session_start();
include('connect.php');
$tbl_name="login_admin";
if(! isset($_SESSION['id'])){
$_SESSION['original_url']=$_SERVER['REQUEST_URI']
header('location:login.php');
exit;
}
// rest of the code.....
Then redirect user to that page instead of default index.html page
Login.php:
<?php
require_once('connect2.php');
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$submit = $_POST['submit'];
// Security note: see I've sanitized $username and $password with mysql_real_escape_string() to avoid SQL injection
if($username && $password){
$sql = sprintf("SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'");
$result = mysql_query($sql);
$accounts = mysql_fetch_array($result);
}
// when account was found store identity to session
if($accounts){
$_SESSION['id'] = $accounts['username'];
if (isset($_SESSION['original_url']) {
// if user came from internal url, redirect to it and remove it from session
$originalUrl = $_SESSION['original_url'];
unset($_SESSION['original_url']);
header("location:".$originalUrl);
exit;
} else {
// redirect user to default page after login
header("location:index.html");
exit;
}
} elseif($submit){
// login form was sent, but user with given password not found
$msg = 'Invalid Username or Password';
}
?>

Losing session values after header redirection

I'm using $_SESSION to keep my users logged in after they have logged in.
When they return to the homepage, they at first appear to be logged in, but after refreshing the page once, they are no longer logged in.
NOTE: I'm still learning PHP programming so please don't mind that most of my code is rather, noobish.
Index.php Code:
<?php
session_start();
$UserOnline = "Guest";
if (isset($_SESSION['username'])) {
$UserOnline = $_SESSION['username'];
}
echo $UserOnline;
?>
Login.php Code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username)) {
$InvalidLogin = "Please submit a username";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
} elseif (empty($username)) {
$InvalidLogin = "Please submit a password";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
require 'required/connect.php';
$result = mysqli_query($con, "SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
if ($password == $row['password']) {
$_SESSION['username'] = $username;
echo "Successful Login!";
echo "<br>";
echo "<a href='index.php'>Return to HomePage?</a>";
} else {
$InvalidLogin = "Your info didn't match ours!";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
?>
I have tested on the login.php page if the user is in a session there, and I always get the correct return value. The issue is that after I refresh once on the Index.php page, the user is no longer in a session.
Is there something I'm forgetting, or am I not using the $_SESSION correctly? Is there another error that I simply do not know about?
Put exit; after header('location:.....') and your problem will be solved.
Issue is resolved. Error was found in Index.php. Set Variable $UserOnline before the if(isset($_SESSION['username'])). Thanks for the help guys

Session information being lost

I'm running a login script and according to who logs in I redirect to one of two pages
If I direct to a page that is in a directory below the main directory all works fine, however if i direct to a page that is above the directory in which the index.php file sits, the session information seems to be lost and the user is asked to login again
I know that I could simply place the second page in a directory below the main directory but I would like to understand if it is possible to maintain the session information when directing to a page above the main directory
the user goes to a page called login.html, when they have input there information, they are sent to login.php, it is here where the redirect occurs
if ($username==$dbusername&&$password==$dbpassoword)
{
if($admin == "1"){
header('location: http://www.edit.domain_name.co.uk/');
$_SESSION['username']=$username;
$_SESSION['id']=$id;
}else{
header('location: /member');
$_SESSION['username']=$username;
$_SESSION['id']=$id;
}
}
I have put session_start (); at the beginning of every page where the user would need to login to access. Any input would be greatly received
the full code for the login script is
<?php
session_start () ;
$username = $_POST['username'] ;
$password = $_POST['password'] ;
################# ADMIN OR NOT ###################################################
include_once "mysql/global.php";
$result = mysql_query("SELECT admin FROM users WHERE username = '$username'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
$admin = $row[0];
################# ###############################################################
if ($username&&$password)
{
include "mysql/global.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'] ;
$dbpassoword = $row["password"] ;
}
// check to see if they match!
if ($username==$dbusername&&$password==$dbpassoword)
{
if($admin == "1"){
session_start();
header('location: http://www.edit.domin_name.co.uk/admin');
$_SESSION['username']=$username;
$_SESSION['id']=$id;
}else{
session_start();
header('location: /member');
$_SESSION['username']=$username;
$_SESSION['id']=$id;
}
}
else
echo "<center>incorrect password!</center>" ;
}
else
die ("<center>That user does not exist!</center>") ;
}
else
echo ("<center>Please enter a username and password</center><br/>") ;
die ("<a href=\"index.php\"><center><b>Click here to try again</b></center></font>");
?>
In order to load sessions, you must place session_start() at the top of each page.
Also, you need to call session_start() before setting them and before redirecting:
if ($username == $dbusername && $password == $dbpassoword) {
if($admin == "1"){
session_start();
$_SESSION['username']=$username;
$_SESSION['id']=$id;
header('Location: http://www.edit.domain_name.co.uk/');
}
else {
session_start();
$_SESSION['username']=$username;
$_SESSION['id']=$id;
header('Location: /member');
}
}
header('location: /member');
For a start, this is invalid. The Location header should be followed by a full, not a relative, URL.
Secondally, if /member is a directory, and you access www.example.com/member, Apache is quite likely to redirect you to example.com/member/, adding the forward slash and dropping the www.. The move to a different domain name is likely to result in the loss of session data.

How to prevent browser from going back to login form page once user is logged in?

I'm trying to make a website in which the admin can upload books through an admin portal. I've made a successful login but when the user gets logged in and presses the back button (on the browser) the form page appears again, and the same happens when they log out and press back button, the page that should appear only appears after they login again. I searched a lot on the internet but all in vain. Please make a suggestion about it.
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password) {
$connect = mysqli_connect("localhost", "root", "") or die ("Could'nt connect to database!"); //database connection
mysqli_select_db($connect, "mahmood_faridi") or die ("Could'nt find database");
$query = ("SELECT * FROM user WHERE username= '$username'");
$result = mysqli_query($connect, $query);
$numrows = mysqli_num_rows($result);
if ($numrows !== 0) {
while ($row = mysqli_fetch_assoc($result)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password == $dbpassword) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header('location: help.php'); //another file to send request to the next page if values are correct.
exit();
} else {
echo "Password Incorrect";
}
exit();
} else {
die("That user doesn't exists!");
}
} else {
die("Please enter a username and password");
}
?>
On the login screen, in PHP, before rendering the view, you need to check if the user is already logged in, and redirect to the default page the user should see after logged in.
Similarly, on the screens requiring login, you need to check if the user is not logged in and if not, redirect them to the login screen.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
}
You can conditionally add Javascript code to go forward to the intended page.
<script>
history.forward(1);
</script>
This might be annoying or fail when Javascript is not present and/or disabled.
index.php page you should need to add the code in the top of a php file....
<?php
include 'database.php';
session_start();
if (isset($_SESSION['user_name'])) {
header('location:home');
}
if (isset($_POST['submit'])) {
$user = $_POST['user_name'];
$password = $_POST['password'];
$query = "select count(*) as count from users where user_name= '$user' and password = '$password';";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($result)) {
$count = $row['count'];
if ($count == 1) {
$_SESSION['user_name'] = $user;
header('location:home');
}
}
}
?>
This is another page. home.php page you should need also to add the code in the top of a php file to check it first.
<?php
include 'database.php';
if (!(isset($_SESSION['user_name']))) {
header('location:index');
}
?>
I am just modifying #sbecker's answer, use exit() after redirecting.
I have faced the same issue, but now exit(); works for me.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
exit();
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
exit();
}
you can use this it's easy to use
<?php
if(empty($_SESSION['user_id'])){
header("Location: login.php");
}
else{
header("Location: dashboard.php");
}
?>
My suggestion: the login should happen when the users clicks some link/button
Once the login server side takes place, use the the php function header('url') to redirect the user to the url it should be. (be careful not to echo anything otherwise the redirect will not happen)
[Edit] You say you have the first login file an html one, that is fine to me, but you say it redirects to whatever, then you are using a redirect from client side. In my opinion you should not use that client side redirect for the login. Probably that is causing the confusion.

Categories