on my website, at the top of every php page, I have an
include_once 'header.php';
This file contains HTML.
In my file, 'authenticate.php', I want to have a redirect after logging in back to the index.
My code is the following:
header('Location: http://www.URLHERE.com/index.php');
However after submitting, the page just refreshes. It doesn't redirect. The redirect worked properly on my localhost dev server, but as soon as I uploaded it online, it stopped working.
Is this because my header contains HTML, which is called before the header() function? Note that all HTML in the 'header.php' file is in HEREDOC tags.
Here is my code:
<?php // login.php
include_once 'header.php';
include_once 'functions.php';
require_once 'login_users.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to database:" . mysql_error());
mysql_select_db($db_database)
or die("Unable to find database:" . mysql_error());
if (isset($_POST['username']) &&
isset($_POST['pw_temp']))
{
$username = sanitizeString($_POST['username']);
$pw_temp = sanitizeString($_POST['pw_temp']);
$pw_temp = md5($pw_temp);
$query = "SELECT username,password FROM users WHERE username='$username' AND password='$pw_temp'";
if (mysql_num_rows(mysql_query($query)) == 0)
{
die("Wrong info");
}
else
{
$_SESSION['username'] = $username;
$_SESSION['password'] = $pw_temp;
$_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR'];
header('Location: http://www.URLHERE.com/index.php');
}
}
...more code down here
on my website, at the top of every php page, I have an include_once 'header.php';
This is what you are doing wrong.
What it have to be
<?php // login.php
include_once 'functions.php';
require_once 'login_users.php';
// some code
include 'output.php'; // ONLY HERE output starts.
Here you can see a concise but complete example with some explanations and reasoning. But the main reason for getting rid of your header.php and start using templates is the very question you asked.
You can do the include in else, remove the include_once 'header.php'; from the top file lines an do it like this:
if (isset($_POST['username']) &&
isset($_POST['pw_temp']))
{
$username = sanitizeString($_POST['username']);
$pw_temp = sanitizeString($_POST['pw_temp']);
$pw_temp = md5($pw_temp);
$query = "SELECT username,password FROM users WHERE username='$username' AND password='$pw_temp'";
if (mysql_num_rows(mysql_query($query)) == 0)
{
die("Wrong info");
}
else
{
$_SESSION['username'] = $username;
$_SESSION['password'] = $pw_temp;
$_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR'];
header('Location: http://www.URLHERE.com/index.php');
}
}
else
{
include_once 'header.php';
//..... now your code!!!!!
}
Maybe it's because of code that you're executing after setting header? Add die after that line (header is not stopping execution!).
Related
i have used this code for years and never experienced this, using a new hosting service prior to the ones i have always used and am getting this issue.
session_start();
$rec_page = $_SERVER['REQUEST_URI'];
$cPage = $_SERVER['PHP_SELF'];
if(!isset($_SESSION['isadmin'])){
header('location: login.php?l=i');
}
include('includes/constants.php');
include('includes/functions.php');
$admin_login = $_SESSION['login'];
$admin_psw = GetAdminInfo($admin_login,'1');
if(isset($_REQUEST['cmd'])){
if($_REQUEST['cmd']=="logout"){
session_destroy();
header('location: login.php');
}
}
this is the section of the code with the issues, once i login i get redirected to the login.php if i delete this
`if(!isset($_SESSION['isadmin'])){
header('location: login.php?l=i');
}`
i can login successfully but if i click on another page i will have to login again, so im guessing its a Session problem.
here is the action php for the login.php
<?php
include('../includes/constants.php');
include('../includes/functions.php');
if(isset($_POST['xin'])){
$ikey = addslashes($_POST['textKey']);
$nkey = addslashes($_POST['textname']);
$mysqli = mysqli_connect($dbserver,$dbuser,$dbpass) or die('Cannot connect to db');
mysqli_select_db($mysqli, $db_db) or die('Cannot select db');
$result=mysqli_query($mysqli, "SELECT * FROM admins WHERE login = '".$ikey."' && adminname = '".$nkey."'");
$cnt = mysqli_num_rows($result);
if($cnt > 0){
while($rw=mysqli_fetch_array($result)){
session_start();
$_SESSION['isadmin']=true;
$_SESSION['login'] = $ikey;
$_SESSION['adminname'] = $nkey;
header('location: ../index.php?cm='.$_SESSION['isadmin']);
}
}else{
header('location: ../login.php?err=1'.mysqli_error($mysqli));
}
mysqli_close($mysqli);
}
?>
use javascript instead of header. No long story
echo "<script>parent.self.location='index.php';</script>";
I've been working on a login system using PHP and the MySQLi functions, however I've come across an error that I believe is failing to identify the session, I can't figure out the reason as to why it's happening.
Edit: Updated code.
Login.PHP
<?php
session_start();
require 'db/connect.php';
If (Isset($_POST['Login'])) {
$EM = mysqli_real_escape_string($db, $_POST['email']); //Assign directly no need to create the $EM. You can put the whole into your query also
$PW = mysqli_real_escape_string($db, $_POST['password']);
$result = $db->query("select * from users where Email='$EM' AND password='$PW'");
$row = $result->fetch_array(MYSQLI_BOTH);
$_SESSION["UserID"] = $row['UserID'];
header('location: Account.php');
exit;
}
?>
Account.php
<?php
require 'db/connect.php';
session_start();
if (isset($_SESSION["UserID"])) {
include 'header.php'; //It contains output so move after session_start();
echo 'Successfully logged in';
} else {
header('location: Login.php');
exit;
}
?>
You have output before calling session_start();. This should cause the "header has already been sent"-fatal error.
Remove the empty line in account.php (closing and opening php doesn't make sense anyway, in this snippet)
include 'header.php';
?>
<?php
session_start();
Is there some kind of output in the header.php?
Do you get any errormessages? You can display errors by adding following to the top of your code:
ini_set('display_errors', 1);
error_reporting(-1);
edit after knowing what heder.php does: your account.php should start like this
<?php
session_start();
require 'db/connect.php';
include 'header.php';
EDIT
Based on OP comments.
Here are the finel files. Do not put anything before session_start() or header() functions, there should be nothing output in the buffer before these functions.
session_start();
require 'db/connect.php';
if (Isset($_POST['Login'])) {
$EM = mysqli_real_escape_string($db, $_POST['email']); //Assign directly no need to create the $EM. You can put the whole into your query also
$PW = mysqli_real_escape_string($db, $_POST['password']);
$result = $db->query("select * from users where Email='$EM' AND password='$PW'");
$row = $result->fetch_array(MYSQLI_BOTH);
$_SESSION["UserID"] = $row['UserID'];
header('location: Account.php');
exit;
}
And the Account.php
session_start();
require 'db/connect.php';
if (isset($_SESSION["UserID"])) {
include 'header.php'; //It contains output so move after session_start();
echo 'Successfully logged in';
} else {
header('location: Login.php');
exit;
}
I am having problems with my code. This is a login/register script I've made by following a tutorial.
The problem I have is that I want the script to echo "logged in" ONLY when the user has entered correct login details, and yet it still echoes "logged in" even if I don't enter any login details. I checked it and if I delete the "session_start()" function, it doesn't do the same thing, but it still doesn't give me access to the session when I want to login.
This is the init.php file, used to initiate the connection with the database and define some other functions:
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
?>
This is the connect.php file, used to connect to the database :
<?php
$connect_error = 'Sorry, we are experiencing connection issues. This will be solved as soon as possible.';
$con=mysqli_connect("localhost","root","","lr") or die ($connect_error);
mysqli_select_db($con,'lr') or die($connect_error);
mysqli_close($con);
?>
The general.php file is not important for this question.
This is the users.php file, where I keep some other functions.
function user_id_from_username ($username){
$username = sanitise($username);
$mysqli = new mysqli("localhost", "root", "", "lr");
$query = "SELECT * FROM users";
$result = $mysqli->query($query);
while($row=$result->fetch_row()){
if ($row[1]==$username){ //username == $username
return $row[0];//user_id;
}
}
}
function login ($username, $password){
$user_id= user_id_from_username($username);
$mysqli = new mysqli("localhost", "root", "", "lr");
$username = sanitise($username);
$password =md5 ($password);
$query = "SELECT * FROM users";
$result = $mysqli -> query($query);
while ($row =$result -> fetch_row()){
if($row[1]==$username && $row[2]==$password){
return TRUE;
}else {
return FALSE;
}
}
}
This is the file that calls the login function, presented above:
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) ===TRUE || empty ($password) === TRUE) {
$errors[]='You need to enter a username and password!';
} else if (user_exists($username) ===FALSE) {
$errors[]="We can't find that username, have you registered?";
} else if (user_active($username)===FALSE){
$errors[]="You have not activated your account!";
} else{
$login = login($username, $password);
session_start();
if ($login ==false) {
$errors[] ='That username/password combination is incorrect!';
}else if ($login==true) {
//set the user session
$_SESSION['username'] = $login;
//redirect user to homepage
header('Location: index.php');
exit();
}
}
if ($errors){
print_r($errors);
}
}
?>
And now the index.php file, in which I have the if statement that echoes 'logged in' even if I am not logged in :
<?php
if (empty($_SESSION['username'])) {
echo 'not logged_in';
}else {
echo 'logged in';
}
?>
Now I think the problem is located somewhere either in the users.php, login.php or in the index.php file. I presented all of the files so you could get an idea of what I am trying to achieve. This code is spread over so many files because I have functions and interfaces that I have included and I want to be able to reuse the code, so I am using includes.
For you to get a better idea, if my files did not help you enough, I will leave the Youtube link of the tutorial I am following :
https://www.youtube.com/watch?v=JUk2e8oqOvI&list=PLE134D877783367C7&index=7#t=6.296979
Thank you,
Waiting for your answer,
Best regards,
If you don't use $_GET requests to include the pages, you need to put session_start() on top of each file where you are using the $_SESSION variable otherwise you can't use the sessions.
<?php
session_start();
// Rest of your script
I hope this will help you.
I have a class named User which has a function named logout(). I create an instance of this class in index.php and i pass it's value to $_SESSION[usr] before i call memberspage.php . In memberspage.php i have a link named logout which when clicked i want the logout() function to run and also send the user to index.php. For this purpose i've done something like this.
Log out
I know that -> causes the problem but i don't know how to fix it. thnx for your time.
The following code worked for me
Log out
but there is a problem. If i go to the page(memberspage.php) where the above code is and i press the back arrow (not logout link) the logOut() function will still be used(the session is destroyed and i will have to log in again to access memberpage.php) . I don't get it because i thought that the only way to call the logOut() function was to click on Log out link.
If $_SESSION[usr]->logout() is working for you as you said in your comment. I don't know how.
But here is just for calling a php function inside anchor tag.It's totally depend on your function response.
<?php
function usr(){
return "abc";
}
?>
Log out
First i suggest that you change your use of session you can create a page for example session.php where all your session is place, it can also be the re directory page of your login page.
like this one named login.php
create in your form make action redirect to session.php
i also suggest that all your php codes of login are inside the session.php then make this one.
<?php
session_start();
$host = "localhost";
$uname = "root";
$pass = "";
$db = "mydb;
//database connection
$conn = mysqli_connect($host, $uname, $pass, $db);
mysqli_select_db($conn, $db);
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
//$username = mysqli_real_escape_string($username);
//$password = mysqli_real_escape_string($password);
$sql = "SELECT * FROM table WHERE username = '" .$username. "' AND password = '".$password."' LIMIT 1";
$res = mysqli_query($conn, $sql);
if(mysqli_num_rows($res) > 0){
if($data = mysqli_fetch_assoc($res))
{
$_SESSION['type'] = $data['type'];
if(isset($_SESSION["login_user"]))
{
if($data['type'] == 'admin'){
header('location: admin.php');
}
else if($data['type'] == 'customer'){
header('location: customerhome.php');
}//header('location: uservalidation.php');
}
}
}
else{
//header('location: #');
echo '<script>';
echo 'alert("Invalid no?")';
echo '</script>';
header('location: logind.php');
}
}
?>
then create another page which is logout.php
put this code inside:
<?php
session_start();
header('location: index.php');
session_destroy();
?>
then save put the a link your page for logout.php
Add file logout.php and put into them your logout implementation:
<?php
header('Content-Type: application/json');
$_SESSION[usr]->logout();
echo json_encode(['message' => 'ok']);
And call this file with AJAX:
<script>
function logout() {
$.ajax({
url: '/logout.php'
}).then(function (res) {
window.location.href = '/';
});
}
</script>
Log out
On my offline dev server, I have the following code:
<?php //submit_build.php
include_once 'header.php';
require_once 'login_users.php';
include_once 'functions.php';
if(empty($_SESSION['username']))
die ("You must be logged in to use this page");
$choice = $_GET['choice'];
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
if (isset($_POST['buildname']) &&
isset($_POST['weapon']) &&
isset($_POST['mod1']) &&
isset($_POST['description']) &&
isset($_POST['category']) &&
isset($_POST['hidden']) &&
isset($_POST['password']))
{
$buildname = clean(sanitizeString($_POST['buildname']));
$buildurl = urlencode($buildname);
$section = $choice;
$weapon = sanitizeString($_POST['weapon']);
$modcap = sanitizeString($_POST['modcap']);
$mod1 = sanitizeString($_POST['mod1']);
$mod2 = sanitizeString($_POST['mod2']);
$mod3 = sanitizeString($_POST['mod3']);
$mod4 = sanitizeString($_POST['mod4']);
$mod5 = sanitizeString($_POST['mod5']);
$mod6 = sanitizeString($_POST['mod6']);
$mod7 = sanitizeString($_POST['mod7']);
$mod8 = sanitizeString($_POST['mod8']);
$polarity1 = sanitizeString($_POST['polarity1']);
$polarity2 = sanitizeString($_POST['polarity2']);
$polarity3 = sanitizeString($_POST['polarity3']);
$polarity4 = sanitizeString($_POST['polarity4']);
$polarity5 = sanitizeString($_POST['polarity5']);
$polarity6 = sanitizeString($_POST['polarity6']);
$polarity7 = sanitizeString($_POST['polarity7']);
$polarity8 = sanitizeString($_POST['polarity8']);
$description = sanitizeString($_POST['description']);
$category = sanitizeString($_POST['category']);
$hidden = sanitizeString($_POST['hidden']);
$pw_check = sanitizeString($_POST['password']);
$pw_check = md5($pw_check);
if ($pw_check == ($_SESSION['password']))
{
$add_build = "INSERT INTO weapons VALUES(NULL,'$username', '$buildname', '$section', '$weapon', '$modcap', '$mod1', '$mod2', '$mod3', '$mod4', '$mod5', '$mod6', '$mod7', '$mod8', '$polarity1', '$polarity2', '$polarity3', '$polarity4', '$polarity5', '$polarity6', '$polarity7', '$polarity8', '$category', '$hidden', '$description', NULL, '{$_SESSION['ipaddress']}', '$buildurl')";
mysql_query($add_build);
header("Location: account.php");
}
else{
die("Incorrect password.");
}
}
Followed by some more PHP, and HTML later on in the document.
NOTE The file header.php contains HTML.
My code works perfectly offline. I can click submit, and I will be redirected to account.php.
However as soon as I upload the files to my remote server, the code still works perfectly but the redirect does not. Instead of redirecting, it just brings me back to the same page. The data that was entered DOES however get submitted to MySQL, so it's just the redirect that isnt working.
Can someone tell me how I would get this
header(Location: account.php);
to work? Where should I place it? Or where should I move
include_once 'header.php';
to make it work?
Thanks so much!
EDIT:
Here is my authenticate.php file.. up to where the html begins. Maybe you can see an issue here.
<?php // authenticate.php
include_once 'functions.php';
require_once 'login_users.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to database:" . mysql_error());
mysql_select_db($db_database)
or die("Unable to find database:" . mysql_error());
if (!empty($_POST['username']) &&
(!empty($_POST['pw_temp'])))
{
$username = sanitizeString($_POST['username']);
$pw_temp = sanitizeString($_POST['pw_temp']);
$pw_temp = md5($pw_temp);
$query = "SELECT username,password FROM users WHERE username='$username' AND password='$pw_temp'";
if (mysql_num_rows(mysql_query($query)) == 0)
{
die("Wrong info");
}
else
{
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $pw_temp;
$_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR'];
header('Location: index.php');
exit;
}
}else{
include_once 'header.php';
echo <<<_END
<html xmlns="http://www.w3.org/1999/xhtml">
Its a good idea to exit; after a header() as otherwise your code will continue in the current script. Which probably means it will send itself again. So you may well be running account.php but this page is then being sent and overwriting account.php making it look like account.php is not being run.