How to end a PHP session on page close - php

I have several pages inside an AJAX directory. I don't want these pages accessible directly so you cannot just type in the URL of the page within the AJAX directory and access it. I "solved" this by using a PHP session on the page that calls it as follows:
Main page:
<?php
session_start();
$_SESSION['download']='ok';
?>
and on the ajax page I have this:
<?php
session_start();
if($_SESSION['download']!=='ok'){
$redirect='/index.php'; //URL of the page where you want to redirect.
header("Location: $redirect");
exit;}
?>
The only problem is that if a user goes through the correct process once, the cookie is stored and they can now access the page directly. How do I kill the session once they leave the parent page?
thx

why use session ?
if i understood what you want:
<?php /// Is ajax request var ?
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=="xmlhttprequest") {
// do your ajax code
} else {
// redirect user to index.php since we do not allow direct script access, unless its ajax called
$redirect='/index.php'; //URL of the page where you want to redirect.
header("Location: $redirect");
exit();
}
} ?>

A really simple solution is to open up each of the files you want to protect from direct URL entry & add the following to the top:
<?php if (isset($_GET['ajax']) != true) die();?>
Now get rid of your redirect script since it's useless now. You don't need to use sessions for this. Every time you request a page, use it's direct URL, just add ?ajax=1 to the end of it.
By adding the ?ajax=1, PHP will set a key of 'ajax' to the $_GET global variable with the value of 1. If ?ajax=1 is omitted from the URL then PHP will not set a key of 'ajax' in $_GET and thus when you check if it's set with isset() it will return false, thus the script will die and not output anything. Essentially the page will only output data if ?ajax=1 is at the end of the URL.
Someone could still "spoof" the URL and add '?ajax=1' themselves, but that is not the default behavior for people or web browsers. If you absolutely need to prevent this then it will be much more complicated, e.g. using templates outside of a publicly available folder. Most other "simple" solutions will have the same "spoofing" potential.

There's really no way to accomplish this with a 100% certainty - the problem is, both AJAX and regular web browser calls to your web site are using the same underlying protocol: HTTP. If the integrity and security of your site depends on keeping HTTP clients from requesting a specific URL then your design is wrong.
so how do you prevent people from directly accessing files inside certain directories while still letting the site use them??
Create a controller file. Send all AJAX requests to this controller.
ajax-control.php
<?php
$is_ajax = true;
include "ajaxincludes/test.php";
// ... use the ajax classes/functions ...
ajaxincludes/test.php
<?php
if (!isset($is_ajax) || !$is_ajax)) {
exit("Hey you're not AJAX!");
}
// ... continue with internal ajax logic ...
If clients try to access the file directly at http://mysite/ajaxincludes/test.php they'll get the error message. Accessing http://mysite/ajax-control.php will include the desired file.

I don't think there is a surefire way to do what you are asking, since HTTP request headers can be faked. However, you can use $_SERVER['HTTP_REFERER'] to see if the request appears to be coming from another page on your site.
If the rest of the security on your site is good, the failure of this method would not grant the user access to anything they were not already able to access.

I've never tried this but maybe you could do something with jQuery's .unload() and then call a PHP page to unset() the session.

Why not (on Ajax page):
session_start();
if($_SESSION['download']!=='ok'){
$redirect='/index.php'; //URL of the page where you want to redirect.
header("Location: $redirect");
exit;
}
// do whatever you want with "access granted" user
// remove the download flag for this session
unset($_SESSION["download"]);

Related

How To Proceed File #2 Only When Accessed By File #1? I'm Using $_SESSION

I have 2 files :
// test-redirect1.php
<?php
session_start();
$_SESSION['ctrl_access'] = '81938193813819381';
// then some codes here...
?>
and this file :
// test-redirect2.php
<?php
session_start();
if ($_SESSION['ctrl_access'] != '81938193813819381') {
header( 'Location : goto-hell.php' );
}
// then some codes here...
?>
I want to have test-redirect2.php only proceed when the referrer file is test-redirect1.php.
I tried to use $_SERVER["HTTP_REFERER"] in test-redirect2.php but it doesn't show up if test-redirect1.php use header( 'Location : some-file' ); as redirect.
also, I don't want to show the ctrl_access variable to user. That's why I don't want to use POST / GET method.
so, I decided to go with $_SESSION...
but, the problem with the $_SESSION is, once I open test-redirect1.php on my browser, that variable is created then I can open test-redirect2.php and passing if condition.
how to have test-redirect2.php only proceed when the referrer file is test-redirect1.php?
thank you.
The "http referer" variable is sent by the browser. It is not a good security method for that reason, as it can be easily spoofed, however, you already answered your question as to how it is sent reliably. It is sent when you move from one page to another via a user clicking on a link.
You could probably trigger this behavior with javascript in a variety of ways such as:
document.getElementById('some_link_id').click();
The entire idea is bad. Adult sites were infamous for using this technique for security, and were easily exploited using browser plugins that let you set HTTP headers.
The session method you were using is far better.

Check if cookies are enabled without redirect

