Parsing URL query in PHP [duplicate] - php

This question already has answers here:
Parse query string into an array
(12 answers)
Closed 8 months ago.
Assuming a URL of www.domain.org?x=1&y=2&z=3, what would be a smart method to separate out the query elements of a URL in PHP without using GET or REQUEST?
$url = parse_url($url);
echo $url[fragment];
I don't think it's possible to return query parts separately, is it? From what I can tell, the query will just say x=1&y=2&z=3, but please let me know if I am wrong. Otherwise, what would you do to parse the $url[query]?
Fragment should be Query instead. Sorry for the confusion; I am learning!

You can take the second step and parse the query string using parse_str.
$url = 'www.domain.org?x=1&y=2&z=3';
$url_parts = parse_url($url);
parse_str($url_parts['query'], $query_parts);
var_dump($query_parts);
I assumed you meant the query string instead of the fragment because there isn't a standard pattern for fragments.

The parse_url function returns several components, including query. To parse it you should run parse_str.
$parsedUrl = parse_url($url);
parse_str($parsedUrl['query'], $parsedQueryString);
If you are going just to parse your HTTP request URL:
use the $_REQUEST['x'], $_REQUEST['y'], and $_REQUEST['z'] variables to access the x, y, and z parameters;
use $_SERVER['QUERY_STRING'] to get the whole URL query string.

I was getting errors with some of the answers, but they did lead me to the right answer.
$url = 'www.domain.org?x=1&y=2&z=3';
$query = $url[query];
parse_str($query);
echo "$x &y $z";
And this outputs 1 2 3, which is what I was trying to figure out.

As a one-liner with no error checking
parse_str(parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY), $query);
$query will contain the query string parameters.
Unlike PHP's $_GET, this will work with query parameters of any length.

I highly recommend using this URL wrapper (which I have written).
It is capable of parsing URLs of complexity like protocol://username:password#subdomain.domain.tld:80/some/path?query=value#fragment and has many more goodies.

Related

How to compose a query string when one of query string is URL that contains its query string in PHP?

In PHP, I would like to create a GET request by composing a query string. One of the query string key-value is like url=http://www.example.com/a.php?id=xyz&name=def, the rest of query string is like regular key-value pair.
However, when I compose them, the url will impact the whole GET request. For example, I have regular key-value pairs like site=uts&user=zzz, I will end up with getting the GET request like below
http://domain?url=http://www.example.com/a.php?id=xyz&name=def&site=uts&user=zzz
This is totally wrong. How can I pass url value in this GET request and avoid this situation?
If i understand your question correctly, you will want to use urlencode.
http://uk1.php.net/manual/en/function.urlencode.php
For example:
$url = 'http://domain?url='.urlencode('http://www.example.com/a.php?id=xyz&name=def').'&site=uts&user=zzz';
will produce:
http://domain?url=http%3A%2F%2Fwww.example.com%2Fa.php%3Fid%3Dxyz%26name%3Ddef&site=uts&user=zz
You need to use urlencode and urldecode

Capture value from URL string with php

I need to extract a variable's value from a string, which happens to be a URL. The string/url is loaded as part of a separate php query, not the url in the browser.
The url's will look like:
index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44
How can I always find & capture the value of the id which in this example is 2773?
I read several examples already, but what I've tried captures the id value of the current page which is being viewed in the browser, and not the URL string.
Thanks
You are looking for a combination or parse_url (which will isolate the query string for you) and parse_str (which will parse the variables and put them into an array).
For example:
$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';
// This parses the url for the query string, and parses the vars from that
// into the array $vars (which is created on the spot).
parse_str(parse_url($url, PHP_URL_QUERY), $vars);
print_r($vars); // see what's in there
// Parse the value "2773:xcelsiors" to isolate the number
$id = reset(explode(':', $vars['id']));
// This will also work:
$id = intval($vars['id']);
echo "The id is $id\n";
See it in action.
You can use parse_str
You can use parse_url to parse URLs!
But you can use, to extract directly the numbers of ID variable:
$url = 'index.php?option=com_content&view=article&catid=334:golfeq&id=2773:xcelsiors&Itemid=44';
$id = preg_replace("/^.*[&?]id=([0-9]+).*$/",'$1',$url);
echo $id;

