Strange issue PHP session inside condition - php

I have this code:
session_start();
$i = 'NO';
if ( $_GET['page'] != 'login' ) {
$_SESSION['redirect'] = 'my-account';
$i = 'YES';
}
The logic says:
allways $_GET['page'] != "login", the block inside IF condition will be skipped...
In a URL like this: www.example.com/?page=login
The first time is OK, $_SESSION['redirect'] has no value
if I reload the page, $i still has the value "NO" (OK)
but $_SESSION['redirect'] now contains the value "my-account"
Currently, this code is everything that is written on my test url
And a strange thing more:
Chrome / Firefox (Windows) and Chrome (Mac) exhibit this behavior
Firefox (Mac) effectively ignores the block
how can it be possible?

Try below code:
<?php
session_start();
$i = 'NO';
$page = $_GET['page'];
if ( isset($page) ) {
if ($page != 'login') {
$_SESSION['redirect'] = 'my-account';
$i = 'YES';
} else {
$_SESSION['redirect'] = '';
}
}
echo $i;
echo $_SESSION['redirect'];
?>
before trying it, clear the session variable

So, your SESSION is getting set even though you think it shouldn't?
Your page is probably getting called anyway - either you have a redirect to it or an auto include, and the browser is then calling it when you yourself call the page because it's trying to load "favicon.ico".

Related

Change urls depending on landing page

