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.

NOTE:

  • 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.

<?php
    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:

http://www.example.com?intro=Hello%20John&swap_copy=information%20about%20printing%20values%20from%20URL%20strings

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      -> http://www.example.com/test1/test2/test3
System URL     -> http://www.example.com/node/1234

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.