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.
4
Answers
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’
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 aphp
"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
check.php
All the
.htaccess
directive does is makecheck.php
happen before every script call — So technically you COULD just includecheck.php
at the top of every file .. But I find this a more complete, elegent solution.You can do it with
$_SERVER['HTTP_REFERER']
but it can be fake/dummy made.You can check with php_sapi_name() if you are running on CLI.
This example will only allow scripts from CLI.
You can reverse the condition to make it only running for web server.