Print values from URL query string with PHP

Below is a way to get some values from a URL string and insert them into your page. This can be useful for creating things like email campaigns with 'call-to-action' links which send users to a single landing page which can be personalised.


  • it's not good practice to include raw data in your URL strings and they should be encypted
  • it's not recommended that you use the PHP text format on Drupal sites
  • there is a more 'Drupal' way of doing this if you know the order of the values in the URL string - see this solution at the bottom of the page.

Getting values from URL string by parameter name using PHP

You will need to enable the PHP code format if you are going to be inserting the following code into something like your body field.

    if ($_REQUEST['intro']) {
        $intro = $_REQUEST['intro'];
    } else {
        $intro = 'Welcome';
    if ($_REQUEST['swap_copy']) {
        $swapCopy = $_REQUEST['swap_copy'];
    } else {
        $swapCopy = ' Drupal development tips';

<?php print $intro; ?>, thanks for visiting Drupal Den for <?php print $swapCopy; ?>.

Using a URL such as:

Will result in the below copy appearing on the page:

Hello John, thanks for visiting Drupal Den for information about printing values from URL strings.

If no URL strings are included the default values will be used and will return:

Welcome, thanks for visiting Drupal Den for Drupal development tips.

The Drupal way of getting values from URL string with PHP

You can use the below method to retrieve the values but you will need to know the order in which they appear in the URL string. For instance if you have a URL like:

Clean URL      ->
System URL     ->

You can get the values using the arg() function, examples below:

$ref1 = arg(0);     -> node
$ref2 = arg(1);     -> 1234

$ref3 = arg(0, drupal_get_path_alias());     -> test1 
$ref4 = arg(1, drupal_get_path_alias());     -> test2 
$ref5 = arg(2, drupal_get_path_alias());     -> test3
Justin Chevallier

Justin Chevallier

Avid Drupal site builder & user for +10 years.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.