I have two landing pages (homepage1 and homepage2). If I land on homepage1, the logo link needs to change to homepage1 and keep it as I go to other pages. The same goes when I land on homepage2. I tried -
if (strstr($_SERVER['HTTP_REFERER'], 'homepage1.php') !== false) {
<a href='homepage1.php'><img src='logo.jpg'></a>
}
elseif (strstr($_SERVER['HTTP_REFERER'], 'homepage2.php') !== false ) {
<a href='homepage2.php'><img src='logo.jpg'></a>
}
It works when I go to one page but anymore than one the url and logo are gone. In other words, it doesn't hold on to the url.
I need it to hold on to the url based on what landing page I land on. And it needs to hold on to the url, no matter how many pages I go to.
Is this possible?
As #DragonYen pointed out , you need to use session variable as it can be used to persist state information between page requests.
session_start();
$ref = $_SERVER['HTTP_REFERER'];
$page = explode("/", $ref);
if($page[3] == "homepage1.php") {
$_SESSION['home'] = 1;
}
else if($page[3] == "homepage2.php") {
$_SESSION['home'] = 2;
}
Now you can check for session variable home
if ($_SESSION['home'] == 1) {
<a href='homepage1.php'><img src='logo.jpg'></a>
}
elseif ($_SESSION['home'] == 2) {
<a href='homepage2.php'><img src='logo.jpg'></a>
}
put this when you no longer need the session
unset($_SESSION['home'];
session_destroy();

Do not increment on page reload

I've placed a hit counter on my page. It reads a text file, increments the number in the file, and later in the page, I output the incremented value.
$hitsFile = "hits/exps/stats.txt";
$hits = file($hitsFile);
$hits[0]++;
$fp = fopen($hitsFile , "w");
flock($fh, LOCK_EX);
fwrite($fp , $hits[0]);
fclose($fp);
My problem is that if I reload the page, the code will increment the hits. I don't want that. I thought of using session to fix that, but with session, in order the increment the hits again, I need to exit the site and visit again. I don't want that either.
I want it to increment not when I reload the page but when I revisit the page.
For example, let's say I have two-page website, Home and Contact, and on contact page I have a hit counter. I don't want the hit counter to increment if I reload(refresh) the contact page, but if I leave the contact page and visit homepage, and later revisit the contact page, I want it to increment.
In short, I don't want it to increment on page reload. Is there a way to do that?
In each of your pages, you need to write the page name in the session.
Do something like this:
$_SESSION['page'] = 'contact';
On the pages where you need to count hits, you need to check this session key.
For example, if you were on page 'contact', then $_SESSION['page'] == 'contact'.
Now when you go to visit the 'homepage':
$page = $_SESSION['page'];
if($page != 'homepage')
{
//increment your hits counter
$_SESSION['page'] = 'homepage';
}
I suggest this method, is my preferred, create in root these folders: cnt and log... then put inside cnt folder the following files cnt.php and showcnt.php...
cnt.php
<?php
##############################################################################
# Php Counter With Advanced Technology For The Prevention Of Reloading Pages #
# Version: 1.4 - Date: 13.11.2014 - Created By Alessandro Marinuzzi [Alecos] #
##############################################################################
function cnt($file) {
session_start();
global $pagecnt;
$reloaded = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
$thispage = basename($_SERVER['SCRIPT_FILENAME']);
if (!isset($_SESSION['first_go'])) {
$_SESSION['first_go'] = 1;
$first_go = TRUE;
} else {
$first_go = FALSE;
}
if (!isset($_SESSION['thispage'])) {
$_SESSION['thispage'] = $thispage;
}
if ($_SESSION['thispage'] != $thispage) {
$_SESSION['thispage'] = $thispage;
$new_page = TRUE;
} else {
$new_page = FALSE;
}
$pagecnt = rtrim(file_get_contents($file));
if ((!$reloaded) && ($new_page == TRUE) || ($first_go == TRUE)) {
$fd = fopen($file, 'w+');
flock($fd, LOCK_EX);
fwrite($fd, ++$pagecnt);
flock($fd, LOCK_UN);
fclose($fd);
}
}
?>
showcnt.php
<?php
##############################################################################
# Show Counter Results - v.1.4 - 13.11.2014 By Alessandro Marinuzzi [Alecos] #
##############################################################################
function gfxcnt($file) {
global $number;
$number = rtrim(file_get_contents($file));
$lenght = strlen($number);
$gfxcnt = "";
for ($i = 0; $i < $lenght; $i++) {
$gfxcnt .= $number[$i];
}
$gfxind = "<span class=\"counter\"><span class=\"number\">$gfxcnt</span></span>";
echo $gfxind;
}
?>
Well, then edit your index.php or other php page... and put at the beginning this piece of code:
<?php session_start(); include("cnt/cnt.php"); cnt("log/index.txt"); include("cnt/showcnt.php"); ?>
Well, then edit index.php or other php page... and use this piece of code for reading counter file:
<?php gfxcnt("log/index.txt"); ?>
It's all, I hope you'll find my answer useful :) My counter can write/read multiple php pages...
Source: my blog (https://www.alecos.it/new/101/101.php)
Add session_start(); to the top.
Now change your if to this:
if (!isset($_SESSION['lastpage']) || $_SESSION['lastpage'] != $_SERVER['QUERY_STRING') {
$hits[0]++;
}
$_SESSION['lastpage'] = $_SERVER['QUERY_STRING'];
This will basically force someone to move to another page if they want to increment the counter.
Update the hit count only if the current URL is not stored in $_SESSION['url'].
After updating the hit count, store the current URL in $_SESSION['url'].

Can you spot this PHP error? I'm stumped

Here's the scenerio of what is happening in the script:
Session is start.
$id is set to a number (tournament ID number).
Result:
User SESSION vars are reset with the ID number and the ID number's respective user data. Essentially logging the user in under a different account.
Troubleshooting:
Renaming $id to $tid stops the glitch.
Not starting the session (session_start()) stops the glitch.
Thought Process:
$id must overwrite similar variable which is inside a block which contains:
if(isset( $_SESSION['someVar'] )) {
$id = "some Value";
}
Since $id is only overwritten when session is started.
The Problem:
There is no block of code that uses that syntax.
Here's the call stack.
jointourney.php
<?
session_start();
$id = (isset($_POST['id'])) ? $_POST['id'] : false;
include("html.php");
?>
html.php
<?
if(session_id() == '') session_start();
if(!function_exists('isLogged')) include("includes/islogged.inc.php");
include("includes/autologin.inc.php");
$query = mysql_query("SELECT value FROM config WHERE name='shutdown'");
$query = mysql_fetch_array($query);
$shutdown = end($query);
if(!class_exists('ban')) include("class/ban.class.php");
$ban = new ban();
if(isLogged()){
$ban->setUsername($_SESSION['username']);
}
$user_level = (isset($_SESSION['user_level'])) ? $_SESSION['user_level'] : "0";
$ban->setIP($_SERVER['REMOTE_ADDR']);
if((strlen($shutdown) > 0 || $ban->isBanned()) && $user_level == 0 && strtolower($_SERVER['REQUEST_URI']) != "/login.php"){
if(strtolower($_SERVER['REQUEST_URI']) != "/error.php"){
header("Location: ./error.php");
}
}
?>
islogged.inc.php
File not needed, no variables set: only returns true/false.
autologin.inc.php
<?
if(!class_exists('login')) include("./class/login.class.php");
$login = new Login();
if(isset($_COOKIE['username'],$_COOKIE['password']) && !$login->isLoggedIn()){
$login->setUsername($_COOKIE['username']);
$login->setPasswordDirect($_COOKIE['password']);
if(!$login->_error){
$login->processLogin();
}
}
?>
As you see, there is absolutely no place where jointourney.$id can overwrite - since there is no other variable called $id being used.
Note: There are no variables that are being set globally (i.e. global $id)
I do not understand why this is happening, are you guys able to figure this out? Everything you see here is exactly how it looks (minus HTML).
Turn register_globals Off in your server's php.ini.

PHP Code Cleaning

Am running the following code to gather some data from my page and store it in my database, however, i need to add some extra functionality to it but i don't seem to be able to do it correctly.
The Code:
// Get Referrer and Page
if (isset($_GET["ref"]))
{
// from javascript
$referer = $_GET["ref"];
$page = ((isset($_SERVER['HTTP_REFERER'])) ? (parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH)) : (''));
}
else
{
// from php
$referer = ((isset($_SERVER['HTTP_REFERER'])) ? ($_SERVER['HTTP_REFERER']) : (''));
$page = $_SERVER['PHP_SELF']; // with include via php
}
// Cleanup
if (basename($page) == basename(__FILE__)) $page = "" ;
This script is storing $page as "/site/index.php or /site/about.php", for example. I kinda want it to store it as "Index or About" without the whole /site/ and .php part.
Thanks in advance
Use pathinfo(), for example:
<?php
$page = "/site/index.php";
$page_info = pathinfo($page);
$page_name = $page_info['filename'];
echo $page_name; //output: index
?>

Sessions are going crazy. Only Mozilla is able to process

PROBLEM
I've got an admin panel. Currently only Mozilla is able to process log ins. Browsers like Chrome, IE, Opera won't even show any message carried through sessions thus no one is able to log in any browser but Mozilla.
SOME INFORMATION
I'm using PHP 5.3.6 on my server, PHP 5.3.5 on my local
computer.
My code is Object Oriented.
ini_set("session.use_only_cookies", 1); and
ini_set('session.cookie_secure', 1); are used in construction method
of my session class.
This website on SLL
Login process: First I gather all information from form, validate and gather data. After validation if everything is right, I send this data to login method in my session class.
public function login ($user) {
global $siteSettings;
if ($user) {
$this->id = $_SESSION['id'] = $user->id;
$this->username = $_SESSION['username'] = $user->username;
$this->fullName = $_SESSION['fullName'] = $user->fullName;
$this->group_id = $_SESSION['group_id'] = $user->group_id;
$this->groupName = $_SESSION['groupName'] = $user->groupName;
$this->lastLogin = $_SESSION['lastLogin'] = $user->lastLogin;
$this->isAdmin = $_SESSION['isAdmin'] = ($user->admin == 1) ? true : false;
$this->isAgent = $_SESSION['isAgent'] = ($user->agent == 1) ? true : false;
self::$language = $_SESSION['language'] = ($user->language != "" || $user->language != NULL) ? $user->language : self::$language;
if ($user->language != "" || $user->language != NULL) {
$_SESSION['language'] = $user->language;
}else {
if (!defined(DEFAULT_LANGUAGE)) {
$browserLang = "|".$_SERVER["HTTP_ACCEPT_LANGUAGE"];
$browserLang = getStringBetween($browserLang, "|","-", FALSE);
if (!file_exists(LANGUAGES.$browserLang.".php")) $browserLang = FALSE;
}
$_SESSION['language'] = ($browserLang) ? $browserLang : DEFAULT_LANGUAGE;
}
# When 2 Update session_id
$date = new DateTime("now");
$UpdateTime = $siteSettings->session->timeOut * 60;
$date->add(new DateInterval("PT".$UpdateTime."S"));
$_SESSION['SIDUpdateTime'] = $date->format("Y-m-d G:i:s");
# UPDATE LAST LOGIN & ADD SESSION ID
# Clear Fields
members::clearFields();
members::$fields['id'] = $_SESSION['id'];
members::$fields['lastLogin'] = date("Y.m.d G:i:s");
members::$fields['lastLoginIP'] = $_SERVER['REMOTE_ADDR'];
# GET THE SALT
$saltInfo = members::getData("id", "salt", members::$fields['id']);
# SETTING SESSION ID ENCRYPTION
crypt::setKey($saltInfo->salt);
members::$fields['sessionID'] = crypt::encode(session_id());
members::$fields['sessionIP'] = $_SERVER['REMOTE_ADDR'];
members::$fields['sessionAgent'] = $_SERVER['HTTP_USER_AGENT'];
members::save();
$this->loggedIn = true;
var_dump($_SESSION);
}
}
When I dumb the data I can see $_SESSION got some values.
Just to test it, I stopped the script where after var_dump($_SESSION); (added die();) I created test.php file and tried this;
<?php
ob_start();
session_start();
echo '<pre>';
var_dump($_SESSION);
echo '<pre>';
ob_end_flush();
?>
Output is array(0) {}
But when I try exactly the same thing with Mozilla, output of test.php is the way it should be (matching with login method's result in my session class).
I have tried from my local computer and I don't experience the same
problem.
I disabled all java script and jquery codes from the page just to
have no 'maybe' in my mind.
After dumping the data, script is stopped. That's why $_SESSION variable shouldn't change. For some reason when it is on the server only Mozilla is able to show expected result while other browsers shows NULL.
At this point I really don't know what to think of about this problem to try to solve it. All I can think of is, this problem is possibly related to server configuration. But then, PHP is server side programming. PHP shouldn't display different behavior for browsers like Jquery, CSS, HTML...
I'm sorry, I can't provide admin panel link. Considering this is an active admin panel. If necessary I could install it on another domain to let you try but I believe the information I gave above explains everything.
Thank you for your help in advance.
I had a similar problem... just enable the cookies.. so that after login the code to set the sessions will be executed and the sessions will be set. may be the sessions r not able to set...
also check this http://php.net/manual/en/function.session-cache-limiter.php
If something large doesn't work, trim it down, test & debug, and build up from there.
Does this work? (Run it twice).
<?php
session_start();
echo "Session ID: " . session_id() . "<br/>\n";
if (!isset($_SESSION['test']))
{
$_SESSION['test'] = "foobar";
echo "Setting session variable: ";
echo $_SESSION['test'];
}
else
{
echo "Restoring session variable: ";
echo $_SESSION['test'];
}
If this works in all browsers, it's got something to do with your code. An empty session might have something to do with a cookie that can't be written, for example. Also set error reporting to E_ALL | E_STRICT, so you'll see everything that goes wrong.
It turns out Mozilla FireFox is able to process some data but other browsers I tried with are not and therefore they reset the whole session with each page load.
I had no problem with my local computer but on the server I had sessions problem. I don't know why session_set_cookie_params(); and setcookie(); didn't work on the server so I had to code longer version;
private static function sessionLifeTime() {
global $siteSettings;
# HOW LONG WE WANT SESSIONS
$lifeTime = intval($siteSettings->session->timeOut) * 60;
if (isset($_SESSION['id']) && isset($_SESSION['lastActivity']) && (time() - $_SESSION['lastActivity'] > $lifeTime) ) {
// SEND INFORMATION TO USER
self::logout();
}
$_SESSION['lastActivity'] = time();
}
Replacing my method with the code above solved the problem.
Thank you all for your time, concern and interest.

Categories