tags:

views:

232

answers:

4

How can you use the part after the question mark in the url which comes as a output of the following variable?

$_SERVER['HTTP_REFERER'];

I run unsuccessfully

if (0 !== $_GET['question_id'] && isset( $_GET['question_id'] ) ) {                                              
    $result = pg_execute( $dbconn, "query_fetch", array( $_GET['question_id'] ) ); 
}
if (isset( $_SERVER['question_id'] ) ) {
    $result = pg_execute( $dbconn, "query_fetch", array( $_SERVER['question_id'] ) ); 
}
                                                        // problem here!
+1  A: 

I think that you may want to use a page's referer.

http://archives.devshed.com/forums/php-windows-119/get-referer-with-php-2329588.html

mauro.dec
Please, see the edit in the question. Thank you for your answer which put me in the right track!
Masi
+1  A: 

You can get the $_GET equivilant of the Referer by using:

$parts = explode("?", $_SERVER['HTTP_REFERER']);
$get = parse_str(end($parts))

Whenever you use the variable $_SERVER, make sure that you are using one of the predefined variables. $_SERVER['question_id'] isn't likely to be in the $_SERVER array.

......
// These variables aren't normally present:
if (isset( $_SERVER['question_id'] ) ) {
    $result = pg_execute( $dbconn, "query_fetch", array( $_SERVER['question_id'] ) ); 
}
Chacha102
Note that the query can also contain a plain `?`.
Gumbo
+1  A: 

If you want to extract the URL parameters of an URL, try the parse_str function:

$query = preg_match('/\?([^#]*)/', $url, $match) ? $match[1] : '';  // extract query from URL
parse_str($query, $params);


Edit    Here’s an example:

$url = 'http://localhost/?foo&bar=&baz=quux';
$query = preg_match('/\?([^#]*)/', $url, $match) ? $match[1] : '';
parse_str($query, $params);
var_dump($params);

Output:

array(3) {
  ["foo"]=>
  string(0) ""
  ["bar"]=>
  string(0) ""
  ["baz"]=>
  string(4) "quux"
}
Gumbo
Please, see my reply to your answer.
Masi
Please, see the edit in my reply to your answer.
Masi
A: 

Reply to Gumbo's answer

I understand your answer as follows

$pattern = '/\?([^#]*)/';
$subject = $_SERVER['HTTP_REFERER'];
$query = preg_match($pattern, $subject, $match) ? $match[1] : '';  // extract query from URL
parse_str($query, $params);
$question_id = explode( "=", $query );           // to get the parameter
echo "This is the output: " . $question_id[1];

How can you access the variable $params without the use of explode?

I run the following commands unsuccessfully

print_r( $params );
var_dump( $params );

The former gives me Array(), while the latter nothing.

Masi
`$params` is aready an associative array of the URL parameters.
Gumbo