On a Drupal site, PHP code is enabled for Page body content. How can I get the argument and its value in PHP code? For example, I'd like to get ref
and 33002
from:
http://example.com/node/1?ref=33002
In the following code:
<?php
print arg(0);
print arg(1);
print arg(2);
print arg(3);
?>
I can get node
and 1
, but nothing about ref
or 33002
.
Thanks!
Use this:
<?php
$a=$_REQUEST['ref'];
echo "The value of the ref parameter is ".$a;
?>
You can use drupal_get_query_parameters() as follows:
$params = drupal_get_query_parameters();
if (isset($params['ref']) && is_numeric($params['ref'])) {
var_dump(check_plain($params['ref']));
}
The solution by crowicked works, but "the Drupal way" is to pass the ref value as a url argument, ie:
http://example.com/node/1/33002
Now you can access the ref value using the arg() function:
$ref = arg(2);
Of course an approach like this can only work if the ref value is always the third argument.
Even though the code above works, it is not recommended to place php scripts in the node body. It makes your site harder to maintain and debug. The day will come when an editor deletes your php node by accident, thus breaking your site.
If you have a php script that you want to run, the best way is to add a simple custom module to your site which implements hook_menu. Have a look at the Menu Example module or this hello world module to learn more about hook_menu.
Lastly, regardless of the method you choose (php nodes or a custom module), always make sure to sanitize url input, for instance with check_plain().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With