darkhorse
darkhorse

Reputation: 8772

How do I get a URL parameter in a PHP template?

Let's say my URL is the following:

https://www.example.com/downloads?query=RobinHood

In my template (.phtml file), I have the following input:

<input type="text" placeholder="Query for books" name="query">

What I want to do is check if the URL parameter called query actually exists, and if it does, I want to put it as the value for the input.

How can I do this? Thanks for any help.

Upvotes: 1

Views: 371

Answers (2)

Ivan86
Ivan86

Reputation: 5708

Since .phtml is an extension used for php2, here's what the docs say:

Any component of the GET data (the data following a '?' in the URL) which is of the form, word=something will define the variable $word to contain the value something. Even if the data is not of this form, it can be accessed with the $argv built-in array

So based on this, php2 will automatically create variables for the GET data:

https://www.example.com/downloads?query=RobinHood

$query    // should contain "RobinHood"
$argv[0]  // should contain "query=RobinHood"

To check if a variable has been set you can use IsSet() function:

The IsSet function returns 1 if the given variable is defined, and 0 if it isn't.

if( IsSet($query) )
{
    //...
}

Note: All of the above is purely based on docs. I haven't tested this.

Upvotes: 1

Amir MB
Amir MB

Reputation: 3418

You can check the query parameter from $_GET variable:

<input type="text" placeholder="Query for books" name="query" <?php echo isset($_GET['query']) ? '"value"="'.$_GET['query'].'"' : '' ?>>

Upvotes: 0

Related Questions