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

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.

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.

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'].'"' : '' ?>>

Related

How to use $_GET variable (index.php?cat=about)

I know there must already has this question been asked but I didn't find the answer cause I don't know how to search exactly what I want.
So, I wanna make such a link http://example.com/index.php?cat=about where I should insert some about info. But I don't know how to make a page with this URL containing ? symbol and other stuff, or how to edit that page then, where to edit and etc.
About Us
I've also made cat.php file but what next?
In your index.php file you can use the following:
if(isset($_GET['cat']) { // means if the user use the url with ?cat=something
echo "<1>About {$_GET['cat']}</h1>"; //print the about of the cat as html
}
OK, Suppose you've two PHP files. page_a.php & page_b.php.
page_a.php
<?php
echo "<a href='page_b.php?cat=about'>Click Me</a>";
page_b.php
<?php
print_r($_GET); // Show all GET contents
echo $_GET['cat']; // Show what content exist in 'cat' part of url
Hope, this will clear your doubt of how to send data in url from one page to another using GET mehtod.
To store variable data in the url, you can use the query string. This is the portion of the url that immediately follows the protocol, domain name and file path
The query string begins with ? and may contain one or more parameter parameter value pairs. The parameter and parameter value are separated by =. Each pair is separated by &.
Let's suppose you do development for a tourism company called Gi Tours which provides content in 3 different languages. Because site visitors will want to be able to select their preferred language, you can provide flag images that will indicate a certain language and wrap those flags with the appropriate hyperlinks. Rather than writing out the full language name, you can simply assign id numbers to represent each like this:
<?php
echo "<img src=\"img/ge.png\">";
echo "<img src=\"img/en.png\">";
echo "<img src=\"img/ru.png\">";
?>
If a visitor clicks the second flag which loads this url: https://www.gitours.ge/index.php?lang=2, your index.php code can be written to extract the value assigned to lang by using $_GET["lang"].
If you write in your index.php file:
<?php
echo $_GET["lang"];
?>
Your code will display:
2
Or on your index.php file, you can easily generate dynamic page content using $_GET array data.
<?php
if(isset($_GET["lang"])){ // this checks if lang exists as a parameter in the url
$lang=$_GET["lang"]){ // $lang will equal the value that follows lang=
}else{
$lang=1; // if there was no lang parameter, this sets the default value to 1
}
if($lang==2){
// show English content
}elseif($lang==3){
// show Russian content
}else{
// show Georgian content
}
?>
This is, of course, a simplified demonstration; other techniques can be used to interact with the $lang value.
#Lasha Palelashvili let suppose below example:
above you are sending only one input parameter cat through url to the index.php file at server side so when you send this data from url it will send by get method by default, if you want to get this url info(input parameter) at the php side so $_GET will help you to fetch that info $_GET is actually an array which stores your input parameter as key and input parameter's value as value for your case("index.php?cat=about") $_GET array will contain value like below:
$_GET = array("cat" => "about")
now at the server side you can easily get the value like:
//index.php
<?php
$cat = $_GET["cat"];
echo $cat;
?>

Outputting cookie in Laravel-5/Blade

I have cookie date stored in a serialized array which I would like to access via the Blade template.
If a cookie value is set matching the current field name, then I want to show it. I am currently using the following code, but I'm not sure how to access the array value.
{{{ Cookie::has('myBookingDetails') ? Cookie::get('myBookingDetails') : old('name') }}}
The value of the myBookingDetails cookie looks like this:
a:4:{s:4:"name";s:13:"Joe Bloggs";s:5:"email";s:29:"joe#domain.co.uk";s:5:"phone";s:11:"0777777777";s:3:"reg";s:6:"123456";}
How can I access the "name" value via Blade?
The data is serialized. You need to use unserialize() function to get the data.
$data = unserialize(Cookie::get('myBookingDetails'));
$name = $data['name']
Check for existence before use.
Don't know if previous answer solved your enigma, but I could give some help.
I fought with a similar case. Seems that in template - in laravel 5.1 - I couldn't access directly to cookies:
Cookie::get('cookiename') simply returns null
cookie('cookiename') returns a Symfony\Component\HttpFoundation\Cookie, but $cookie->getValue() returns (again) null.
The good old $_COOKIE['cookiename'] returns the right cookie, so you could simply go with unserialize( $_COOKIE['myBookingDetails'] )['name']; !
PS: It should be better to handle with cookies in controller and pass a normal variable to the view!

Usage of "isset" function

Although I visit php documentation , I didn't understand usage of "isset" function .
1 - for example in a php tutorial book author wrote a text with this context : when we create a form in a first.html and we want to use from form information in second.php , we must use these 2 pieces of code :
if(!isset($_GET['q']))
die("The Search key word is not set !!!");
$key = $_GET['q'];
if($key == "")
die("The Search key word must be entered !!!");
but I don't understand what is difference between these 2 codes ?
2 - for another example I saw this code for checking that a bottom is clicked or not :
if(isset($_POST['login_btn']))
{
....
}
but I don't understand why does it check that a bottom is clicked or not ?
$key="";
isset($key) //This evaluates to true.
The string is empty, but the variable is defined. The isset() function returns true, even for an empty string.
Perhaps you would like to use empty() instead, which has a broader range of conditions that evaluate to false.
isset checks to see if a given variable or index exists. If you assume that a variable exists and it doesn't, PHP generates a notice. All you're doing by using isset is suppressing possible notices -- which is good practice.
The difference is, in one instance the form was not submitted, in the second instance, the form was submitted, but with a blank value.
You wouldn't want to process a form on your page if the form has not been submitted yet.
There may also be multiple forms on one page, so you might check the button value to find out which form was submitted.
This function is quite simple
As on php.net:
Determine if a variable is set and is not NULL.
In your case, the isset function checks of your post variable is empty or not
$key == ""; // Is $key an empty string
isset($key); // Has the $key variable been defined and not null
And just for reference, here are a few others that may be useful
empty($key); // Is $key and empty value (0, false, null, "", array())
$key == false // Is $key a falsey value (0, false, null, "", "0", array())
$key === false // Is $key a false boolean (false)
I'm just going to dissect your code a little bit..
isset
if(!isset($_GET['q']))
die("The Search key word is not set !!!");
Would typically be used to see if a variable in a URL is set so something like this:
http://mysite.com/index.php?q=1
Would have $_GET['q'] set and isset($_GET['q']) would come back true
$key==""
$key = $_GET['q'];
if($key == "")
Would check to see if $key is empty. Using my previous example URL, $key would not be empty or blank, it would be 1.
Why check for a button press
The script that processes your form needs to know that it is being accessed after the form that way it does not error out. This is where you would want to make sure that the form submit button was pressed. As this is confusing, here is an example:
Say you want to insert a tag for your blogging system into a database you might have code that looks like this:
AddTag.php
<form name="addtag" method="process.php" action="post">
<input type="text" name="tagname" />
<input type="submit" name="submittag" />
</form>
process.php
<?php
if ($_POST['submittag']) {
//INSERT query
}
?>
As you can see, if process.php is accessed without the AddTag form being accessed first, the script would not try to insert your tag.
Everyone here has already explained to you what the isset() function checks for (that being if a variable is set or not), but I think what you're really asking about is how $_GET[] and $_POST[] work. You're going to need to look more at the form that feeds this code. Read about what $_GET[] and $_POST[] variables are and I think this code will make a lot more sense to you.
For instance, your second example checks to see if the value named login_btn was sent via post method. If it was, then it runs the ... code block.

How to add a $userid onto an Html Link

Is it possible once I have retrieved a userid from a MySql database, for example, $userID, to then use that as a parameter in a HTML link, for example;
<href="http://www.site.com/?110938">
Thanks.
In PHP, anything you echo is sent to the browser. So you can simply echo that variable.
echo $userID;
Or to put it in the link:
<href="http://www.site.com/?<?php echo $userID ?>">
Of course that means you're trusting that $userID will contain valid data (and not some malformed HTML attempting to break your site and ruin your user's lives).
If it should always be a number, you can keep out potential bad data by forcing it to be an integer:
<href="http://www.site.com/?<?php echo (int) $userID ?>">
I believe what you are looking to do is use the GET method of retrieving data.
The GET method (as opposed to post) pulls all of the parameters out of the URL. For example, lets take a google maps search url:
http://maps.google.com/maps?q=Empire+State+Building,+NY&hl=en
Let us break down this URL:
http://maps.google.com/ - this is the location of the script
maps? - Maps is the name of the file that contains the script (if
they are using PHP); notice, there is a ? in the URL, indicating
that the GET method is being used. All information after the ?
pertains to the GET data.
q=Empire+State+Building,+NY& - this portion is the first GET
variable. They have decided to use the letter q as the name of
their GET variable, and the value is Empire+State+Building,+NY. The
& indicates that another variable will be specified.
hl=en - this is the second variable in their query.
If they were to use PHP to read these parameters, they would use the following code:
$var1 = $_GET['q']; //Has value Empire+State+Building,+NY as string
$vars = $_GET['hl']; //Has value en as string
If you wanted to have your user's ID be in the URL, and use that to interact with the database, the easiest way would be to use GET, such that your URL would look like this:
www.example.com/example.php?id=45828
Then in your script, you would use the following code to access that data and query the database with it:
$userid = $_GET['id'];
$query = "SELECT * FROM users WHERE userid=$userid;";
$query = mysql_escape_string( $query );
mysql_query( $query );
just pass the variable like <href="http://www.site.com/?var_name=<?php echo $userID;?>">

