PHP: Get all parameters from the url without the file id - php

I want to extract all used parameters of a link as a text string. Example:
$link2 = http://example.com/index.html?song=abcdefg;
When using the above link $param should give out all the parameters '?song=abcdefg'. Unfortunately I do not know the id index.html nor the parameters and their respective data values.
As much as I am informed there is the function $_GET, which creates an array, but I need a string.

You can use parse_url:
$link2 = 'http://example.com/index.html?song=abcdefg';
$param = '?' . parse_url($link2, PHP_URL_QUERY);
echo $param;
// ?song=abcdefg

Many librairies exist to parse url, you can use this one for an exemple :
https://github.com/thephpleague/uri
use League\Uri\Schemes\Http as HttpUri;
$link2 = 'http://example.com/index.html?song=abcdefg';
$uri = HttpUri::createFromString($link2);
// then you can access the query
$query = $uri->query;
You also can try this one :
https://github.com/jwage/purl

A weird way to do this is
$link2 = 'http://example.com/index.html?song=abcdefg';
$param = strstr($link2, "?");
echo $param // ?song=abcdefg
strstr($link2, "?") will get everything after the first position of ?; including the leading ?

you can loop over the get array and parse it into a string:
$str = "?"
foreach ($_GET as $key => $value) {
$temp = $key . "=". $value . "&";
$str .= $temp
}
rtrim($str, "&")//remove leading '&'

You can use http_build_query() method
if ( isset ($_GET))
{
$params = http_build_query($_GET);
}
// echo $params should return "song=abcdefg";

Related

two variables values in one variable is possible?

My code:
$url = "http://www.google.com/test";
$parseurl = parse_url($url);
$explode = explode('.', $parseurl['host']);
$arrayreverse = array_reverse($explode);
foreach(array_values($arrayreverse) as $keyvalue) {
$result[] = $keyvalue;
}
$implode = implode('.', $result);
...
I'm interested to have values in one variable from $implode result and the result if isset the path from $parseurl... how can I do that ?
EDIT:
I want the values of $implode + and(if isset $parseurl['path']); to be in 1 variable but I can't figure out how to unite them.
Is ths what you want?
$newurl = $implode . (isset($parseurl['path']) ? $parseurl['path'] : '');
It uses the conditional operator to return either the path or an empty string, and concatenate that onto $implode.

Add Querystring Variable with Multiple Values PHP

