PHP Mobile Detection - php

I have a problem with the Mobile Detection Script.
There are two scenarios:
First the script should detect if it's a mobile or not. If mobile, than redirect to another page (this works fine).
The second query should determine, if the person is on the root page or not. If it's not the root page, the layout should be the classic one. (no redirection)
But when I add this line there won't be anymore redirection, even if I open the root page on a mobile.
I also tried to destroy the session on the google_mobile.php (redirected page) and set the $_SESSION['layoutType'] = 'mobile', but anyway the session is set to classic when I open the root page.
Thanks for your help!
Here is the script:
session_start();
require_once 'Mobile_Detect.php';
function layoutTypes() {
return array('classic', 'mobile');
}
function initLayoutType() {
// Safety check.
if (!class_exists('Mobile_Detect'))
return 'classic';
$detect = new Mobile_Detect;
$isMobile = $detect->isMobile();
$layoutTypes = layoutTypes();
// Set the layout type.
if (isset($_GET['layoutType'])) {
$layoutType = $_GET['layoutType'];
} else {
if (empty($_SESSION['layoutType'])) {
$layoutType = ($isMobile ? 'mobile' : 'classic');
} else {
$layoutType = $_SESSION['layoutType'];
}
//check if it's the root page
if ($_SERVER['REQUEST_URI'] != "/")
$layoutType = 'classic';
}
// Fallback. If everything fails choose classic layout.
if (!in_array($layoutType, $layoutTypes))
$layoutType = 'classic';
// Store the layout type for future use.
$_SESSION['layoutType'] = $layoutType;
return $layoutType;
}
$layoutType = initLayoutType();
if ($_SESSION['layoutType'] == 'mobile') {
header("Location: www.example.com/google_mobile.php");
exit;
}

I've tested your code, it seems to work as you described. I'd guess it is a session issue.
session_destroy() does not clear your previous session state in the immediate session. That means your $_SESSION would still be "dirty" in a script even if session_destroy() is the first line in it. It's safer to clear cookies from your browser instead.
One other possible problem would be query string. You're checking the REQUEST_URI and it includes any query string on URI. "/?foo=bar" is certainly not "/". You may want to check SCRIPT_NAME (i.e. $_SERVER['SCRIPT_NAME'] == 'index.php) instead.

Related

Using $_SERVER['HTTP_REFERER'] with multi referers

I am trying to (somehow) secure an Ajax - PHP connection. using the $_SERVER['HTTP_REFERER'] I need to validate the HTTP_REFERER for two pages as products.php (all products) and product.php (single product). Can I use PHP in_array() to handle this, something like:
$referers = array("https://example.com/products.php", "https://example.com/product.php");
if (#isset($_SERVER['HTTP_REFERER']) && in_array($_SERVER['HTTP_REFERER'], $referers))
{
}
If so, how can I handle the dynamic URL parameters with https://example.com/product.php ? for example if I have https://example.com/product.php?sku=96 or https://example.com/product.php?sku=300 this is not gonna work with in_array() as it is different than what are listed in the $referers even though the source are correct.
$_SERVER['HTTP_REFERER'] is not guaranteed to be set and not guaranteed to be the original referer. You might use a session variable:
//products.php and product.php
session_start();
$_SESSION['ref'] = basename(__FILE__);
//other.php
session_start();
$referers = array("products.php", "product.php");
if (isset($_SESSION['ref']) && in_array($_SESSION['ref'], $referers))
{
}
Keep in mind that if you hit the products.php and then another.php and then other.php that $_SESSION['ref'] will still be products.php, so you either want to set it in all files or unset() it in other files.
<?php
$trustedReferers = array("https://example.com/products.php", "https://example.com/product.php");
$referer = '';
if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']) {
$infos = parse_url($_SERVER['HTTP_REFERER']);
$referer = "{$infos['scheme']}://{$infos['host']}:{$infos['port']}{$infos['path']}";
}
if (in_array($referer, $trustedReferers)) {
echo "Trusted referer";
} else {
echo "Untrusted referer";
}
By the way, I suggest make changes the business logic that only restrict the domain of the referer. Then the site is easier to maintain.

php session lost after submitting form