Want to use both GET and POST methods

I know result page that uses GET method can be bookmarked while the one using POST cannot be. I also know about the restrictions of the GET methods.
Now suppose I want to build a search engine which by default uses GET allowing users to bookmark but when the length of the search phrase exceeds the limit, switch to POST. On the server side I make use of $_GET or $_POST depending on which is set.
Is this doable?
If no, why?
If yes, please provide a brief outline.
Thanks
It is doable, no problem.
There is the $_REQUEST array that merges GET, POST, and COOKIE values but the better way would be to handle GET and POST manually in your script.
Just have your engine check both $_GET["variable"] and $_POST["variable"] and use whichever is set. If a variable is set in both methods, you need to decide which one you want to give precedence.
The only notable difference between the two methods is that a GET parameter has size limitations depending on browser and receiving web server (POST has limitations too, but they are usually in the range of several megabytes).
I think the general rule is that a GET string should never exceed 1024 characters.
Here's how you could use GET and POST in one:
<form action="myfile.php?var1=get1&var2=get2&var3=get3" method="post">
<input type="hidden" name="var1" value="post1" />
<input type="hidden" name="var2" value="post2" />
<input type="submit" />
</form>
The PHP:
print_r($_REQUEST);
// var1 = "post1"
// var2 = "post2"
// var3 = "get3"
print_r($_GET)
// var1 = "get1"
// var2 = "get2"
// var3 = "get3"
print_r($_POST);
// var1 = "post1"
// var2 = "post2"
You could use something like the following:
<?php
function getParam($key)
{
switch (true) {
case isset($_GET[$key]):
return $_GET[$key];
case isset($_POST[$key]):
return $_POST[$key];
case isset($_COOKIE[$key]):
return $_COOKIE[$key];
case isset($_SERVER[$key]):
return $_SERVER[$key];
case isset($_ENV[$key]):
return $_ENV[$key];
default:
return null;
}
}
It's also as well to be aware that using GET opens up a temptation among certain sets of users to manipulate the URL to 'see what happens' so it's absolutely necessary to ensure that your code suitably sanitises the input variables.
Of course you were doing that anyway ;-). But with get it pays to be doubly paranoid.
Myself if I'm using GET I'll generally set a cookie too and drop an ID of some sort in it, then cross-correlate that to a variable in the GET list, just to make sure there's absolutely no issues over user A manipulating the input and letting them see anything originating with user B.
Yes its doable, although (IMHO) the limit at which GET becomes cumbersome is significantly greater than the threshold at which a user interface for providing this much information becomes unusable. Also, the more complex a query you submit to a conventional search engine, the more effectively it can be resolved.
But I'm guessing you have your reasons.
The simplest way, from the information you've provided, to achieve this would be to change the form method at run time from GET to POST using javascript, e.g.
<form method='GET' id='searchform' target='search.php' onsubmit='
if (document.getElementById("searchdata")) {
if ((document.getElementById("searchdata").length >$some_threshold)
&& (document.getElementById("searchform"))) {
// 2nd if in case this moved to action for button
document.getElementById("searchform").method="POST";
}
}
return true;'>
<textarea name='searchdata' id='searchdata'>
</textarea>
<input type='submit' value='go get it'>
</form>
Which also downgrades nicely for non-javascript clients.
C.
function getQVar($key){
return isset($_GET[$key]) ? $_GET[$key] : (isset($_POST[$key]) ? $_POST[$key] : null);
}
echo getQVar("name");
Switch around $_GET and $_POST to prioritize POST over GET vars.

Categories