I found a bit of code for stripping a query string and adding a new value to it, but I want to be able to do this with an array of options. Could someone give me a hand in modifying this code to do that?
Current code:
function add_querystring_var($url, $key, $value) {
$url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -1);
$value = $value ? "=".urlencode($value) : '';
if (strpos($url, '?') === false)
return ($url . '?' . $key . $value);
else
return ($url . '&' . $key . $value);
}
And I want it to do a foreach for each key and value given and then rebuild the new url.
Example: add_querystring_var(curPageURL(), array("order","sort"), array("swn","DESC"))
So I want the following URL http://www.example.com/students when put through the example above would return http://www.example.com/students?order=swn&sort=DESC
Does anyone know how I can do this? I'm new to this area of PHP. :)
UPDATE:
I forgot to mention sometimes the url may have other queries in it, so I want it to replace the ones that I enter into my array.
Example 1: http://www.example.com/students?page=2 would need to turn into http://www.example.com/students?page=2&order=swn&sort=DESC
Example 2: http://www.example.com/students?page=2&order=name&sort=ASC would need to turn into http://www.example.com/students?page=2&order=swn&sort=DESC
function add_querystring_var($url, $additions) {
$parsed = parse_url($url);
if (isset($parsed['query'])) {
parse_str($parsed['query'], $query);
} else {
$query = array();
}
$parsed['query'] = http_build_query(array_merge($query, $additions));
return http_build_url($parsed);
}
Use it this way:
$new_url = add_querystring_var($url, array('order' => 'swn', 'sort' => 'DESC'));
If you're getting errors saying that http_build_url is not defined, see
PHP http_build_url() and PECL Install
You're kind of reinventing the wheel with that function... first off, you'd be better off using urlencode() on your key/value data rather than that regular expression (and I see that you're not encoding your value string at all)
As dpDesignz mentions in his comment - there is a built-in function available: http_build_query()
$querydata = array('foo' => array('bar', 'baz'),
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
$querystring = http_build_query($data, '', '&');
Or, to use your example:
$querydata = array("order" => "swn", "sort" => "DESC");
$url = curPageURL();
$concat = "?";
if (strpos($url, "?") !== false)) {
$concat = "&"
}
$url .= $concat . http_build_query($data, '', '&');

preg_replace remove parameter variable

Want to remove p2variable from url string, below are 3 cases if case 3 also remove ? sign.
case 1: http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj
result: http://www.domain.com/myscript.php?p1=xyz&p3=ghj
case 2: http://www.domain.com/myscript.php?p2=10&p3=ghj
result: http://www.domain.com/myscript.php?p3=ghj
case 3: http://www.domain.com/myscript.php?p2=10
result: http://www.domain.com/myscript.php
Want to achieve result with single preg_replace expression.
Don't use regular expressions when dealing with URL values. It's much easier (and safer) to handle them as a URL instead of plain text.
This could be one way to do it:
Split the url first and parse the query string
Take the parameter out
Rebuild the url
The below code is an example of such an algorithm:
// remove $qs_key from query string of $url
// return modified url value
function clean_url_qs($url, $qs_key)
{
// first split the url in two parts (at most)
$parts = explode('?', $url, 2);
// check whether query string is passed
if (isset($parts[1])) {
// parse the query string into $params
parse_str($parts[1], $params);
// unset if $params contains $qs_key
if (array_key_exists($qs_key, $params)) {
// remove key
unset($params[$qs_key]);
// rebuild the url
return $parts[0] .
(count($params) ? '?' . http_build_query($params) : '');
}
}
// no change required
return $url;
}
Test code:
echo clean_url('http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj', 'p2'), "\n";
echo clean_url('http://www.domain.com/myscript.php?p2=10&p3=ghj', 'p2'), "\n";
echo clean_url('http://www.domain.com/myscript.php?p2=10', 'p2'), "\n";
Found this in one of my old projects (a bit of shitcode, but...), may help you:
$unwanted_param = 'p2';
$s = 'http://www.domain.com/myscript.php?p1=xyz&p2=10&p3=ghj';
$s = parse_url($s);
$params = explode('&', $s['query']);
$out_params = array();
foreach ($params as $key => &$param) {
list($name, $value) = explode('=', $param);
if ($unwanted_param == $name) {
unset($params[$key]);
} else {
$out_params[$name] = $value;
}
}
$query = '?' . http_build_query($out_params);
$result = $s['scheme'] . '://' . $s['host'] . $s['path'] . $query;
var_dump($result);
Using preg_replace, something like
$url = preg_replace('!([\?&]p2=[^&\?$]+)!i', '', $url);
However, personally I'd do the following
if (strpos($url, '?') !== false) {
list($domain, $qstring) = explode('?', $url, 2);
parse_str($qstring, $params);
if (isset($params['p2'])) {
unset($params['p2']);
}
$qstring = !empty($params) ? '?' . http_build_query($params) : '';
$url = $domain . $qstring;
}

PHP: Replace 1st char in a string - to create a link to itself

In my test.php I would like to provide a link back to the production script index.php, passing the same GET-parameters:
foreach ($_GET as $key => $val) {
$get .= "&$key=$val";
}
# this one is wrong - I want to replace just the first "&"
$get = str_replace("&", "?", $get);
echo '<p>You are viewing the test version.</p>
<p><a href="/index.php' . $get .
'">Return to production version</a></p>';
How do I replace just the 1st char in the $get string?
Or maybe there is a nicer way to create a "self-link"?
You could just do:
$get = 'index.php?' . $_SERVER['QUERY_STRING'];
$get = preg_replace('/&/', '?', $get, 1);
You should look at $_SERVER['QUERY_STRING'], which contains the query string from the request, except for the first ? charater.
So, for instance, if you were to go to http://example.com/page.php?var1=val1&var2=val2, the contents of $_SERVER['QUERY_STRING'] would be var1=val1&var2=val2
Also, to replace the first character of the string, you can simply use:
if(strlen($string) > 0) // Unexpected behavior would occur with empty strings
{
$string[0] = '?'; // This would modify the first character of a string
}
$get = "";
foreach ($_GET as $key => $val) {
$get .= "&$key=$val";
}
if(strlen($get) > 0)
$get[0] = "?";

trim url(query string)

I have a query string like the one given below:
http://localhost/project/viewMember.php?sort=Y2xhc3M=&class=Mw==&page=9
Now variable: page in query string can be anywhere within the query string either in beginning or middle or at end (like ?page=9 or &page=9& or &page=9).
Now, I need to remove page=9 from my query string and get a valid query string.
Lots of ways this could be done, including regex (as seen below). This is the most robust method I can think of, although it is more complex than the other methods.
Use parse_url to get the query string from the url (or write your own function).
Use parse_str to convert the query string into an array
unset the key that you don't want
Use http_build_query to reassemble the array into a query string
Then reconstruct the Url (if required)
Try:
preg_replace('/page=\d+/', '', $url);
Tried writing a function for this. Seems to work:
<?php
$url = "http://localhost/project/viewMember.php?sort=Y2xhc3M=&class=Mw==&page=9";
// prints http://localhost/project/viewMember.php?sort=Y2xhc3M=&class=Mw==
print changeURL($url) . "\n";
$url = "http://localhost/project/viewMember.php?sort=Y2xhc3M=&page=9&class=Mw==";
// prints http://localhost/project/viewMember.php?sort=Y2xhc3M=&class=Mw==
print changeURL($url) . "\n";
function changeURL($url)
{
$arr = parse_url($url);
$query = $arr['query'];
$pieces = explode('&',$query);
for($i=0;$i<count($pieces);$i++)
{
if(preg_match('/^page=\d+/',$pieces[$i]))
unset($pieces[$i]);
}
$query = implode('&',$pieces);
return "$arr[scheme]://$arr[host]$arr[user]$arr[pass]$arr[path]?$query$arr[fragment]";
}
?>
I created these two functions:
function cleanQuery($queryLabels){
// Filter all items in $_GET which are not in $queryLabels
if(!is_array($queryLabels)) return;
foreach($_GET as $queryLabel => $queryValue)
if(!in_array($queryLabel, $queryLabels) || ($queryValue == ''))
unset($_GET[$queryLabel]);
ksort($_GET);
}
function amendQuery($queryItems = array()){
$queryItems = array_merge($_GET, $queryItems);
ksort($queryItems);
return http_build_query($queryItems);
}
To remove the page part I would use
$_GET = amendQuery(array('page'=>null));
cleanQuery does the opposite. Pass in an array of the terms you want to keep.
function remove_part_of_qs($removeMe)
{
$qs = array();
foreach($_GET as $key => $value)
{
if($key != $removeMe)
{
$qs[$key] = $value;
}
}
return "?" . http_build_query($qs);
}
echo remove_part_of_qs("page");
This should do it, this is my first post on StackOverflow, so go easy!

Categories