Redirect site using session script - php

I´m trying to redirect visitor when visits the page for first time to site 1. The second visit the script will redirect the visitor to site 2. I want to use session. But it doesn´t work right and I dont know where is the mistake.
Logic should be: If you are here for the first time you will be redirected to site 1, if you are here for the second time you will be redirected to side 2.
this is the code i made:
session_start();
if ($_SESSION["header"] = " " || !isset($_SESSION))
{
$_SESSION["header"] = "1";
echo header("Location: http://site 1");
}
else
{
session_destroy();
echo header("Location: http://site 2");
exit();
}
well I´m not sure if the session is the right way how to do it
Thanks a lot.

It's not possible and not recommended to do it with a session. Because after a while the session gets destroyed automatically.
I rather you to use cookies.
The code is similar to your code. The only difference between sessions and cookies is that cookies can be setted for lifetime

You're using this code which is wrong.
$_SESSION["header"] = " "
$_SESSION["header"] = " " means to assign ' ' to $_SESSION["header"]
It should be:
$_SESSION["header"] == " "
$_SESSION["header"] == " " means $_SESSION["header"] is equal to ' '
== is for comparison, = is for assignment, and === is for identical or same type.
More information at http://php.net/manual/en/language.operators.comparison.php.

Related

how can I define how long a client was visiting a site

I have a site and I want to measure how long a client was connected to my site, one hour or two hour... or? how is it possible?
can someone help me in this regard.
it will be appreciated.
As mentioned in the comments, it's best to use analytic software but if you are looking for something simple (or just learning experience)
<?php
session_start();
if(!isset($_SESSION['sessionId'])) // No session, first time (subject to session timeout)
{
mysqli_query("INSERT INTO visitor_sessions(`started_on`, `last_checkin`) (" . time() . ", " . time() .")");
$_SESSION['sessionId'] = mysqli_insert_id(); // start the 'visiting session'
}
else
{
mysqli_query("UPDATE visitor set `last_checkin` = " . time() . " WHERE id = " .$_SESSION['sessionId']); // Update last checkin
}
?>
visitor_sessions is a table with 3 columns, id, started_on and last_checkin (timestamps).
You can include this script in your pages thus updating last check_in with each new page opened or have jquery call it every x seconds to maintain time even if they just view a page.
PS: Code was not tested but this is the general idea

unset somehow destroys all absolutely different sessions

I have one serious problem.
There is a little PHP system, which contains admin panel and customer panel.
These panels must be functioning independently from each other.
For example - if admin logs out, customer must stay inside, etc.
There is my logout.php script (which is called by logout button javascript handler):
<?php
require_once("./setup/additional_functions.php");
require_once("./setup/mysql_settings.php");
session_start();
$functionName = filter_input(INPUT_GET, "functionName");
if($functionName == "logoutAdmin") {
initiateLogout("um_status", "users_managers", "um_id", $_SESSION['admin_id'], "admin");
} else if($functionName == "logoutCustomer") {
initiateLogout("customer_visit", "users_customers", "customer_id", $_SESSION['cust_id'], "../customer");
} else {
echo "Unknown error!";
}
function initiateLogout($loginTime, $tableName, $id, $sessionName, $backPage) {
$sqli = new sqlSettings();
$sql = "SELECT ". $loginTime ." FROM ". $tableName ." WHERE ". $id ." = ". $sessionName;
$result = $sqli->setConnection()->query($sql);
$user = $result->fetch_array();
$timestamp = $user[$loginTime] - 300;
$sql = "UPDATE " .$tableName. " SET " .$loginTime ." = ". $timestamp. " WHERE " .$id ." = ". $sessionName;
$result = $sqli->setConnection()->query($sql);
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 50000, '/');
}
unset($sessionName);
//redirect_to($backPage);
echo "../" . $backPage;
}
?>
Data inside $_SESSION['admin_id'] and $_SESSION['customer_id'] - absolutely different! But anyway - when I hit button (for example) on admin side - customer also logs out!!! It shouldn't be like this.
How to avoid this? Will be very thankful for any help!!
You don't need to be setting $_SESSION to an empty array.
You need to be setting the respective $_SESSION key to null or insetting it.
For customers this would be unset($_SESSION['cust_id']) and for admin this would be unset($_SESSION['admin_id'])
Your current code destroys the whole session which logs both customer and admin accounts out.
Well, I think my mistake was in testing whole system on my local computer. Cause if you do the same - session is being created during one browser and one pc. And it doesn't matter by whom you're logged in. After I placed my system on remote server and tested my old code from different "points" - everything works perfect.

