PHP: Adding parameters to a url? - php

If I have the url mysite.com/test.php?id=1. The id is set when the page loads and can be anything. There could also be others in there such as ?id=1&sort=new. Is there a way just to add another to the end without finding out what the others are first then building a new url? thanks.

As an alternative to Kolink's answer, I think I would utilize http_build_query(). This way, if there is nothing in the query string, you don't get an extra &. Although, it won't really make a difference at all. Kolink's answer is perfectly fine. I'm posting this mainly to introduce you to http_build_query(), as you will likely need it later:
http_build_query(array_merge($_GET, array('newvar'=>'123')))
Basically, we use http_build_query() to take everything in $_GET, and merge it with an array of any other parameters we want. In this example, I just create an array on the fly, using your example parameter. In practice, you'll likely have an array like this somewhere already.

"?".$_SERVER['QUERY_STRING']."&newvar=123";
Something like that.

Use this function: https://github.com/patrykparcheta/misc/blob/master/addQueryArgs.php
function addQueryArgs(array $args, string $url)
{
if (filter_var($url, FILTER_VALIDATE_URL)) {
$urlParts = parse_url($url);
if (isset($urlParts['query'])) {
parse_str($urlParts['query'], $urlQueryArgs);
$urlParts['query'] = http_build_query(array_merge($urlQueryArgs, $args));
$newUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'] . '?' . $urlParts['query'];
} else {
$newUrl = $url . '?' . http_build_query($args);
}
return $newUrl;
} else {
return $url;
}
}
$newUrl = addQueryArgs(array('add' => 'this', 'and' => 'this'), 'http://example.com/?have=others');

Related

Adding to url with link

