Pass Multiple query parameter through URL - php

I have a path alias like below
$node_alias = '/node/add/page?id=1';
what i need is have to append query parameter to a destination url with above url,i have tried below but doenn't work
$node_alias = '/node/add/page?id=1&destination=/admin/content?id=1
Any solution?

You need to url-encode each component in the query string.
The first parameter id=1 is fine, but the destination parameter contains special characters used for delimiting uri components : /, ?, =.
You can use urlencode() or rawurlencode() :
$node_alias = '/node/add/page?id=1&destination=' . rawurlencode('/admin/content?id=1')
There is a drupal way of doing this, using drupal_http_build_query() (d7):
$path = current_path();
$params = drupal_get_query_parameters() + array('destination' => '/admin/content?id=1');
$query = drupal_http_build_query($params);
$node_alias = $path . '?' . $query;
See also urlencode vs rawurlencode?

Related

Remove one querystring parameter from a URL with multiple querystring parameters

I would like to remove a querystring parameter from a url that may contain multiple. I have succeeded in doing this using str_replace so far like this:
$area_querystring = urlencode($_GET['area']);
str_replace('area=' . $area_querystring, '', $url);
preg_replace also works, like this:
preg_replace('~(\?|&)area=[^&]*~', '$1', $url)
Either works fine for most URLs. For example:
http://localhost:8000/country/tw/?area=Taipei%2C+Taiwan&fruit=bananas
Becomes:
http://localhost:8000/country/tw/?&fruit=bananas
However, if the querystring contains an apostrophe html entity, nothing happens at all. E.g.:
http://localhost:8000/country/cn/?area=Shanghai%2C+People%27s+Republic+of+China&fruit=bananas
The %27 part of the url (an apostrophe) seems to be the cause.
To be clear, I don't wish to remove all of the URL after the last /, just the area querystring portion (the fruit=bananas part of the url should remain). Also, the area parameter does not always appear in the same place in the URL, sometimes it may appear after other querystring parameters e.g.
http://localhost:8000/country/tw/?lang=taiwanese&area=Taipei%2C+Taiwan&fruit=bananas
You can use the GET array and filter out the area key. Then rebuild the url with http_build_query. Like this:
$url = 'http://localhost:8000/country/cn/?area=Shanghai%2C+People%27s+Republic+of+China&fruit=bananas';
$filtered = array_filter($_GET, function ($key) {
return $key !== 'area';
}, ARRAY_FILTER_USE_KEY);
$parsed = parse_url($url);
$query = http_build_query($filtered);
$result = $parsed['scheme'] . "://" . $parsed['host'] . $parsed['path'] . "?" . $query;
You probably don't need urlencode() -- I'm guessing your $url variable is not yet encoded, so if there are any characters like an apostrophe, there won't be a match.
So:
$area_querystring = $_GET['area'];
should do the trick! No URL encoding/decoding needed.

Add params to query string in a clean way in php

I'd like to find a clean if possibile (without too much string manipulation preg_*)
I know that to replace a parameter I would do
$_GET['info'] = "newinfo";
and to remove a parameter:
unset($_GET['info']);
so is there something like that that I can use?
of course after I've "unset" or "set" I'm building a new query.
(http_build_query).
At the end I'm trying to make this:
/index.php?foo=bar
to
/index.php?foo=bar&info=newinfo
Just do this:
$get = $_GET;
$get['new'] = 'some value';
function getPath()
{
// Stolen from https://stackoverflow.com/a/8775529/3578036
$request = parse_url($_SERVER['REQUEST_URI']);
$path = $request["path"];
return rtrim(str_replace(basename($_SERVER['SCRIPT_NAME']), '', $path), '/');
}
header("Location: " . getPage() . http_build_query($get));
The above code will create a query string and append it to the current URL and redirect to that location. Obviously, you can change the location that you redirect to by replacing the getPage() function result and putting your own result there, this just demonstrates the premise of the answer.
The docs for http_build_query are a very good place to start.
Effectively, what it will do is convert an associative array into an HTTP query string.

parse non encoded url

