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

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.

Related

Replace GET variable value in PHP [duplicate]

This question already has answers here:
How to get and change URL variable PHP
(8 answers)
Closed 8 months ago.
everyone.
Is it possible to replace a specific GET variable value by using RegEx?
Here is what I have in mind.
I have a URL: https://example.com/category/?var1=value1&page=2&var2=value2
It can have different GET variables, but the one that it always has is "page".
What I want to do is this:
Set the URL value to a string variable in PHP code - Done.
$current_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
In that string replace the value of the "page" variable with another value but keep the rest of the URL the same so that I could use them for paging buttons - Struggling
Take the string variable and echo it in a href tag - Done.
Next
The "page" value, of course, is not always 2 - it represents the page number where the user currently is so can be anything from 1 to any other integer.
I'm trying to do it with explodes and joins, but haven't succeeded yet. Maybe there is an easier way to replace values using RegEx?
Here's a quick way to replace a parameter. Note, however, that this solution doesn't necessarily work out of the box for all URLs as some may not have a query.
# Your URL.
$url = "https://example.com/category/?var1=value1&page=2&var2=value2";
# Parse your URL to get its composing parts.
$parts = parse_url($url);
# Save the query of the URL.
$query = $parts["query"];
# Parse the query to get an array of the individual parameters.
parse_str($query, $params);
# Replace the value of the parametre you want.
$params["page"] = "your-value";
# Build the query.
$newQuery = http_build_query($params);
# Replace the old query with the new one.
$newUrl = str_replace($query, $newQuery, $url);
Snippet

Is there a PHP equivalent to Java's ServletRequest.getParameterValues()? [duplicate]

This question already has answers here:
How to pass an array within a query string?
(12 answers)
Closed 4 years ago.
I have an array of parameter values (with matching parameter names) in my request URL, like this:
?my_array_of_values=First&my_array_of_values=Second
In a Java servlet, I can detect them like this:
ServletRequest request = ...;
String[] myArrayOfValues = request.getParameterValues("my_array_of_values");
And this will result in:
myArrayOfValues[0] = "First";
myArrayOfValues1 = "Second";
...which is what I want.
However, I am not sure how to get the same results in PHP. For the same (above) parameters, when I try:
print_r($_GET);
it results in
Array ( [my_array_of_values] => Second )
...i.e., the "First" parameter is lost.
I can see why this happens, but is there a way to detect such an array of parameter values in PHP as you can in Java/servlets? If not, is there a recommended workaround or alternative way of doing it?
I don't know about the strange magic that happens in a Java environment, but query params must have different names or else they will overwrite each other.
In the example of ?my_array_of_values=First&my_array_of_values=Second only the last given value is returned. It is the same as assigning different values to the same variable one after the other.
You may retrieve a single parameter as array though, by using angle brackets after the parameter name:
?my_array_of_values[]=First&my_array_of_values[]=Second
In that case $_GET['my_array_of_values'] will be an array with all the given values.
See also: Authoritative position of duplicate HTTP GET query keys

Parsing URL query in PHP [duplicate]

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.

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.

Passing & in URL variable with the help of urlencode

I have done urlencode of the variable before passing to the URL
http://example.com/Restaurants?alias=F%26B
But when I try to print like in the page
$alias = rawurldecode($_GET['alias']);
echo $alias;
it prints only F. How to solve this?
I doubt that $_GET['alias'] exists when requesting a URL with the query aliasF%26B. It’s rather $_GET['aliasF&B'] that’s getting populated.
In this case you need to use $_SERVER['QUERY_STRING'] to get the full query.
It looks like you are not using the query string "correctly." It should be in key=value pairs. I would look at using $_SERVER['QUERY_STRING'] to get your information instead.
You don't need to urlencode the pair. You only need to urlencode name and a value as such:
Wrong:
urlencode('aliasF=B')
Correct:
urlencode('aliasF') . '=' . urlencode('B')
AFAIK $_GET are already decoded.
See php.net
The superglobals $_GET and $_REQUEST
are already decoded. Using urldecode()
on an element in $_GET or $_REQUEST
could have unexpected and dangerous
results.
It is possible to solve this problem by using a different encoding system specific for your situation:
function encode($string)
{
$result = str_replace("|","||",$string);
return str_replace("&","|20",$result);
}
function decode($string)
{
$result = str_replace("|20","&",$string);
return str_replace("||","|",$result);
}
This will basically create a separate escaping system using the '|' character. That character can be anything you normally don't use and isn't an field separator.
Here, Apache won't transform the URL to something different, thus voiding the conversion. Also browsers won't transform it.
Mind that you would decode($_GET['alias']) and encode() the url that the user is pressing or the script is following.

Categories