Header redirect if user agent equals variables using PHP

I have a script that must redirect to 403 page if user agent equals variables, but if not - must display normal page. Instead of this the script display only blank page and that's all. Please help me to solve my problem or what i'm doing wrong.

Here is the script:

<?php

 //-- Get user agent
 //-- Thanks @creditosrapidos10min for hint about strtolower() 
 $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);

 //-- BadBot variable
 $Baiduspider = stripos($useragent, "Baiduspider");
 $DotBot = stripos($useragent, "DotBot");

 //-- BadBot constant
 $BADBOT = ($Baiduspider||$DotBot);

if ($agent == $BADBOT){

    header("Location: ohno/403.php");
    exit;


} else { ?>

 Display home page

 <?php }?>

Upvotes: 1

Views: 1091

Answers (4)

Chris Ngure
Chris Ngure

Reputation: 50

I think you used $user instead of $user_agent.

And according to php manual php manual on stipos you should use triple = like ===.

Here is an example of how it should be.

<?php
    //-- Get user agent
    //-- Thanks @creditosrapidos10min for hint about strtolower() 
    $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);

    //-- BadBot variable
    $Baiduspider = stripos($useragent, "Baiduspider");
    $DotBot = stripos($useragent, "DotBot");

    //-- BadBot constant
    $BADBOT = ($Baiduspider||$DotBot);

    if ($useragent === $BADBOT){

    header("Location: ohno/403.php");
    exit;

    } else { ?>

    Display home page

    <?php }
    ?>

Upvotes: 1

Chris Ngure
Chris Ngure

Reputation: 50

Works on my browser! maybe its not the code its your browser? i am using opera browser enter image description here

Upvotes: 0

creditosrapidos10min
creditosrapidos10min

Reputation: 21

Try with $HTTP_SERVER_VARS instead of $_SERVER, in order to not to have problems with global variables.

If not, try with strtolower:

<?php

 //-- Get user agent
 $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);

 //-- BadBot variable
 $Baiduspider = stripos($useragent, "baiduspider");
 $DotBot = stripos($useragent, "dotbot");

 //-- BadBot constant
 $BADBOT = ($Baiduspider||$DotBot);

if ($agent == $BADBOT){

    header("Location: ohno/403.php");
    exit;


} else { ?>

 Display home page

 <?php }?>

Upvotes: 2

Syn
Syn

Reputation: 331

You're using stripos on $useragent but you haven't defined $useragent, you've only defined $agent. Try correcting this and trying again.

Upvotes: 1

Related Questions