I was thinking if there is a way to hide part of the url in PHP/ Zend Framework 2. Something like this:
sitename.com/something/?inviter=1234&id=1
But I'd like to hide the part with the &id=1 somehow, so that when the url is copied and entered by the user, it would look like this:
sitename.com/something/?inviter=1234
And on the other side I can do something like this:
$id = $_GET["id"])
Is this possible to do, if so, how? Maybe there is something close to what I'm looking for to achieve?
You can hide it only with Cookie or Session techniques. But it will work only for one user during one session.
You can parse and rebuild the url using parse_url, http_build_url, with parse_str, and http_build_str.
For example:
/**
* Transform a url using a whitelist of query-string keys
*/
function transformUrlKeepQueryKeys($url, array $whitelist)
{
// Break the given url into parts
$parts = parse_url($url);
// Break the parts into key-value pairs
$query = $parts['query'];
parse_str($query, $queryParts);
// Unset all unwanted keys
foreach (array_keys($queryParts) as $k) {
if (!in_array($k, $whitelist)) {
unset($queryParts[$k]);
}
}
// rebuild the url
$parts['query'] = http_build_query($queryParts);
// return
return http_build_url('', $parts);
}
Invocation should be:
$url = 'http://sitename.com/something/?inviter=1234&id=1';
$whitelist = [
'inviter'
];
$expectedUrl = 'http://sitename.com/something/?inviter=1234';
$actualUrl = transformUrlKeepQueryKeys($url, $whitelist);
assert($expectedUrl == $actualUrl);
Alternatively, you could implement something similar using a blacklist of keys to remove.
The only problem with this is that the function http_build_url is not included in core PHP, but is part of the PECL HTTP extension. If you are unable to install that extension in your environment, then you can use a pure PHP implementation of that function, for example here.
Related
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.
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".
re: Home Site = http://mobiledetect.net/
re: this script = Mobile_Detect.php
Download script here: https://github.com/serbanghita/Mobile-Detect
This script functions perfectly detecting the different parameters of a user's device.
However, this is how I am currently detecting these parameters:
// each part of the IF statement is hard-coded = not the way to do this
if($detect->isiOS()){
$usingOS = 'iOS';
}
if($detect->isAndroidOS()){
$usingOS = 'Android';
}
echo 'Your OS is: '.$usingOS;
My goal is to use a FOREACH to iterate thru the various arrays in this script to determine a user's device's parameters. I would need to have the "($detect->isXXXXOS())" be dynamic... (which, would be based upon the KEY). The results would display the KEY. But the detection would be based upon the VALUE.
Also, since my web page uses a REQUIRE to access this script... in the Mobile_Script.php script, the arrays are "protected." I think this is also causing me problems (but I don't know for sure).
Any help is appreciated.
In foreach loop you can call dynamic method look like this :
$array = array('Android','Windows','Linux','Mac');
foreach( $array as $value) {
$method = "is{$value}OS";
if($detect->$method()) {
$os = $value;
echo "Your OS is : {$os}";
}
}
Please rearrange your code what you want. I give you an example.
you can try to use somethin like this:
$OSList = $detect->getOperatingSystems();// will give array of operating system name => match params
foreach($OSList as $os_name=>$os_params/*unused*/)
{
$method = 'is'.$os_name;
if($detect->$method())
{
$usingOS = $os_name;
}
}
I want remove a parameter from a URL:
$linkExample1='https://stackoverflow.com/?name=alaa&counter=1';
$linkExample2='https://stackoverflow.com/?counter=4&star=5';
I am trying to get this result:
https://stackoverflow.com/?name=alaa&
https://stackoverflow.com/?&star=5
I am trying to do it using preg_replace, but I've no idea how it can be done.
$link = preg_replace('~(\?|&)counter=[^&]*~','$1',$link);
Relying on regular expressions can screw things up sometimes..
You should use, the parse_url() function which breaks up the entire URL and presents it to you as an associative array.
Once you have that array, you can edit it as you wish and remove parameters.
Once, completed, use the http_build_url() function to rebuild the URL with the changes made.
Check the docs here..
Parse_Url Http_build_query()
EDIT
Whoops, forgot to mention. After you get the parameter string, youll obviously need to separate the parameters as individual ones. For this you can supply the string as input to the parse_str() function.
You can even use explode() with & as the delimeter to get this done.
I would recommend using a combination of parse_url() and http_build_query().
Handle it correctly! !
remove_query('http://example.com/?a=valueWith**&**inside&b=value');
Code:
function remove_query($url, $which_argument=false){
return preg_replace( '/'. ($which_argument ? '(\&|)'.$which_argument.'(\=(.*?)((?=&(?!amp\;))|$)|(.*?)\b)' : '(\?.*)').'/i' , '', $url);
}
A code example how I would grab a requested URL and remove a parameter called "name", then reload the page:
$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //complete url
$parts = parse_url($url);
parse_str($parts['query'], $query); //grab the query part
unset($query['name']); //remove a parameter from query
$dest_query = http_build_query($query); //rebuild new query
$dest_url=(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http").'://'.$parts['path'].'?'.$dest_query; //add query to host
header("Location: ".$dest_url); //reload page
parse_url() and parse_str() are buggy. Regular expressions can work but have the tendency to break. If you want to correctly deconstruct, make changes, and then reconstruct a URL, you should look at:
http://barebonescms.com/documentation/ultimate_web_scraper_toolkit/
ExtractURL() generates parse_url()-like output but does much more (and does it right). CondenseURL() takes an array from ExtractURL() and constructs a new URL from the information. Both functions are in the 'support/http.php' file.
Years later...
$_GET can be manipulated like any other array in PHP. Simply unset the key and create the http query using the http_build_query function.
// Populate _GET with sample data...
$_GET = array(
'value_a' => "A",
'key_to_remove' => "Don't delete me bro!",
'value_b' => "B"
);
// Should output everything...
// "value_a=A&key_to_remove=Don%27t+delete+me+bro%21&value_b=B"
echo "\n".http_build_query( $_GET );
// Remove the key from _GET...
unset( $_GET[ 'key_to_remove' ] );
// Should output everything else...
// "value_a=A&value_b=B"
echo "\n".http_build_query( $_GET );
This is working for me:
function removeParameterFromUrl($url, $key)
{
$parsed = parse_url($url);
$path = $parsed['path'];
unset($_GET[$key]);
if(!empty(http_build_query($_GET))){
return $path .'?'. http_build_query($_GET);
} else return $path;
}
Let's say I have some code like this
if(isset($_GET['foo']))
//do something
if(isset($_GET['bar']))
//do something else
If a user is at example.com/?foo=abc and clicks on a link to set bar=xyz, I want to easily take them to example.com/?foo=abc&bar=xyz, rather than example.com/?bar=xyz.
I can think of a few very messy ways to do this, but I'm sure there's something cleaner that I don't know about and haven't been able to track down via Google.
Here's one way....
//get passed params
//(you might do some sanitizing at this point)
$params=$_GET;
//morph the params with new values
$params['bar']='xyz';
//build new query string
$query='';
$sep='?';
foreach($params as $name=>$value)
{
$query.=$sep.$name.'='.urlencode($value);
$sep='&';
}
If you are updating the query string you need ot make sure you don't do something like
$qs="a=1&b=2";
$href="$qs&b=4";
$href contains "a=1&b=2&b=4"
What you really want to do is overwrite the current key if you need to .
You can use a function like this. (disclaimer: Off the top of my head, maybe slightly bugged)
function getUpdateQS($key,$value)
{
foreach ($_GET as $k => $v)
{
if ($k != $key)
{
$qs .= "$k=".urlencode($v)."&"
}
else
{
$qs .= "$key=".urlencode($value)."&";
}
}
return $qs
}
View report
Just set the link that changes bar to xyz to also have foo=abc if foo is already set.
$link = ($_GET['foo'] == 'abc') ? 'foo=abc&bar=xyz' : 'bar=xyz';
?>
Click Me
You would have to render out the links with the proper URL querystring to make that happen. This is a design decision that you would need to make on your end depending on how your system is setup.
I have some sites that have this issue, and what I do is setup a querystring global variable that sets the current page data the top of the page request.
Then when I am rendering the page, if I need to make use of the current query string I do something like:
echo '<a href="myurl.php' . querystring . '&bar=foo';
It's not the cleanest, but it all depends on how your system works.
Save some code and use the built-in http_build_query. I use this wrapper in one of my projects:
function to_query_string($array) {
if(is_scalar($array)) $query = trim($array, '? \t\n\r\0\x0B'); // I could split on "&" and "=" do some urlencode-ing here
else $query = http_build_query($array);
return '?'.$query;
}
Also, though it isn't often used, you can have $_GET on the left-hand side of an assignment:
$_GET['overriden_or_new'] = 'new_value';
echo 'Yeah!';
Other than that, just do what Paul Dixon said.