How do i get the URL of the current page minus all of the get arguments (?blah=2&blah4=90...)
I know i can get the full URL with $_SERVER['REQUEST_URI'] but i was wondering if there was something that more fit my needs.
Or should i just do strpos ? and substr to chop of the arguments? ( i imagine that a $_SERVER var would be more efficient - if one exists)
Thanks
$_SERVER['REQUEST_URL']
Sometimes answers are easy :) I found the solution here: http://php.net/manual/en/reserved.variables.server.php by CTRL+F'ing for "query".
EDIT
As matchu said in the comments, not all servers support REQUEST_URL. In that case I would use the much less elegant strtok($url, '?');.
$_SERVER['REQUEST_URL']
should do the trick...
It's listed here in the comments:
http://php.net/manual/en/reserved.variables.server.php
Don't know why it isn't in the doco?
You can use the parse_url function and then concat the parts you need(scheme, host, port, user, pass and path)
You can use this, is pretty simple:
$url = explode("?",$_SERVER[REQUEST_URI]);
$url = "http://$_SERVER[HTTP_HOST]/" . $url[0];
With exploding the URL you will have in $url[0] the "first part" and in $url[1] all the arguments.
Related
So just a quick thought and I understand that there are millions of ways around this 'problem' but I was wondering if there is a character or format for both initiating and separating GET parameters. Let me explain:
I am redirecting the user to a link defined as a variable but adding on a parameter at the end like so:
Header("Location: ".$link."&err=1");
The problem is, some of these links ($link) will contain GET params and some will not. If the link does not already contain GET parameters, '&' will not work as an initiator.
Header("Location: page&err=1");
And if the link does already contain parameters, '?' will not work as a separating character.
Header("Location: page?val=123?err=1");
So again, I know there are many ways around this and I'm not lookign for someone to code a simple check for me but I'm curious about the link formatting aspect and I can't find anything through my own research. I'm honestly expecting that the answer is 'not possible' but I'm intrigued enough to ask now, thanks.
No.
? starts the query string.
& and ; separate key=value pairs in application/x-www-form-urlencoded data which is the format most back ends expect. (; hasn't got as good a level of support).
Will parse_url() not work?
Specifically parse_url($url, PHP_URL_QUERY);
http_build_query() could also be useful
This is an easy one. There seem to be plenty of solutions to determine if a URL contains a specific key or value, but strangely I can't find a solution for determining if URL does or does not have a query at all.
Using PHP, I simply want to check to see if the current URL has a query string. For example: http://abc.com/xyz/?key=value VS. http://abc.com/xyz/.
For any URL as a string:
if (parse_url($url, PHP_URL_QUERY))
http://php.net/parse_url
If it's for the URL of the current request, simply:
if ($_GET)
The easiest way is probably to check to see if the $_GET[] contains anything at all. This can be done with the empty() function as follows:
if(empty($_GET)) {
//No variables are specified in the URL.
//Do stuff accordingly
echo "No variables specified in URL...";
} else {
//Variables are present. Do stuff:
echo "Hey! Here are all the variables in the URL!\n";
print_r($_GET);
}
parse_url seems like the logical choice in most cases. However I can't think of a case where '?' in a URL would not denote the start of a query string so for a (very minor) performance increase you could go with
return strpos($url, '?') !== false;
Over 1,000,000 iterations the average time for strpos was about 1.6 seconds vs 1.8 for parse_url. That being said, unless your application is checking millions of URLs for query strings I'd go for parse_url.
Like this:
if (isset($_SERVER['QUERY_STRING'])) {
}
Why does this code not work?
echo explode("?", $_SERVER["REQUEST_URI"])[0];
It says syntax error, unexpected '['.
Oddly, this works:
$tmp = explode("?", $_SERVER["REQUEST_URI"]);
echo $tmp[0];
But I really want to avoid to create such a $tmp variable here.
How do I fix it?
After the helpful answers, some remaining questions: Is there any good reason of the design of the language to make this not possible? Or did the PHP implementors just not thought about this? Or was it for some reason difficult to make this possible?
Unlike Javascript, PHP can't address an array element after a function. You have to split it up into two statements or use array_slice().
This is only allowed in the development branch of PHP (it's a new feature called "array dereferencing"):
echo explode("?", $_SERVER["REQUEST_URI"])[0];
You can do this
list($noQs) = explode("?", $_SERVER["REQUEST_URI"]);
or use array_slice/temp variable, like stillstanding said. You shouldn't use array_shift, as it expects an argument passed by reference.
It's a (silly) limitation of the current PHP parser that your first example doesn't work. However, supposedly the next major version of PHP will fix this.
Take a look at this previous question.
Hoohaah's suggestion of using strstr() is quite nice. The following will return from the beginning of the string until the first ? (the third argument for strstr() is only available for PHP 5.3.0 onward):
echo strstr($_SERVER["REQUEST_URI"], "?", TRUE);
Or if you want to stick with explode, you can make use if list(). (The 2 indicates that at most 2 elements will be returned by explode).
list($url) = explode("?", $_SERVER["REQUEST_URI"], 2);
echo $url;
Finally, to use the natively available PHP URL parsing;
$info = parse_url($_SERVER["REQUEST_URI"]);
echo $info["scheme"] . "://" . $info["host"] . $info["path"];
EDIT:
echo current(explode("?", $_SERVER["REQUEST_URI"]));
I believe PHP 5.4 comes with this feature, at long last. Sadly, it will be a while before your average web host updates their PHP version. My Ubuntu VPS doesn't even have it in the default repos.
I am very curious on how to do this. I want a PHP script to look at the string after the URL link and echo the value.
For example, if I entered:
"http://mywebsite.com/script.php?=43892"
the script will echo the value 43892. I have seen this in most websites, and I think it will be a very useful to have in my application.
Thanks,
Kevin
You mean, something like
http://mywebsite.com/script.php?MyVariable=43892
? Variables provided at the end of the URL like that are available in the $_GET array. So if you visited the above URL and there was a line on the page that said
echo $_GET['MyVariable'];
then 43892 would be echoed.
Do be aware that you shouldn't trust user input like this - treat any user input as potentially malicious, and sanitise it.
echo filter_var($_SERVER['QUERY_STRING'], FILTER_SANITIZE_NUMBER_INT);
The sanitation is because in your example the query string is =43892, not 43892. The filter used "remove[s] all characters except digits, plus and minus sign".
Don't you mean http://mywebsite.com/script.php?43892 ?
You can either use apache URL rewriting or try to extract all entries from $_GET and look a the one which looks like a number or simply doesn't have a value.
Try manually parsing the URL like this
$geturl = $_SERVER['REQUEST_URI'];
$spliturl = explode("?",$geturl);
$get
= explode("=",$spliturl[0]);
echo $get[1];
:)
Before I really answer your question, I just have to say that most sites - at least that I have seen - actually use ?43892, with the =. This is also much easier than using it with = in my opinion.
So, now to the actual answer. You can simply extra the query string usingĀ $_SERVER['QUERY_STRING'].
An example:
User requests index.php?12345:
<?php
echo $_SERVER['QUERY_STRING'];
?>
Output:
12345
Note that you can also use something like
<?php
if(substr($_SERVER['QUERY_STRING'], 0, 1) == '=') {
$query_string = substr($_SERVER['QUERY_STRING'], 1);
}else{
$query_string = $_SERVER['QUERY_STRING'];
}
echo $query_string;
to support ?=12345 as well as 12345, with the same result. Note also that ?=12345 would not be available as $_GET[''] either.
The way you usualy use query parameters is by assigning them like http://mywebsite.com/script.php?var1=123&var2=234
Then you will be able to access them by $_GET['var1'] and $_GET['var2'] in your PHP script
I'de recommand parse-url for this. The documentation contains all you (I think) need.
Help me please get the value of the address bar of browser without the parameters passed. Without the use of regular expressions and string functions. You can do this? (I use php on apache).
enter
http://dev.mazda-parts.ru/catalogue/?spattern=1
exit
http://dev.mazda-parts.ru/catalogue/
Take a look at the $_SERVER superglobal.
<?php
//example
echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URL'];
parse_url() can help you, or some of the php string functions, like strtok()
You say that you want the URL of the last page, which can be found in the $_SERVER['HTTP_REFERER'] variable.
Beware that this value is not reliable as it can be freely changed by the client.
If you want a more accurate way of finding the last page, you can use sessions. Here's an example:
session_start();
$last_page = $_SESSION['pageurl'];
$_SESSION['pageurl'] = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URL'];
// $last_page now contains a more reliable value for the last url