I'd like to create a link that changes a PHP $_GET variable. For example:
URL: http://site.com/index&variable=hello&anothervariable=dontchangeme
Click me
(after click)
URL: http://site.com/index&variable=world&anothervariable=dontchangeme
I know you can do this to just change the page (href="1.html"), but I'd like to do the same thing while maintaining the GET variables that were already there.
$query = array('variable' => 'world') + $_GET;
printf('Click me', http_build_query($query));
See http://php.net/http_build_query. That's the easy to understand minimal version. Correctly you need to also HTML-escape the generated query string (because you're putting it into HTML):
printf('Click me', htmlspecialchars(http_build_query($query)));
You can simply redirect the user changing the variable value and using header()..
if(isset($_GET['variable'] && $_GET['variable'] == 'hello') {
header('Location: http://site.com/index&variable=world');
exit;
}
this should do it.
Click me
the variable or parameter in a url is preceded with a ? and then they are separated by &.
To get what you want just use this link:
Click me
but this is hardcoded and not dynamic in the sense that you can change the value of the parameter dynamically so my answer is probably not the best.
Related
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;
?>
I'm trying to make the following form's GET function to be part of a predefined variable.
Any ideas? Thanks in advance!
Let me explain a little more of what I'm really trying to do. I currently run a website concentrating on the U.S. stock market. I've created an HTML form with a method=GET. This form is used like a search box to look up stock ticker symbols. With the GET method, it places the ticker symbol at the end of the URL, and I created a quotes.php page that captures this information and displays a stock chart based on what ticker symbol is keyed into the box. For the company names, I've created a page called company.php that declares all of the variables for the company names (which happens to be a $ followed by the ticker symbol). The file, company.php, is the only file included in quotes.php.
This is where this came in: ' . $$_GET["symbol"] . '
The above code changes the GET into the variable based on what was typed into the form. I've used "die" to display an error message if someone types something into the box that doesn't match a variable in the company.php page.
I've also added into the company.php page variables for each company that will display which stock exchange each stock is listed on. These variables begin with "$ex_". So, what I was trying to do was have the symbol keyed into the box appended to "$ex_" so that it would display the corresponding stock exchange.
My questions are:
Is there a way to have what is typed into the form added to "$ex_"?
Is this an insecure way to code something like this (can it be hacked)?
Thank you all!
Rather than prefixing your variables and using variable variables (that are potentially insecure especially with user input), try this:
$ex = array(
"foo" => "bar",
...
);
if( !isset($ex[$_GET['symbol']])) die("Error: That symbol doesn't exist!");
$chosen = $ex[$_GET['symbol']];
Here's another approach:
extract($_GET, EXTR_PREFIX_ALL, "ex");
Although it's better to use it like this just to make sure there is no security issues.
extract($_GET, EXTR_SKIP);
PHP's extract() does what exactly what you want, and you should specify "ex_" as the prefix you want.
However, there are security issues and unintended consequences to using such a function blindly, so read up on the additional paragraphs following the function parameters.
Will the below achieve what you need?
$myGetVariable = $_GET['symbol'];
$ex_{$myGetVariable} = "Something";
$_GET['symbol'] = 'APPL';
if (!empty($_GET)) {
foreach ($_GET as $k => $v) {
$var = 'ex_'.$k ;
$$var=$v;
}
}
var_dump($ex_symbol);
APPL
I know this is an easy one but it's been a long time since i've done php.
I have 2 types of links. one using $_get[] of p, and other g.
like:
<a href='?p=pages/page-type-1'>page 1</a>
<a href='?g=pages/page-type-2'>page 2</a>
after clicking on a particular link , I want to load .php pages in divs of particular ids through the include('') method.
Thank you so much.
if($_GET['p'] === 'pages/page-type-1') {
include('page-to-include.php');
}
Whatever you do, DO NOT pass variables from $_GET to include. This is extremely dangerous! You cannot trust data being supplied in $_GET and so you always want to test it specifically and avoid passing it into other code unless you have to.
Also notice the use of === to force both a value check AND a type check. Look up === operator on PHP.net if you aren't familiar with this.
You said that you wan to load the pages in a particular div ids right? You can achieve this by using AJAX..
In your .js file write like this.
$.ajax({
type:POST,
url:'path/of/your/php/file/for/requesting/data.php',
success:function(data){
var get_data = parseJSON(data);
//Target the specific div you want to display your requested data that returned to you by your php.
$('#divid').html(get_data.name);
}
});
This should work:
<?php
if(isset($_GET['p']) && ($_GET['p'] === pages/page-type-1){
require_once 'some.php';
}
If you want to do anything with your GET data sanitize it first.Never trust your user
Sorry if this isn't quite your question, but a solution could be just use 1 GET variable for both pages, and then use a switch to determine which page you want:
if (isset($_GET["p"]))
{
switch ($_GET["p"])
{
case "pages/page-type-1":
include("page-type-1.php");
break;
case "pages/page-type-2":
include("page-type-2.php");
break;
default:
include("page-not-found.php");
}
}
Im trying to create some links depending on the GET parametre currently set.
My URL looks like this:
http://mysite.com/index.php?bar=test&page=page
In my code I do the following:
$bar = $_REQUEST['bar'];
<a href="index.php?bar=<?php echo $bar?>&page=anotherpage"
But every time I click the link, it adds the whole string to the URL again.
Like first click would give me this URL:
http://mysite.com/index.php?bar=test&page=anotherpagepage=anotherpage
And next click creates:
http://mysite.com/index.php?bar=test&page=anotherpagepage=anotherpagepage=anotherpage
And so on.
Is there any way to only get the request once so that the URL always looks like this:
http://mysite.com/index.php?bar=test&page=anotherpage
No matter how many times I click the link?
Thanks a lot!
You missed an ampersand in your first example. (&). Give this a try:
$bar = $_REQUEST['bar'];
<a href="index.php?bar=<?php echo $bar?>&page=anotherpage"
Or even better, escape your variables before use to prevent XSS, Cross Site Scripting security vulnerability. Use urlencode() for URLs.
http://nl.php.net/manual/en/function.urlencode.php:
$bar = $_REQUEST['bar'];
<a href="index.php?bar=<?=urlencode($bar)?>&page=anotherpage"
You should take a look on the php function http_build_query
That enables you to construct your array first, like this:
$query = array("bar"=>$_REQUEST['bar'], "page"=>"anotherpage")
echo 'Link';
I'm doing a website. There's a pagination, you click on links and they take you to the page you need, the links pass $_GET variable ( a href="?pn=2" ) and that works fine.
However when i add the category links (also contain $_GET variable
(a href="?sort=english") on the same page, which kind of sort the content on the page, and click it, the system simply overrides the url and deletes all the previous $_GET's.
For example, I'm on page 2 (http://website.com/index.php?pn=2)
and then I click this sorting link and what I'm expecting to get is this (http://website.com/index.php?pn=2&sort=english), but what I get is this:
(http://website.com/index.php?sort=english). It simply overrides the previous $_GET, instead of adding to it!
A relative URI consisting of just a query string will replace the entire existing query string. There is no way to write a URL that will add to an existing query. You have to write the complete query string that you want.
You can maintain the existing string by adding it explicitly:
href="?foo=<?php echo htmlspecialchars($_GET['foo']); ?>&bar=123"
Try using this:
$_SERVER['REQUEST_URI'];
On this link you can see examples. And on this link I have uploaded test document where you can try it yourself, it just prints out this line from above.
EDIT: Although this can help you get the current parameters in URL, I think it's not solution for you. Like Quentin said, you will have to write full link manually and maintain each parameter.
You could create a function that will iterate through your $_GET array and create a query string. Then all you would have to do is change your $_GET array and generate this query string.
Pseudocode (slash I don't really know PHP but here's a good example you should be able to follow):
function create_query_string($array) {
$kvps = array();
for ($key in $array) {
array_push($kvps, "$key=$array[$key]");
}
return "?" . implode("&", $kvps);
}
Usage:
$_GET["sort"] = "english";
$query_string = create_query_string($_GET);
You need to maintain the query parameters when you create the new links. The links on the page should be something like this:
Sort by English
The HTTP protocol is stateless -- it doesn't remember the past. You have to remind it of what the previous HTTP parameters were via PHP or other methods (cookies, etc). In your case, you need to remind it what the current page number is, as in the example above.