The code below page keeps session on GET requests or refreshing browser, but when I submit a form the session data is lost.
$user=$_POST['user']; $pass=$_POST['pass'];
if ($_POST['user'])
{ if($user==$un and $pass=$pw)
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?welcome'); }
else { $msg="chybny login"; }
}
if(isset($_GET['logout'])) { session_destroy(); header('Location: '.$uri); }
$cnt=$_SESSION['cnt']+1; $_SESSION['cnt']=$cnt;
Above is the code for login which re-directs me to the welcome page as it was verified, however the session is lost. If I just refresh or repeatedly load the page without submitting, the session holds by echoing the session variable cnt (counts up 1,2,3,...)
After submitting the form, I see session is lost and too cnt variable is reset?
I usually don't work with session directly try the following, place it a the top of your script :
session_start();
$uid = $_SESSION['uid'];
$cnt = $_SESSION['cnt'];
then work with the variable instead
The problem is likely your 'and' statement. It should be &&. The condition is not going to be true.
If you're 100% sure the code is all fine and the PHP.ini is the problem, based on your comments above. Look at this link at check the settings in the .ini http://php.net/manual/en/session.configuration.php
To pass the current session to the next page... I believe is what you are asking...
You are currently not passing the session to the next page and use session_start() at the top of the next page.
Change line 4 to:
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?'.SID.'&page=welcome'); } // Where "page" is the name of the data you are retrieving
Or, you can save the session data to a cookie and then retrieve it on the next page.
You can alternately name the session when you use session_start("NameHere") on each page, however if the visitor has recently visited and the session not destroyed, they may see parse errors, if you have them enabled.
First of all, make sure that the the first thing you do on every page is to start a session (I recommend calling it once in a header file that you require on all of your sub sites).
So that you have session_start(); everywhere in the system.
Second of all, tighten up your code; make it easier to read. Something like
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$logout = isset($_POST['logout']) ? $_POST['logout'] : false;
$url = '../index.php';
if(!($logout))
{
if($userName && $password)
{
if($userName == $un && $password == $pw)
{
$_SESSION['loggedIn']=true;
$_SESSION['uid']=$Xid;
$_SESSION['message']="success";
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail, incorrect login information.";
}
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail ; username and password not submitted.";
}
header("Location: $url");
}
else
{
session_start();
session_destroy();
session_start();
header("Location: $url");
}
And if you want to display unqiue content depending on whether a user is logged in or not, then you can simply check if the login session is set or not, on each page, instead of modifying the header for that.

How to use $_SESSION with if() in PHP

