fSazy
fSazy

Reputation: 336

Best regular expression for matching URI in http header

I have http header string

GET /phpmyadmin/sql.php?db=monitor&table=boundries&token=08b1cd52b3bc0068ea470988e292f54d&pos=0 HTTP/1.1
Host: mylocalwebhost.net

The above is a sample string which I will recieve through a file. In each string I need to check for validity for the first line.

The 'GET' portion can be any of GET PUT POST DELETE.

How can I match the first line using a regular expression. Please some one provide me with a valid regex that I can use with php preg_match()

Upvotes: 2

Views: 1340

Answers (2)

Joseph Collins
Joseph Collins

Reputation: 461

Try with this:

$string = '//phpmyadmin/sql.php?db=monitor&table=boundries&token=08b1cd52b3bc0068ea470988e292f54d&pos=0';

$parts = explode("&", $string);
$parts = array_map("trim", $parts);
foreach($parts as $current)
{
    list($key, $value) = explode("=", $current);
    $data[$key] = $value;
}

echo '<pre>';
print_r($data);
echo '</pre>';

The result is:

Array
(
    [//phpmyadmin/sql.php?db] => monitor
    [table] => boundries
    [token] => 08b1cd52b3bc0068ea470988e292f54d
    [pos] => 0
)

Upvotes: 0

Vasili Syrakis
Vasili Syrakis

Reputation: 9611

Regex

/^(?:GET|PUT|POST|DELETE) (.*?) \S+$/m

Code

<?php
$re = '/^(?:GET|PUT|POST|DELETE) (.*?) \S+$/m'; 
$str = 'GET /phpmyadmin/sql.php?db=monitor&table=boundries&token=08b1cd52b3bc0068ea470988e292f54d&pos=0 HTTP/1.1
        Host: mylocalwebhost.net'; 

preg_match($re, $str, $matches);
echo $matches[0];

Upvotes: 2

Related Questions