My url contains many variables that I want untouched (don't worry they aren't important).
Let's say it contained...
../index.php?id=5
How would I make a url that just adds
&current=1
rather than replacing it entirely?
I'd like...
../index.php?id=5&current=1
rather than..
../index.php?current=1
I know it's a simple question but that's why I can't figure it out.
Thanks.
To append a parameter to a URL you can do this:
function addParam( $url, $param ){
if( strrpos( $url, '?' ) === false){
$url .= '?' . $param;
} else {
$url .= '&' . $param;
}
return $url;
}
$url = "../index.php?id=5";
$url = addParam( $url, "current=1");
You should just create your link to 'add' that parameter
The Link
and then obviously in the index.php somewhere you'll look for the current variable and do what you need to:
<?php
if(isset($_GET['current']) && !empty($_GET['current]) {
// Do stuff here for the 'current' variable
$current = trim($_GET['current']);
}
?>
On the links that you require the $current variable, I suppose that you could just casually put it in the href attribute. For the index,php file, so something like this....
if(isset($_GET['current']))
{
$current = $_GET['current'];
//Do the rest of what you need to do with this variable
}
Try this one:
$givenVar = "";
foreach($_GET as $key=>$val){
$givenVar .= "&".$key."=".$val;
}
$var = "&num=1";
$link = "?".$givenVar."".$var;
echo $link;
You can just add the variable to the href,
When you clink it while the address is
../index.php?id=5
trust me you then go to
../index.php?id=5&current=1
BUT if you click that link again, than you 'll go to
../index.php?id=5&current=1&current=1
Actually I thinks that's tricky and bad practice to just append the variable.
I suggest you to do it like:
<?php
$query = isset($_GET) ? http_build_query($_GET) . '&current=1' : 'current=1';
?>
A Label
take a look http://us.php.net/manual/en/function.http-build-query.php
I don't know why in Earth you would need this, but here we are. This should do the trick.
$appendString = "&current=1";
$pageURL = $_SERVER["REQUEST_URI"].$appendString;
$_SERVER["REQUEST_URI"] should return just the name of the requested page, with any other GET variable attached. The other string should be clear enough!

PHP - Best way to find URL root from string?

I use PHP.
I have an URL that looks like this
http://www.mydomain.com/mydir/mydir2/?something=hello
I want this:
http://www.mydomain.com
I did it like this but it feels like the wrong way to do it
To long and ugly.
$url = 'http://www.mydomain.com/mydir/mydir2/?something=hello';
$root_url_a = explode('/', $url);
$root_url = $root_url_a[0] . '//' . $root_url_a[2];
$root_url_clean = $root_url_a[2];
Suggestions
Regex?
Xpath?
Some for me unknown PHP function?
The shortest most correct way of doing it will get my vote.
Ok here is an example:
$url = parse_url('http://www.mydomain.com/mydir/mydir2/?something=hello');
echo $url->scheme.'://'.$url->host;
Is along the right lines.
Though technically this is not even right since depending on whether you send in a scheme or not for a url parse_url can actually change the way it assigns variables, so I wrote:
function return_url($url){
$parsed_url = parse_url($url);
if(!$parsed_url){
return false;
}
if(isset($parsed_url['scheme'])){
if(!isset($parsed_url['host'])){
return false;
}else{
return $parsed_url['scheme'].'://'.$parsed_url['host'];
}
}
if(isset($parsed_url['path'])){
return 'http://'.$parsed_url['path'];
}
return false;
}
I would do it like this:
$url = "http://www.mydomain.com/mydir/mydir2/?something=hello";
echo parse_url($url, PHP_URL_HOST);
// Would echo:
http://www.mydomain.com
I would say RTM ;)
http://php.net/manual/en/function.parse-url.php
<?php
$url = 'http://username:password#hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_HOST);
?>

$_GET doesn't work when one of the parameters is a URL

$_GET does not work when one of the parameters to the page is a url.
An external page (which I do not have control on) shows an iframe to my page and it passes parameters of which one is:
turkSubmitTo=http%3A%2F%2Fwww.mturk.com
When on my page I want to extract other parameters, it gives me NULL for everything, but when I remove the "http" it works. Why is that and what can I do to get the other parameters?
EDIT:
You can try it yourself here:
http://www.translate.outofscopes.com/?turkSubmitTo=http%3A%2F%2Fwww.mturk.com
The Array() down there is a print_r of $_GET, you can try to remove the 'http' in the parameter and it will work.
On the localhost it works perfectly.
Try Something like:
$parameters = array();
if (isset($_SERVER['QUERY_STRING'])) {
$pairs = explode('&', $_SERVER['QUERY_STRING']);
foreach($pairs as $pair) {
$part = explode('=', $pair);
$parameters[$part[0]] = urldecode($part[1]);
}
}
You can do this, pretty easily, but you need to control what's creating the url. The trick is to urlencode twice
<?
if ( array_key_exists( 'url', $_GET ) )
{
echo $_GET['url'] . '<br>';
echo urldecode( $_GET['url'] ) . '<br>';
}
$url = 'http://example.com/a/index.php?a=123';
$encUrl = urlencode( urlencode( $url ) );
?>
Not the best - I've seen this fail.
<br>
Much Better

PHP normalize remote url's [duplicate]

This question already has an answer here:
How do I apply URL normalization rules in PHP?
(1 answer)
Closed 9 years ago.
Is there any quick function that will convert: HtTp://www.ExAmPle.com/blah to http://www.example.com/blah
Basically I want to lower case the case-insensitive parts of a url.
No, you'll have to write code for it on your own.
But you can use parse_url() to split the URL into its parts.
Since you asked for "quick," here's a one-liner that does the job:
$url = 'HtTp://User:Pass#www.ExAmPle.com:80/Blah';
echo preg_replace_callback(
'#(^[a-z]+://)(.+#)?([^/]+)(.*)$#i',
create_function('$m',
'return strtolower($m[1]).$m[2].strtolower($m[3]).$m[4];'),
$url);
Outputs:
http://User:Pass#www.example.com:80/Blah
EDIT/ADD:
I've tested, and this version is about 55% faster than using preg_replace_callback with an anonymous function:
echo preg_replace(
'#(^[a-z]+://)(.+#)?([^/]+)(.*)$#ei',
"strtolower('\\1').'\\2'.strtolower('\\3').'\\4'",
$url);
I believe this class will do what you're looking for http://www.glenscott.co.uk/blog/2011/01/09/normalize-urls-with-php/
Here's a solution, expanding on what #ThiefMaster already mentioned:
DEMO
function urltolower($url){
if (($_url = parse_url($url)) !== false){ // valid url
$newUrl = strtolower($_url['scheme']) . "://";
if ($_url['user'] && $_url['pass'])
$newUrl .= $_url['user'] . ":" . $_url['pass'] . "#";
$newUrl .= strtolower($_url['host']) . $_url['path'];
if ($_url['query'])
$newUrl .= "?" . $_url['query'];
if ($_url['fragment'])
$newUrl .= "#" . $_url['fragment'];
return $newUrl;
}
return $url; // could return false if you'd like
}
Note: Not battle-tested but it should get you going.

Replacing a specific part of a query string PHP

I use $_SERVER['QUERY_STRING'] to get the query sting.
A example would be a=123&b=456&c=789
How could I remove the b value from the query string to obtain a=123&c=789 where b can be any value of any length and is alpha numeric.
Any ideas appreciated, thanks.
A solution using url parsing:
parse_str($_SERVER['QUERY_STRING'], $result_array);
unset($result_array['b']);
$_SERVER['QUERY_STRING'] = http_build_query($result_array);
The value is going to be $_GET['b'].
How about:
str_replace('&b='.$_GET['b'], '', $_SERVER['QUERY_STRING']);
you can use this function:
function Remove_QS_Key($url, $key) {
$url = preg_replace('/(?:&|(\?))'.$key.'=[^&]*(?(1)&|)?/i', "$1", $url);
return $url;
}
to remove any key you want, e.g.
echo Remove_QS_Key("http://domain.com/?a=b&ref=dusername&c=d&e=f&g=h", "ref");
result
http://www.domain.com/?a=b&c=d&e=f&g=h
Try this:
$query_new = preg_replace('/(^|&)b=[^&]*/', '', $query);
All the answers look good, but it will be more flexible if you do:
// Make a copy of $_GET to keep the original data
$getCopy = $_GET;
unset($getCopy['b']); // or whatever var you want to take out
// This is your cleaned array
var_dump($getCopy);
// If you need the URL-encoded string, just use http_build_query()
$encodedString = http_build_query($getCopy);
You simply make a variable using $_GET and exclude b query string in build process:
$query_string_new = 'a=' . urlencode($_GET['a']) . '&c=' . urlencode($_GET['c']);
The $query_string_new should now contain a=123&c=789
Pear already has a class(Net_URL2) that handles URL parsing/building:
Install via Composer: https://packagist.org/packages/pear/net_url2
Install as include: https://github.com/pear/Net_URL2/blob/master/Net/URL2.php
Example code:
$url = new Net_URL2('http://www.example.com/?one=1');
$url->setQueryVariable('two', 2);
echo $url; // http://www.example.com/?one=1&two=2
Here is a function to replace a query parameter: (like example.com?a=1&b=2 -> example.com?a=5&b=2)
function replace_qs_key($key, $value) {
$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") .
"://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$current_url_without_qs = strtok($current_url, '?');
parse_str($_SERVER['QUERY_STRING'], $query_params);
$query_params['page'] = $value;
$_SERVER['QUERY_STRING'] = http_build_query($query_params);
$new_url = $current_url_without_qs .'?'. $_SERVER['QUERY_STRING'];
return $new_url;
}

Categories