Extracting a URL string with same results as a $_GET [duplicate]

This question already has answers here:
Getting vars from URL
(6 answers)
Closed 8 years ago.
Ok, so I have a string like so:
index.php?page=test2;sa=blah
And I need only to grab what gets returned using $_GET['page'], so it will return, test2 in this case. BUT page MUST be defined DIRECTLY after index.php? before it can return an actual string. How do I do this? I just need the same results returned from a $_GET for the page variable. I can also have just this:
index.php?page=blah
Should return blah
or this:
index.php?page=anything&sa=blah
Returns anything
or this:
index.php?action=blah;page=2
Returns empty string, cause this is NOT directly after index.php?
or basically any url, but it needs to grab the variable of page if it exists, only after index.php?. And sometimes page might not even exist at all, in this case, an empty string should be returned.
How can I do this? I am not browsing to the URL in my browser, so, don't think $_GET will work, but it needs to simulate and return the EXACT same results that $_GET will return in the browser, but only if page is defined directly after index.php?
parse_url and parse_str are your friends.
Please use following code:
function get($name, $url) {
$src = parse_url($url);
$src = $src['query'];
parse_str($src, $tag);
return $tag[$name];
}
you can check if the element received at $_GET is equal that you expect by comparison or a simple if statement. if not, then process the string to find it (if needed). Maybe also used the index of the elemnt to determine if process or not.

How to change variables in link of foo?q=some&s=3&d=new

Consider a php script visited with URL of foo?q=some&s=3&d=new. I wonder if there is a paractical method for parsing the url to create links with new variable (within php page). For example foo?q=**another-word**&s=3&d=new or foo?q=another-word&s=**11**&d=new
I am thinking of catching the requested URL by $_SERVER['REQUEST_URI'] then parsing with regex; but this is not a good idea in practice. There should be a handy way to parse variables attached to the php script. In fact, inverse action of GET method.
The $_GET variable contains an already parsed array of the current query string. The array union operator + makes it easy to merge new values into that. http_build_query puts them back together into a query string:
echo 'foo?' . http_build_query(array('q' => 'another-word') + $_GET);
If you need more parsing of the URL to get 'foo', use parse_url on the REQUEST_URI.
What about using http_build_query? http://php.net/manual/en/function.http-build-query.php
It will allow you to build a query string from an array.
I'd use parse_str:
$query = 'q=some&s=3&d=new';
parse_str($query, $query_parsed);
$query_parsed['q'] = 'foo-bar';
$new_query = implode('&', array_map(create_function('$k, $v',
'return $k."=".urlencode($v);'),
array_keys($query_parsed), $query_parsed));
echo $new_query;
Result is:
q=foo-bar&s=3&d=new
Although, this method might look like "the hard way" :)

Getting array param out of query string with PHP

(NOTE: This is a follow up to a previous question, How to pass an array within a query string?, where I asked about standard methods for passing arrays within query strings.)
I now have some PHP code that needs to consume the said query string- What kind of query string array formats does PHP recognize, and do I have to do anything special to retrieve the array?
The following doesn't seem to work:
Query string:
?formparts=[a,b,c]
PHP:
$myarray = $_GET["formparts"];
echo gettype($myarray)
result:
string
Your query string should rather look like this:
?formparts[]=a&formparts[]=b&formparts[]=c
If you're dealing with a query string, you are looking at the $_GET variable. This will contain everything after the ? in your previous question.
So what you will have to do is pretty much the opposite of the other question.
$products = array();
// ... Add some checking of $_GET to make sure it is sane
....
// then assign..
$products = explode(',', $_GET['pname']);
and so on for each variable. I must give you a full warning here, you MUST check what comes through the $_GET variable to make sure it is sane. Otherwise you risk having your site compromised.

Categories