I need on each page check if cookies are enabled.And use this code.
<?php
setcookie('COOK_CHK',uniqid(),time()+60*60*24);
if(!isset($_COOKIE['COOK_CHK'])){
echo"Cookies are disabled!";
exit;
}
session_start();
?>
However on the first check it gives me false until i don't refresh the page.I include this code in each page so can not redirect every time i load the page as it reduces performance.However i want to use it even if javascript is disabled.Any suggestions?
Can you use javascript? If so, all it takes is a check at the navigator.cookieEnabled variable.
It works in most modern browsers. You can read more about it here: http://www.w3schools.com/jsref/prop_nav_cookieenabled.asp
It's not possible because Cookies are in the browser, and PHP send them when the page has render, so will be available just in the second page.
A possible way to fix this is using javascript.
If you really should do it in PHP, for some crazy reason, send all your request to a main controller and save the state using other method, for example, write a var into a file, then redirect and in the next redirections you'll know if the cookies are enabled without needed any other redirection. Example:
$file = 'cookie_fake_'.$userIP;
if( !isset($_COOKIE['COOK_CHK']) && !file_exists($file) ){
file_put_contents($file, 'dummy');
setcookie('COOK_CHK',uniqid(),time()+60*60*24);
header('Location:/');
exit;
}
if(!isset($_COOKIE['COOK_CHK'])){
setcookie('COOK_CHK',uniqid(),time()+60*60*24);
echo"Cookies are disabled!";
exit;
}
Then you should write something to clean old files every hour or so, of course you can use a cache layer or a database or anything like that instead of writing a file.
Edit: The previous code will be really f** up if the user enables cookies and refresh the page, now I've fixed so it works at the second time it refresh. Not perfect but... You really should do this using javascript.
Cheers.

Allow access to php file only if redirected

Is it possible to disallow direct access to a PHP file and allow the access only if it's redirected from other PHP file?
For example, access to loading.php should be only allowed if it's redirected from example.php page. How how can I do that?
I hope you understand what I mean. If not, please ask me, and I will try to explain better.
example.php
session_start();
$_SESSION['loading']='yes';
loading.php
session_start();
if($_SESSION['loading']=='yes'){
/all good
}else{
//bad, redirect back or whatever
}
$_SESSION['loading']=''; // clear session var
You can check referer, but it not secure:
loading.php
<?php
if($_SERVER['HTTP_REFERER']!=='http://yoursite/example.php')
die('Denied');
--
or you can set visited flag in session
example.php
<?php
$_SESSION['isVisitedExample'] = true;
loading.php
<?php
if(!isset($_SESSION['isVisitedExample']))
die('Denied');
--
or in cookie (not secure)
example.php
<?php
setcookie('isVisitedExample', 1);
loading.php
<?php
if(!isset($_COOKIE['isVisitedExample']))
die('Denied');
--
or mix this methods
Test for the variable $_SERVER['HTTP_REFERER']. (yes, the incorrect spelling is what must be used.) That variable contains the URL of the site that a user came from. The REFERER header is blank or '-' if the page is accessed directly.
The code for this would look something like the following:
if (empty($_SERVER['HTTP_REFERER']) or $_SERVER['HTTP_REFERER'] == '-') {
exit; // do nothing if hit directly.
}
// The real page logic goes here.
If you want to only allow the loading page from a specific URL, then you may test for that URL instead of testing for empty().
Please be aware that the REFERER header is sent by the browser and easily spoofed. That said, checking the referer header is useful for blocking other sites from directly loading images from your site.
Another option would be to use sessions and session variables to check that someone hit the appropriate page before the loader page.

Is there a way to prevent the post viewed by the visitor?

Supposed the page is example.com/blog/data.php. I am using file_get_contents to get the content in another script page. Now, i want to:
Forbid google search to crawl and index the data.php page.
Forbid the visitor to access it
Is there a way to achieve this?
You can redirect to another page if the request url is example.com/blog/data.php, but a far easier and more logical solution would be to move the file out of your web-root.
Edit: If you really want to keep the file inside the web-root, you can use something like this at the top of the script that you don't want to access directly:
if ($_SERVER['REQUEST_URI'] === $_SERVER['SCRIPT_NAME'])
{
header('Location: /'); // redirect to home page
}
However, this will probably not work in combination with file_get_contents (you need to remove these lines from the result), you could include the file instead.
Don't put data.php under the web root. Keep it in a parallel directory.
You can pass token via GET. Overall your way is slightly wrong. Why don't you incorporate the data.php logic in the script that is calling it.
Simply apply access restriction for authorized users only. You are able to do it in the most simple way by accessing your page using url parama as password:
example.com/blog/data.php?secret=someblah
and in the first of your file data.php do the following:
<?php
if (!isset($_GET['secret']) || $_GET['secret'] != 'someblah')) exit();
?>
However,It is recommended, don't use this from public computer becuase it is not secure but it is the primitive authentication principle.

help with PHP session_destroy();

I have several forms brought in via jQuery .ajax funciton. In the parent page I start a session like this
<php
session_start();
$_SESSION['authenticated'] = 'yes';
?>
then in the form that is loaded have a check like this:
<?php
session_start();
if($_SESSION['authenticated'] != 'yes') {
header("Location: http://www.google.com");
}
?>
I know its not the best, but it's an attempt to stop people form accessing the forms directly. The problem is that if you go to the parent page, then you can enter the form URL and get there because the session was started when you hit the parent page. How can I destroy the session or remedy this issue?
Effectively, you can't.
To make it more complicated, don't request the form URLs directly. Try to request authorize tokens per request of the main page:
If you generate the main page and you know the form to be requested beforehand, then generate tokens e.g. using md5(time().rnd()), associate each with one you your forms and save the association in your session
Then, your JS code won't request the form URLs, but a factory script using a token injected into the JS code
If you find the token in your saved association in your session, emit the form and delete the token in your session.
This way, each form can only be requested once by one preceding call of the main page.
Note, that this isn't fully safe too: If a user requests the URL of the main page using wget, he can request each form once.
You can check $_SERVER['HTTP_REFERER'] in your form .php code to see where the request is coming from. An AJAX call will set the HTTP_REFERER to the page it is called from.
if (strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) === false) {
die();
}
It's not a bulletproof solution. Any page that is publicly accessible can be retrieved by an automated script.

Categories