Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to secure $_SERVER['PHP_SELF']?

I am using this code below to control pagination. It's using $_SERVER['PHP_SELF'] so I wanted to know if its secure this way or what do I have to do to make $_SERVER['PHP_SELF'] secure?

<?php 

    if($rows > 10) {
        echo '<a id=nex href="'.$_SERVER['PHP_SELF'].'?pg='.($startrow+10).'">
        Next</a>';
    } 

    $prev = $startrow - 10;

    if ($prev >= 0) {
        echo '<a id=pex href="'.$_SERVER['PHP_SELF'].'?pg='.$prev.'">
        Previous</a>';
    }

?>
like image 332
ariel Avatar asked Apr 22 '12 21:04

ariel


2 Answers

You should use filter_input: http://php.net/filter_input

$phpSelf = filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_URL);

Then use $phpSelf instead of the $_SERVER['PHP_SELF'].

This is better than htmlspecialchars, but an ideal solution would be using a tool like http://htmlpurifier.org/

like image 183
alganet Avatar answered Oct 18 '22 19:10

alganet


To prevent XSS attacks, you should use htmlspecialchars() or filter_input() to escape $_SERVER['PHP_SELF']. See this question for more info.

Note also that if you start an href attribute with ? and no path, the browser will append the subsequent query string to the current request, much like a relative link would append to the same directory.

I'm assuming that you're sanitizing $prev and $startrow elsewhere. The mathematical comparisons should make them safe, but if they're coming from $_GET it's a good idea to run them through intval() before you do anything else.

like image 31
Austin Smith Avatar answered Oct 18 '22 21:10

Austin Smith