Session variables not transferring between pages [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
I am making a simple login page however my $_SESSION variables are not transferring between pages. I've read numerous other posts about session_start() at the beginning of each page, folder writing priveleges, session_write_close(), etc., but none have worked. The session_write_close() doesn't make a difference withor without so I just left it in. All of the code below works fine as I have left out code below and above such as where $login_fail comes from.
Currently I set the the $_SESSION variables as shown in the code below:
if($login_fail == "")
{
$query = "SELECT first_name, last_name, email_address,password FROM user_info WHERE email_address = '$email_address' AND password = '$password'";
$result = mysql_query($query);
if(!$result) die ("Database access : " .mysql_error());
elseif (mysql_num_rows($result))
{
$row = mysql_fetch_row($result);
$token = "$email_address";
$token1 = "$password";
echo "token: $token, token1: $token1, row[1]: $row[1], row2: $row[2] </ br>";
if($token == $row[2] && $token1 == $row[3])
{
session_start();
$_SESSION['first_name'] = $row[0];
$_SESSION['last_name'] = $row[1];
$_SESSION['email_address'] = $row[2];
$_SESSION['password'] = $row[3];
$_SESSION['check'] = md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']);
//print_r($_SESSION);
session_write_close();
header("Location: http://127.0.0.1/websiteproject/test.php");
}
else die("Invalid username/password combination");
}
}
else
{
echo "Login failed. Please try again.";
}
I have done print_r($_SESSION) and it prints all the correct information.
The session variables are then called again in my test.php just to see what happens in really simply code.
session_start();
print_r($_SESSION);
The result is an empty array.
When I go to the easyphp temp file where my sessions are written I always find two files: the original one with all the correct information and a new one with no information. It seems as if when I call the second session_start() it is literally starting a new session and not recalling the current session.
I try to do my research to give as much info as possible and not waist people's time. Any ideas are greatly appreciated. Odd is that this was working a few days ago and then I started making changes to files deeper into the program and this happened. So I made the test.php just to find out more about the transfer problems.
You cannot call session_start() once any data or whitespace has been output to the browser.
In the code you posted, you are calling echo "token: $token, token1: $token1, row[1]: $row[1], row2: $row[2] "; prior to calling session_start() which will not start the session.
Add error_reporting(E_ALL); ini_set('display_errors', 1); to the beginning of your script and you should see a warning about not being able to start the session because output has already been sent.
Try moving the session_start(); call to the very beginning of the file.

header location not working - but definitely being passed over

Annoyingly my log in check script is not redirecting where I tell it to.
I know it hits the if statements correctly because I put in echos to check it did.
It is blatantly skipping to header as during the first circumstance it echos "- blanks" as it should then also "Did it even get this far?"
So on that basis I know it hits the header - its just plain ignoring it and I can not for the life of me fathom why.
Im sure its simple and I'm missing something ridiculously obvious but I just cant see it.
Any suggestions?
// makes sure they filled it in
if($_POST['frmLogin-username'] == "" || $_POST['frmLogin-password'] == ""){
echo " - blanks";
header('Location: ?page=landing&action=login&message=1');
echo "Did it even get this far?";
die;
}
else{
// checks it against the database
$query = mysql_query("SELECT * FROM shops WHERE shopUsername = '".$_POST['frmLogin-username']."'");
//Gives error if user dosen't exist
$count = mysql_num_rows($query);
if ($count == "0"){
echo " - no user";
header('Location: ?page=landing&action=login&message=2');
die;
}
else{
while($row = mysql_fetch_array( $query )){
//gives error if the password is wrong
if ($_POST['frmLogin-password'] != $row['shopPassword']){
echo " - wrong pass";
header('Location: ?page=landing&action=login&message=3');
die;
}
else{
// if login is ok then we add a cookie
$hour = time() + 3600;
setcookie(shopusername, $_POST['frmLogin-username'], $hour);
setcookie(shopid, $row['shopId'], $hour);
//then redirect them to the shop panel
header("Location: ?page=shop");
die;
}
}
}
}
EDIT: The issue was to do with the way I load all my pages within index.php by calling includes which I am now investigating
I have moves this process page to its own php file and it now works fine
First of all: you can not send headers after having output anything using echo like Sam said in his comment.
Secondly, to send a redirect, the URL after the Location: must be absolute, like http://localhost/page/to/redirect/to.php.
EDIT
Corbin actually beat me to my answer for about 10 seconds ;-)
The issue was to do with the way I load all my pages within index.php by calling includes which I am now investigating I have moved this process page to its own php file and it now works fine
You can use window.location, just echo it within PHP.

Login script with PHP and mySQL - lock pages if not logged in using cookies

I created a login script (with much help of a tutorial) that protects the maintenance parts of my website. It works and when there's a succesful login, cookies are made. The problem is that the used tutorial offers a way to check if there are (valid) cookies saved on the users computer for the pages that are meant only for registered people, but it results in nothing (so probably an error). I can't find what's wrong, so I hope you can help me fixing it. Cookies stay for half an hour by the way.
<?php
// connect to db
include('connect.php');
// page of login script, used when no/wrong cookie is found
$login_pagina = "login.php";
$sql = "SELECT * FROM members WHERE username='".$_COOKIE['username']."'";
$resultaat = mysql_query($sql) OR die ("Couldn't connect to MySQL");
$aantal = mysql_num_rows($resultaat);
if ($aantal == '0') {
// cookie and databasevalues are not the same
echo "Click here to login.";
} else {
$login = mysql_fetch_object($resultaat);
if ($_COOKIE['password'] != $login->password) || ($_COOKIE['username'] != $login->username)) {
echo "Cookies couldn't be combined";
} else {
echo "you're logged in!";
}
}
?>
(As the tutorial was in Dutch I translated the comments and some text. Some variables are still in Dutch, but I think it's clear enough.)
So you get a blank page?
No output at all?
If so , there's must be an error , try enabling error_display (check your php.ini file).
Few things:
1. The query is checking if the cookie's value is a username in the "members" table.
So make sure that it contains members.
2.Use firebug or chrome to check if the cookie is really exists and if its value is a member's username.
5.Instead:
$login = mysql_fetch_object($resultaat);
if ($_COOKIE['password'] != $login->password) || ($_COOKIE['username'] != $login->username)) {
Try: (The condition need to be "AND" not "OR" ... there's no logic if not)
$login = mysql_fetch_array($resultaat);
if ($_COOKIE['password'] != $login['password']) AND ($_COOKIE['username'] != $login['username']) {
replace: if ($aantal == '0') {
($aantal == 0) {
It's not an error but still , this function return a number , so treat it as a number.

Categories