PHP GET variable `/` instead of `?` - php

I'm working with a script that doesn't allow $_GET[] variables in the URL (it's a referrer url I'm giving out and I need to have some way to track it). I can't have this for example domain.com/index.php?id=test. However i can do this domain.com/index.php/idd=test
My question is if i use / instead of ? and treat it like a get variable. How do i get the variable from the url. What's an easy way to do this

If you have a URL like this:
http://example.com/index.php/whatever
Then the /whatever is commonly known as PATH_INFO and available as:
print $_SERVER["PATH_INFO"]
Note that some environments (CGI) can have it set to placeholder values (request_uri) when an actual path_info wasn't present. (See also PHP manual on the environment variables http://php.net/manual/en/reserved.variables.server.php and the notes about PATH_INFO and PATH_TRANSLATED.)
.htaccess: php_value arg_separator.input &;/
# Else strtr(..., "/", "&")
parse_str($_SERVER["PATH_INFO"], $_GET);
Should populate $_GET.

There's no "easy" way to replace the entire functionality of $_GET parameters, but there are some awkward hacks, at least under Apache. Given that you cannot use $_GET parameters, I'll assume you don't have access to mod_rewrite either, but who knows.
A request like http://www.example.com/index.php/foo/bar/baz
will generate the following items in the $_SERVER superglobal:
[REQUEST_URI] => /index.php/foo/bar/baz
[SCRIPT_NAME] => /index.php
[PATH_INFO] => /foo/bar/baz
In theory, you can then parse $_SERVER['PATH_INFO'] by splitting on "/", looping through that array and splitting on "=" (assuming you're still going to use a key=value structure).
Be aware, however, that a side effect of the wonky URL structure is that relative links in your document will become relative to the wonky URL, so an image like
<img src="images/myimage.jpg">
will attempt to load http://www.example.com/index.php/foo/bar/images/myimage.jpg
This can be avoided by using absolute URLs (http://www.example.com/images/myimage.jpg) or root-relative URLs (/images/myimage.jpg).
But basically, you're asking for a world of trouble...and troubleshooting.

$segments = explode("/", $_SERVER['REQUEST_URI']);
then you decide from there. each one of the results from $segments can be manipulated the same way. You can choose to do id=test or just the id and always know that $segments[2] is id, for example. Your call.
You should definitely look into mod_rewrite though. you need to redirect calls to a file cause this method will not allow anything past .php if you are not allowed get vars. (assuming through some config ? and beyond is not read)
basically reroute everything to index.php if that's your one controller.

You could parse it like this:
$uriParts = array_reverse((array) explode('/', $_SERVER['REQUEST_URI']));
$GET = explode('=', $uriParts[0]); // however you wanted to parse it form here
Do with it as you wish, just know that $uriParts[0] would contain id=whatever.

What you have to do is parse $_SERVER['REQUEST_URI'] and then do what you need to it.
from your example you need something like this:
//get rid of "/index.php
$uri = substr($_SERVER['REQUEST_URI'], 11);
//explode incase there are other parameters
$arr = explode('&', $uri);
$token = array();
foreach($token as $t){
$part = explode('=', $t);
$token[$part[0]] = $part[1]
}

Related

PHP: rawurldecode() not showing plus sign

I have a URL like this:
abc.com/my+string
When I get the parameter, it obviously it replaces the + with a space, so I get my string
I replaced the + in the url with %2B, then I use rawurldecode(), but the result is the same. Tried with urldecode() but I still can't get the plus sign in my variable, it's always an empty space.
Am I missing something, how do I get exactly my+string in PHP from the url abc.com/my%2Bstring ?
Thank you
In general, you don’t need to URL-decode GET parameter values manually, since PHP already does that for you, automatically. abc.com?var=my%2Bstring -> $_GET['var'] will contain my+string
The problem here was that URL rewriting was in play. As http://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_b explains,
mod_rewrite has to unescape URLs before mapping them, so backreferences will be unescaped at the time they are applied.
So mod_rewrite has decoded my%2Bstring to my+string, and when you rewrite this as a query string parameter, you effectively get ?var=my+string. And when PHP applies automatic URL decoding on that value, the + will become a simple space.
The [B] flag exists to make mod_rewrite re-encode the value again.
Like this:
echo urldecode("abc.com/my%2Bstring"); // => abc.com/my+string
echo PHP_EOL;
echo rawurldecode("abc.com/my%2Bstring"); // => abc.com/my+string
Further if you want to get the actual my+string, you can utilize the powers of parse_url function which comes with PHP itself, although you have to provide a full URL into it.
Other way is just to explode the value by a / and get it like this:
$parts = explode('/', 'abc.com/my+string'); // => Array(2)
echo $parts[1] ?? 'not found'; // => string|not found
Also read the documentation on both: urldecode and rawurldecode.
Example here.

How to change variables in link of foo?q=some&s=3&d=new

Consider a php script visited with URL of foo?q=some&s=3&d=new. I wonder if there is a paractical method for parsing the url to create links with new variable (within php page). For example foo?q=**another-word**&s=3&d=new or foo?q=another-word&s=**11**&d=new
I am thinking of catching the requested URL by $_SERVER['REQUEST_URI'] then parsing with regex; but this is not a good idea in practice. There should be a handy way to parse variables attached to the php script. In fact, inverse action of GET method.
The $_GET variable contains an already parsed array of the current query string. The array union operator + makes it easy to merge new values into that. http_build_query puts them back together into a query string:
echo 'foo?' . http_build_query(array('q' => 'another-word') + $_GET);
If you need more parsing of the URL to get 'foo', use parse_url on the REQUEST_URI.
What about using http_build_query? http://php.net/manual/en/function.http-build-query.php
It will allow you to build a query string from an array.
I'd use parse_str:
$query = 'q=some&s=3&d=new';
parse_str($query, $query_parsed);
$query_parsed['q'] = 'foo-bar';
$new_query = implode('&', array_map(create_function('$k, $v',
'return $k."=".urlencode($v);'),
array_keys($query_parsed), $query_parsed));
echo $new_query;
Result is:
q=foo-bar&s=3&d=new
Although, this method might look like "the hard way" :)

Get parts of URL in PHP

I am just wondering what the best way of extracting "parameters" from an URL would be, using PHP.
If I got the URL:
http://example.com/user/100
How can I get the user id (100) using PHP?
To be thorough, you'll want to start with parse_url().
$parts=parse_url("http://example.com/user/100");
That will give you an array with a handful of keys. The one you are looking for is path.
Split the path on / and take the last one.
$path_parts=explode('/', $parts['path']);
Your ID is now in $path_parts[count($path_parts)-1].
You can use parse_url(), i.e.:
$parts = parse_url("http://x.com/user/100");
$path_parts= explode('/', $parts[path]);
$user = $path_parts[2];
echo $user;
# 100
parse_url()
This function parses a URL and returns an associative array containing
any of the various components of the URL that are present. The values
of the array elements are not URL decoded.
This function is notmeant to validate the given URL, it only breaks it
up into the above listed parts. Partial URLs are also
accepted, parse_url() tries its best to parse them correctly.
$url = "http://example.com/user/100";
$parts = Explode('/', $url);
$id = $parts[count($parts) - 1];
I know this is an old thread but I think the following is a better answer:
basename(dirname(__FILE__))

PHP Get From URL

I was wondering how I could remove a certain part of a url using PHP.
This is the exact url in questions:
http://www.mysite.com/link/go/370768/
I'm looking to remove the number ID into a variable.
Any help would be great, Thanks!
There are many (many!) ways of extracting a number from a string. Here's an example which assumes the URL starts with the format like http://www.mysite.com/link/go/<ID> and extracts the ID.
$url = 'http://www.mysite.com/link/go/370768/';
sscanf($url, 'http://www.mysite.com/link/go/%d', $id);
var_dump($id); // int(370768)
Use explode()
print_r(explode("/", $url));
You could use mod_rewrite inside of your .htaccess to internally rewrite this URL to something more friendly for PHP (convert /link/go/370768/ into ?link=370768, for example).
I suspect that you are using some kind of framework. There are two ways to check the $_GET variables:
print_r($_GET);
or check the manual of the manual of the framework and see how the GET/POST is passed internally, for example in CakePHP you have all parameters save internally in your controller you can access them like that:
$this->params['product_id'] or $this->params['pass']
There is another solution which is not very reliable and professional but might work:
$path = parse_url($url, PHP_URL_PATH);
$vars = explode('/', $path);
echo $vars[2];
$vars should contain array like this:
array (
0 => link
1 => go
2 => 370768
)

Passing parameters via GET to any url in universal way

I have back_url given to me from the outside. I need to generate a hash and to make redirect to this back_url with this param: header("Location: $back_url?hash=123sdf"). But the problem is that I don't know the format of back_url.
It may be www.example.com and I do header("Location: $back_url/?hash=123sdf") sj that's fine.
It maybe www.example.com/?param=value and if I do header("Location: $back_url/?hash=123sdf") it's wrong, because it would be www.example.com/?param=value/?hash=123asd.
And so on. The question is: what's the universal way to pass params to back_url ignoring its format?
A complex but very clean way is
Use parse_url() to extract the query string (if any) from the URL into an array
Add hash to the resulting array: $params["hash"] = "1234";
Use http_build_query() to glue the parameters back into a query string
Take all the components returned by parse_url() and glue them back into a full URL
one thing to note is that this dissects the URL into it components and glues it back together, so it's likely it won't work with URLs that are broken in the first place.
Have you tried using http://php.net/manual/en/function.parse-url.php ?
If you have the PECL HTTP extension, use http_build_url:
$url = '...';
$hash = '...';
$new_url = http_build_url($url, array('hash' => $hash), HTTP_URL_JOIN_QUERY);
If you don't have http_build_url, you can use parse_url to find the different parts if a URL. Then it's just a matter of pasting them together. Here's a solution in the manual which can be tailored for your needs.
Well, you would need to detect if $back_url has other query parameters (or GET variables) and append your hash using ?hash=123asd if it hadn't, or using &hash=123asd if indeed it had query parameters.
If you know that $back_url is a full url like http://whatever.com/blah/blah (the important part being http://whatever.com, you can use parse_url to get all components, and then continue with Pekka's answer. If your $back_url doesn't begin with http://..., then prepend the right value (I assume http://$_SERVER['host'] and, again, continue with Pekka's answer.
Wrote this function:
private function addUrlParam(array $params, $url){
$parsed = parse_url($url);
if(!isset($parsed['query']))
{
$slash = '';
if(substr($url, -1) !== '/')
$slash = '/';
$start_with = $slash.'?';
}
else
$start_with = '&';
$scheme = '';
if(!isset($parsed['scheme']))
$scheme = 'http://';
$query = http_build_query($params);
return $scheme.$url.$start_with.$query;
}
Looks like it's perfect for me. Thanks everyone.

Categories