I've built a mobile detection with Mobile_Detect.php and it works great. Now if a User does not want to stay on the mobile site he can click on "Desktop-Version" and goes back to the main page via a 'mobile_off.php' which sets $_SESSION['mobile'] = 'off'.
The main Site executes the following code:
<?php
session_start();
// Did the User come back from mobile.php?
if ($_SESSION['mobile'] != 'off') {
include 'Mobile_Detect/Mobile_Detect.php';
$detect = new Mobile_Detect();
// Smartphone?
if ($detect->isMobile() && !$detect->isTablet()) {
// Redirection --> echo 'JS'
echo "<script>window.location='mobile.php'</script>";
}
}
?>
The Problem seems to be that if ($_SESSION['mobile'] != 'off') is ignored or wrong. My iPhone always sends me straight back to 'mobile.php'.
Can anyone help?
Perhaps I should show you the code from 'mobile_off.php':
<?php
session_start();
$_SESSION['mobile'] = 'off';
?>
You need to first check the session variable exists or not before checking the value of session variable.
For checking if session variable is set or not try this code
if(isset($_SESSION['mobile'])
After that check the value of session variable

Tracking a page for redirection with a session variable

I am currently using a SESSION variable for redirection. Hoprfully code snippets will make it clear.
addForm.php:
if (!isset($_SESSION['myusername'])){
if (isset($_COOKIE['username'])){
$_SESSION['myusername'] = $_COOKIE['username'];
}
else{
#using a session var to redirect back to addForm.php
$_SESSION['addForm'] = 1;
header("location:loginForm.php");
}
}
LoginSuccess.php
session_start();
if (!isset($_COOKIE['username'])){
header("location:loginForm.php");
}
if (isset($_SESSION['addForm'])){
header("location:addForm.php");
}
the above works (redirects to addForm.php). My question is, are there any risks in doing it this way? is there a better way to do it? I guess i'm looking for 'best practice'.
You have some errors:
The valid header is header('Location: http://www.example.org/script.php'); notice L and full URL?
After each header('Location: http://www.example.org/script.php'); it should be exit();
You cannot rely just on $_COOKIE['username'], you need to have something from password, I mean not the password, maybe an MD5() hashed password in $_COOKIE also. And you should know not to rely on $_COOKIE that much.
In LoginSuccess.php you have to unset($_SESSION['addForm']) before redirection, addForm from session will still be set.
Personnaly, I prefer store the entry current URI in session varible. Then, when my login process are successfull, I use the stored URI to redirect the user to the previous page.
Pseudo Code
if (!isset($_SESSION['userloginobj'])) {
$_SESSION['callbackuri'] = get_current_url_depending_of_your_process();
header('location:' . get_base_url() . 'index.php?do=login');
exit(0);
}
elseif ('login' == get_param('do')) {
// Show the login form
if ( is_login_successfull() ) {
$_SESSION['userloginobj'] = "userinfo";
header('location:' . $_SESSION['callbackurl']);
exit(0);
}
}
else {
// Normal process
}
But your proccess seems to be a good start if you don't use a framework.

cookie won't set

This is a question regarding an old one of mine: cookie won't unset:
cookie wont unset
where I had problems unseting the cookie (but it was set 'properly'),
Now that the problem is solved; the cookie doesn't seem to SET
cookie 'set': (does not work)
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
cookie check: (seems to work)
function sesion(){
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else{ return false;
}
}
cookie unset: (works)
function cerrar_sesion(){
session_start();
$_SESSION['logueado']= false;
$_SESSION['id']= NULL;
session_unset();
session_destroy();
setcookie("id",false,time()-3600,"/");
setcookie("alias",false,time()-3600,"/");
unset($_COOKIE['id']);
unset($_COOKIE['alias']);
}
What happens is that login is working only through $_SESSION so after 30 minutes of no activity the user is no longer logged in,
Any idea what I'm doing wrong? Thanks a lot!
As stated above you cannot read a cookie from the same page as it is set. I see you have tried tricking this using ajax but i do not believe that would be a valid trick as Ajax calls do not change the state of the page you are still on. so you can either do a full refresh or redirect OR at the same time you use setcookie you can also define the values you need in $_COOKIE so its available on the same page. like this:
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
$_COOKIE['id'] = $data['id'];
$_COOKIE['alias'] = $data['nombre'];
set cookie lines work fine with me.
as for }else if(isset($_COOKIE['id']) && i
since you return if you remove the else here is still okay, if there was no return above you would have to keep the else here in order not to evaluate this block
generally speaking I am not sure that elseif is the same with else if in all cases
The way the function session is build will act like this:
On the first load it will show: no cookie, no session because you cannot see a cookie until reload (which I guess you already know).
-On second load you will see cookie alive session set.
-after the second load you always see session is set.
All I want to say that session works exactly as expected to work, so I don't really see any problem.
<?php
$data='Hello';
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
session_start();
function sesion()
{
if(isset($_SESSION['id']) && isset($_SESSION['logueado'])
&& $_SESSION['logueado'] == true)
{
echo 'SESSION IS SET<br>';
return true;
}
if(isset($_COOKIE['id']) && isset($_COOKIE['alias']))
{
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
echo 'COOKIE is alive and session set'.$_SESSION['alias'].'<br>';
return true; //THIS IS NEVER RETURNING TRUE
}
else
{
echo 'NO SESSION, NO COOKIE YET, WAIT UNTIL REFRESH<br>';
return false;
}
}
sesion() ;
?>
Try removing the path parameter from your setcookie() calls, maybe that's the issue.
Also, did you check that $data actually contains any data?
Propably you have really known problem with setting cookies and you have disabled error reporting about warnings.
Just try:
error_reporting(E_ALL);
You will propably see at your page something like "Cannot modify headers. Headers already sent". That because you need to SET cookies before you display anything on your page. So solution to resolve your problem is to implement your code to SET cookies at the bottom of your page or use ob_start/ob_clean.
Let me know if it helps :)
According to the "setcookie()" implementation in PHP, the cookie value check will not work until you move the control from the page that you are creating the cookie. So, your "SET" will create the cookie in one page and "sesion()" should be called from other page to check the value of the cookie that you set. Try it and hope it helps!
Try the following approach (please refine this as per your need). What I am trying here to refresh the page itself after setting the cookie and the "sesion()" function is a dynamic function that may or may not have any arguments. So, when you pass any argument to it, the the cookie will be set, otherwise it will be checked for existence. An accompanying function with func_num_args() is func_get_args(). It will help you to sanitize the expected arguments in the function.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("log_errors", 0);
session_start();
function sesion(){
// func_num_args() number of arguments passed to the function
if (func_num_args() == 0) { // if no arguments were passed, means the page is refreshed and cookie won't be set further
if(isset($_COOKIE['id']) && isset($_COOKIE['alias'])){
$_SESSION['logueado'] = true;
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['alias'] = $_COOKIE['alias'];
return true; //THIS IS NEVER RETURNING TRUE
}
if(isset($_SESSION['id']) && isset($_SESSION['logueado']) && $_SESSION['logueado'] == true){
return true;
}
else {
return false;
}
}
else { // if number of args > 0, means you need to cookie here and refresh the page itself
global $data; // set this to global as the $data will be available outside of this function
setcookie("id",$data['id'], time()+3600*24*30,'/');
setcookie("alias",$data['nombre'], time()+3600*24*30,'/');
/**
* refresh the page by javascript instead of header()
* as header already being sent by the session_start()
*/
echo '<script language="javascript">
<!--
window.location.replace("' . $_SERVER['PHP_SELF'] . '");
//-->
</script>';
die();
}
}
sesion(1); // passed an argument to set the cookie
?>
I think you will face issue with the JavaScript section, as it will change the page URL and I guess you are trying to include this script into the pages. So, I will take the help of call_user_func() and the final "else" part after the setcookie() lines will be changed with the following line:
call_user_func("sesion");
Hope this will make sense now.

Categories