there is an external page, that passes a URL using a param value, in the querystring. to my page.
eg: page.php?URL=http://www.domain2.com?foo=bar
i tried saving the param using
$url = $_GET['url']
the problem is the reffering page does not send it encoded. and therefore it recognizes anything trailing the "&" as the beginning of a new param.
i need a way to parse the url in a way that anything trailing the second "?" is part or the passed url and not the acctual querystring.
Get the full querystring and then take out the 'URL=' part of it
$name = http_build_query($_GET);
$name = substr($name, strlen('URL='));
Antonio's answer is probably best. A less elegant way would also work:
$url = $_GET['url'];
$keys = array_keys($_GET);
$i=1;
foreach($_GET as $value) {
$url .= '&'.$keys[$i].'='.$value;
$i++;
}
echo $url;
Something like this might help:
// The full request
$request_full = $_SERVER["REQUEST_URI"];
// Position of the first "?" inside $request_full
$pos_question_mark = strpos($request_full, '?');
// Position of the query itself
$pos_query = $pos_question_mark + 1;
// Extract the malformed query from $request_full
$request_query = substr($request_full, $pos_query);
// Look for patterns that might corrupt the query
if (preg_match('/([^=]+[=])([^\&]+)([\&]+.+)?/', $request_query, $matches)) {
// If a match is found...
if (isset($_GET[$matches[1]])) {
// ... get rid of the original match...
unset($_GET[$matches[1]]);
// ... and replace it with a URL encoded version.
$_GET[$matches[1]] = urlencode($matches[2]);
}
}
As you have hinted in your question, the encoding of the URL you get is not as you want it: a & will mark a new argument for the current URL, not the one in the url parameter. If the URL were encoded correctly, the & would have been escaped as %26.
But, OK, given that you know for sure that everything following url= is not escaped and should be part of that parameter's value, you could do this:
$url = preg_replace("/^.*?([?&]url=(.*?))?$/i", "$2", $_SERVER["REQUEST_URI"]);
So if for example the current URL is:
http://www.myhost.com/page.php?a=1&URL=http://www.domain2.com?foo=bar&test=12
Then the returned value is:
http://www.domain2.com?foo=bar&test=12
See it running on eval.in.

$_GET for + in url get request?

My project Url is like this in yii:
http://localhost/php_pro_106/activate/Test?JJ=HEY+OOO
In my action :
public function actionTest()
{
print_r($_GET);
}
I am getting:
Array ( [JJ] => HEY OOO )
But I should get:
Array ( [JJ] => HEY+OOO )
What should I do for this,I need same Url ?
A + in a URL means a space. So you get the result you should have.
If you want to encode a + character in a URL, then you should represent it as %2B.
http://localhost/php_pro_106/activate/Test?JJ=HEY%2BOOO
If you are generating the URL programatically with PHP, you can use the urlencode function.
$keyname = "JJ";
$data = "HEY+OOO";
$url = "http://localhost/php_pro_106/activate/Test?" . urlencode($keyname) . "=" . urlencode($data);
You need to encode your URL (e.g. with urlencode in php). + needs to become %2B.
http://localhost/php_pro_106/activate/Test?JJ=HEY%2BOOO
"+" is one of reserved characters, according to RFC 2396.
If you want "+" in your example, you should use url encoding.
http://localhost/php_pro_106/activate/Test?JJ=HEY%2BOOO
If you produce URL from code, use urlencode() function to generate your URLS.

How do I extract query parameters from a URL string in PHP?

Users can input URLs using a HTML form on my website, so they might enter something like this: http://www.example.com?test=123&random=abc, it can be anything. I need to extract the value of a certain query parameter, in this case 'test' (the value 123). Is there a way to do this?
You can use parse_url and parse_str like this:
$query = parse_url('http://www.example.com?test=123&random=abc', PHP_URL_QUERY);
parse_str($query, $params);
$test = $params['test'];
parse_url allows to split an URL in different parts (scheme, host, path, query, etc); here we use it to get only the query (test=123&random=abc). Then we can parse the query with parse_str.
I needed to check an url that was relative for our system so I couldn't use parse_str. For anyone who needs it:
$urlParts = null;
preg_match_all("~[\?&]([^&]+)=([^&]+)~", $url, $urlParts);
the hostname is optional but is required at least the question mark at the begin of parameter string:
$inputString = '?test=123&random=abc&usersList[]=1&usersList[]=2' ;
parse_str ( parse_url ( $inputString , PHP_URL_QUERY ) , $params );
print_r ( $params );

Categories