Home > Enterprise >  PHP detect if connection is browser or script
PHP detect if connection is browser or script

Time:11-10

I am trying to prevent users from connecting to certain pages with a script. Thus, is there any method I can use to detect if a connection to a specific web page is a client browser versus an automated script?

I know certain headers can be spoofed, but is there another mechanism I can use; say like if unable to set a sesseion_start or setCookie. Do those return true/false values if able or unable be to be set?

Something like:

$sessionID = session_id() ;
$isSet = setCookie('cookieName',$sessionID, [ .... ]) ;
if ($isSet == false) {
   ... do something to kill the session
   ... or do something to redirect
}

Is this even possible? And even if it is, I know this probably isn't reliable, but what would be a better or more reliable method?

And to clarify, detect if its a script and if so, kill it before even serving the rest of the html page.

CodePudding user response:

If you are trying to prevent pages from being called entirely, you can reliably do this with a combination of using an .htaccess file and a php "check" file .. This will check to see if the requested file came from your scripts, or an outside source. Make a directory, and put your "hidden" script files in it along with the following 2 files:

.htaccess

php_value auto_prepend_file check.php

check.php

<?php
    if( !@$_SERVER["HTTP_X_REQUESTED_WITH"] ){
        header('/page_404.php'); // Or whatever you want it to do.
        exit;
    }

All the .htaccess directive does is make check.php happen before every script call -- So technically you COULD just include check.php at the top of every file .. But I find this a more complete, elegent solution.

CodePudding user response:

You can check with php_sapi_name() if you are running on CLI.

This example will only allow scripts from CLI.

if (PHP_SAPI !== php_sapi_name()) {
    die('CLI only');
}

You can reverse the condition to make it only running for web server.

if (PHP_SAPI === php_sapi_name()) {
    die('Web Server only');
}

CodePudding user response:

You can do it with $_SERVER['HTTP_REFERER'] but it can be fake/dummy made.

<?php

    if (isset($_SERVER['HTTP_REFERER']) && strtolower(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST)) === 'example.com') {
     //your code
    }else{
        die('Bots are not allowed!');
    }

CodePudding user response:

You can use UserAgent

(You can see how to get it here : How to get user agent in PHP)

This will let you know user web browser which -I assume- will be different for 'scripts'

  • Related