Cut some word from php available ?
First access to page for example
www.mysite.com/test.php?ABD_07,_oU_876.00/8999&message=success
From my php code, i will get $curreny_link_redirect = test.php?ABD_07,_oU_876.00/8999&message=success
And i want to get $curreny_link_redirect_new = test.php?ABD_07,_oU_876.00/8999
( Cut &message=success )
How can i do ?
<?PHP
$current_link = "$_SERVER[REQUEST_URI]";
$curreny_link_redirect = substr($current_link,1);
$curreny_link_redirect_new = str_replace('', '&message=success', $curreny_link_redirect);
echo $curreny_link_redirect_new;
?>
Your str_replace call is inverse of what it should be. What you want to replace should be the first parameter, not the second.
//Wrong
$curreny_link_redirect_new = str_replace('', '&message=success', $curreny_link_redirect);
//Right
$curreny_link_redirect_new = str_replace('&message=success','', $curreny_link_redirect);
While simple way to do this is to use regex (or even static with str_replace()), I recommend to use built-in functions for url handling. This may be useful when working with complex parameters or multiple parameters:
$data = 'www.mysite.com/test.php?ABD_07,_oU_876.00/8999&message=success';
$url = parse_url($data);
parse_str($url['query'], $url['query']);
//now, do something with parameters:
unset($url['query']['message']);
$url['query'] = http_build_query($url['query']);
$url = http_build_url($url);
-please, note, that http_build_url() is a PECL function (pecl_http to be precise). The way above may look more complex, but it has benefits - first, as I've already mentioned, this will be easy to modify for working with complex parameters or multiple parameters. Second, it will produce valid url - i.e. encode such things as slashes, spaces, e t.c. - in result. Thus, result will always be correct url.
Do like this
<?php
$str = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo $str = array_shift(explode('&',$str));
Try this:
$current_link_path = substr($_SERVER['PHP_SELF'], 1);
$params = $_GET;
if ($params['message'] == 'success') {
unset($params['message']);
}
$current_link_redirect = $current_link_path . '?' . http_build_query($params);
Maybe not an answer, but a disclaimer for future visitors:
1) I would strongly recommend the function: http://pl1.php.net/parse_url.
And in that case:
$current_link = "$_SERVER[REQUEST_URI]";
$arguments = explode('&', parse_url($current_link, PHP_URL_QUERY));
print_r($arguments);
2) To build new url, use http://pl1.php.net/manual/en/function.http-build-url.php. This is the best, future modifications ready solution I think.
In that case this solution is a little overkill, but these functions are really great, and worth to introduce here.
Best regards
Related
I am trying to parse url and extract value from it .My url value is www.mysite.com/register/?referredby=admin. I want to get value admin from this url. For this, I have written following code. Its giving me value referredby=admin, but I want only admin as value. How Can I achieve this? Below is my code:
<?php
$url = $current_url="//".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
setcookie('ref_by', parse_url($url, PHP_URL_QUERY));
echo $_COOKIE['ref_by'];
?>
You can use parse_str() function.
$url = "www.mysite.com/register/?email=admin";
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['email'];
Try this code,
$url = "www.mysite.com/register/?referredby=admin";
$parse = parse_url($url, PHP_URL_QUERY);
parse_str($parse, $output);
echo $output['referredby'];
$referred = $_GET['referredby'];
$referred = "referredby=admin";
$pieces = explode("=", $referred);
echo $pieces[1]; // admin
I don't know if it's still relevant for you, but maybe it is for others: I've recently released a composer package for parsing urls (https://www.crwlr.software/packages/url). Using that library you can do it like this:
$url = 'https://www.example.com/register/?referredby=admin';
$query = Crwlr\Url\Url::parse($url)->queryArray();
echo $query['referredby'];
The parse method parses the url and returns an object, the queryArray method returns the url query as array.
Is not a really clean solution, but you can try something like:
$url = "MYURL";
$parse = parse_url($url);
parse_str($parse['query']);
echo $referredby; // same name of the get param (see parse_str doc)
PHP.net: Warning
Using this function without the result parameter is highly DISCOURAGED and DEPRECATED as of PHP 7.2.
Dynamically setting variables in function's scope suffers from exactly same problems as register_globals.
Read section on security of Using Register Globals explaining why it is dangerous.
How can I take out the part of the url after the view name
Example:
The URL:
http://localhost/winner/container.php?fun=page&view=eims
Extraction
eims
This is called a GET parameter. You can get it by using
<?php
$view = $_GET['view'];
If this is for a URL which is not part of your website (e.g. Not your domain), but you wish to parse it. Something like this will work
$url = "http://example.com/index.php?foo=bar&acme=baz&view=asdf";
$params = explode('?', $url)[1]; // This gets the text AFTER the ? Note: If using PHP 5.3 or less, this may not work. You would then need to split it into two lines with the [1] happening on $params.
$pairs = explode('&', $params);
foreach($pairs as $p => $pair) {
list($keys[$p], $values[$p]) = explode('=', $pair);
$splits[$keys[$p]] = $values[$p];
}
echo $splits['view'];
<?php echo $_GET['view']; ?> //eims
If that's current URL, the simple and rock solid approach is to use the filter functions:
filter_input(INPUT_GET, 'view')
Otherwise, you can use parse_url() with PHP_URL_QUERY as second argument. The resulting string can be split with e.g. parse_str().
Are sure you are writing this "echo $_GET['view'];" in the container.php file?
Maybe write why do you need that "view".
I am trying to set up a small script that can play youtube videos but thats kinda besides the point.
I have $ytlink which equals www.youtube.com/watch?v=3WAOxKOmR90
But I want to make it become www.youtube.com/embed/3WAOxKOmR90
Currently I have tried
$result = str_replace('https://youtube.com/watch?v=', "https://youtube.com/watch?v=", $ytlink);
But this returns it as standard
I have also tried
preg_replace('/https://youtube.com/watch?v=/, '/https://youtube.com/embed/', $ytlink);
but both of these dont work.
Instead of using ugly regexes, I recommend using parse_url() with parse_str(). This allows you to be flexible in the event that you want to change something or if Youtube decides to change their URL slightly.
$url = 'https://www.youtube.com/watch?v=3WAOxKOmR90';
// Parse the URL into parts
$parsed_url = parse_url($url);
// Get the whole query string
$query = $parsed_url['query'];
// Parse the query string into parts
parse_str($query, $params);
// Get the parameter you want
$v = $params['v'];
// Now re-build the URL how you want
echo $parsed_url['scheme'].'://'.$parsed_url['host'].'/embed/'.$v;
// Outputs: https://www.youtube.com/embed/3WAOxKOmR90
This works:
$ytlink = 'www.youtube.com/watch?v=3WAOxKOmR90';
$result = str_replace('watch?v=', 'embed/', $ytlink);
echo $result;
$url = 'www.youtube.com/watch?v=3WAOxKOmR90';
echo preg_replace('/.*?v=(\w+)/i', 'www.youtube.com/embed/$1', $url);
I want to add a query string to a URL, however, the URL format is unpredictable. The URL can be
http://example.com/page/ -> http://example.com/page/?myquery=string
http://example.com/page -> http://example.com/page?myquery=string
http://example.com?p=page -> http://example.com?p=page&myquery=string
These are the URLs I'm thinking of, but it's possible that there are other formats that I'm not aware of.
I'm wondering if there is a standard, library or a common way to do this. I'm using PHP.
Edit: I'm using Cbroe explanation and Passerby code. There is another function by Hamza but I guess it'd be better to use PHP functions and also have cleaner/shorter code.
function addQuery($url,array $query)
{
$cache=parse_url($url,PHP_URL_QUERY);
if(empty($cache)) return $url."?".http_build_query($query);
else return $url."&".http_build_query($query);
}
// test
$test=array("http://example.com/page/","http://example.com/page","http://example.com/?p=page");
print_r(array_map(function($v){
return addQuery($v,array("myquery"=>"string"));
},$test));
Live demo
I'm wondering if there is a standard, library or a common way to do this. I'm using PHP.
Depends on how failsafe – and thereby more complex – you want it to be.
The simplest way would be to look for whether there’s a ? in the URL – if so, append &myquery=string, else append ?myquery=string. This should cover most cases of standards-compliant URLs just fine.
If you want it more complex, you could take the URL apart using parse_url and then parse_str, then add the key myquery with value string to the array the second function returns – and then put it all back together again, using http_build_query for the new query string part.
Some spaghetti Code:
echo addToUrl('http://example.com/page/','myquery', 'string').'<br>';
echo addToUrl('http://example.com/page','myquery', 'string').'<br>';
echo addToUrl('http://example.com/page/wut/?aaa=2','myquery', 'string').'<br>';
echo addToUrl('http://example.com?p=page','myquery', 'string');
function addToUrl($url, $var, $val){
$array = parse_url($url);
if(isset($array['query'])){
parse_str($array['query'], $values);
}
$values[$var] = $val;
unset($array['query']);
$options = '';$c = count($values) - 1;
$i=0;
foreach($values as $k => $v){
if($i == $c){
$options .= $k.'='.$v;
}else{
$options .= $k.'='.$v.'&';
}
$i++;
}
$return = $array['scheme'].'://'.$array['host'].(isset($array['path']) ? $array['path']: '') . '?' . $options;
return $return;
}
Results:
http://example.com/page/?myquery=string
http://example.com/page?myquery=string
http://example.com/page/wut/?aaa=2&myquery=string
http://example.com?p=page&myquery=string
You should try the http_build_query() function, I think that's what you're looking for, and maybe a bit of parse_str(), too.
Suppose I have the following, which is the current url:
http://myurl.com/locations/?s=bricks&style=funky-quirky+rustic&feature=floors-concrete+kitchen+bathroom
How would I remove all parameters except S using PHP? In other words, just leaving: http://myurl.com/locations/?s=bricks The other parameters will always be Style, Type, Feature, and Area, and some or all of them may be present.
Thanks!
if ( isset($_GET['s']) && count($_GET) > 1 ) {
header('Location: ?s='. rawurlencode($_GET['s']));
exit;
}
Edited to somewhat appease Jon.
Not much in the way of error checking, but if s is guaranteed to exist this will work:
list($base, $query) = explode('?', $url);
parse_str($query, $vars);
$result = $base.'?s='.rawurlencode($vars['s']);
It will also work no matter in what position s appears in the query string. I 'm doing a minimal initial "parsing" step with explode, but if that doesn't feel right you can always bring in the big guns and go with parse_url instead at the expense of being much more verbose.
You can achieve this in several different manners.
I will show you the best standard I ever faced to work with urls:
$originUrl = parse_url('http://myurl.com/locations/?s=bricks&style=funky-quirky+rustic&feature=floors-concrete+kitchen+bathroom');
parse_str($originUrl['query'], $queryString);
echo $newUrl = $originUrl['scheme'].'://'.$originUrl['host'].$originUrl['path'].'?s='.$queryString['s'];
Good Luck!
parse_str(parse_url($url, PHP_URL_QUERY), $query);
$newurl = 'http://myurl.com/locations/?s=' . $query['s'];
If you know that s will always be the first parameter, then you can simply do:
$url = "http://myurl.com/locations/?s=bricks&style=funky-quirky+rustic&feature=floors-concrete+kitchen+bathroom";
$split = explode('&',$url);
echo $split[0];
However, if the position of s in the parameters is unkown, then you can do this:
$url = "http://myurl.com/locations/?s=bricks&style=funky-quirky+rustic&feature=floors-concrete+kitchen+bathroom";
$split = explode('?',$url);
parse_str($split[1],$params);
echo $split[0].'?s='.$params['s'];