Can PHP 5 do request handling similar to Tomcat or GAE? - php

lets say i want to go to
http://example.com/something/a/few/directories/deep
is there a way I can process this in PHP without having to make those directories? I just want to get everything after the domain name as a variable and work from there.

The most common way of doing this is by using mod_rewrite. (There in an introduction to this at http://articles.sitepoint.com/article/guide-url-rewriting). This allows you to internally map these friendly URLs to query parameters passed to your PHP script.

Sure. You don't even need mod_rewrite if the beginning is constant or has only a few possible values. Make a php file named something (no extension) and tell Apache (via a SetHandler or similar directive) to treat it as PHP. Then, examine $_SERVER['PATH_INFO'] in the script, which will look like a/few/directories/deep IIRC. You can use that to route your request however you like.
Alternatively. as Martin says, use a simple mod_rewrite rule to rewrite it to /dispatch.php/something/a/few/directories/deep and then you have the whole path in PATH_INFO.

You do not need mod_rewrite to handle such a scenario. Most of the popular PHP frameworks currently support URI segment parsing. This is a simple example which still leaves a few security holes to be patched up.
You could handle this by taking one of the global $_SERVER variables and splitting it on forward slashes like so:
if (!empty($_SERVER['REQUEST_URI'])) {
$segments = explode('/', $_SERVER['REQUEST_URI']);
}
The $segments variable will now contain an array of segments to iterate over.

Assuming you are using apache...
Add a re-write rule (in your vhost conf or just drop .htaccess file in you doc root), to point everything to index.php. Then inside of your index.php, parse the request uri and extract path
RewriteEngine on
RewriteRule ^.*$ index.php [L,QSA]
index.php:
$filepath = $_SERVER['REQUEST_URI'];
$filepath = ltrim($myname, '/'); //strip leading slash if you want.

This actually is not a PHP5-related quesion - URL rewriting is part of your webserver.
You can, when you use mod_rewrite on Apache (don't know about IIS, but there likely is something similar).

Related

Why use $_SERVER['REQUEST_URI'] over $_GET['url'] in PHP after URL rewriting occurs for an MVC Router?

Apache (2.4.x)
If I establish a rewrite rule in my httpd-vhosts.conf (which is included into my main httpd.conf), within a <VirturalHost> block, like the following (as I see some example and tutorials do, not my idea):
RewriteRule ^(.*)$ /public/www/foo.com/public/index.php?url=$1 [QSA,L]
1) Do I need to specify the absolute path (seems so, as RewriteBase is not appropriate in this context)? It works this way, but I just wanted to know if there was something I overlooked. However, it only works this way because of a dubious suggestion (which seems unacceptable).
<Directory />
AllowOverride none
Require all granted ---> original setting: Require all denied
</Directory>
That seems outrageously flawed and permissive (seems). I really need to study up on the module that implements the Require runtime directive (mod_access, I think).
Is this enough (never works for me within a <VirtualHost> block)? Is it better to put the rewrite rules in .htaccess so that they travel with the application (instead of being coupled to the server)?
RewriteRule ^(.*)$ index.php [L] -->Wihout QSA, Query String Append
2) I see some people using $_SERVER['REQUEST_URI'] instead of $_GET['url']. Is there any benefit, or advantage, to doing this?
I read some where in Stackoverflow Code Review that $_SERVER['REQUEST_URI'] will receive URL encoded values. So, I tested it and found that to be true.
For http://www.foo.com/hi/there/" ...
$_SERVER
... you would get this in your $_SERVER['REQUEST_URI']
[REQUEST_URI] => /hi/there%22 <---definitely URL encoded.
... this in $_SERVER['QUERY_STRING']
[QUERY_STRING] => url=/hi/there" <---probably URL decoded?
this in $_SERVER['SCRIPT_NAME']
[SCRIPT_NAME] => /hi/there" <---probably URL decoded?
... and, this in $_SERVER['SCRIPT_URL']
[SCRIPT_URL] => /hi/there" <---probably URL decoded?
$_GET
[url] => /hi/there/" <---probably URL decoded.
3) Am I wrong for wanting to use the values without %22? What I mean is, "Am I wrong for wanting to send that input through my filters, as opposed to the value with %22" For instance I use FILTER_SANITIZE_URL and FILTER_VALIDATE_URL (among other techniques) to validate URLs.
Note: After establishing a centralized index.php, my filters on INPUT_SERVER (just 6 or 7 elements) started failing (all 6 or 7). I use filter_input_array() Anyone experience something similar? I can figure it out. It just started happening after implementing the rewrite rule above.
Why would anyone use $_SERVER['REQUEST_URI'] over $_GET['url'] in PHP after URL rewriting occurs for an MVC Router?
Because using your approach means my app can't have a query string parameter of url anywhere in it, and I'll get weird, hard to diagnose behavior if I forget that. Diagnosing why submit?url=google.com gives me a 404 won't be much fun.
Laravel's .htaccess rule is just:
RewriteRule ^ index.php [L]
It'll get the route from $_SERVER['REQUEST_URI'], and parse it accordingly.
Do I need to specify the absolute path (seems so, as RewriteBase is not appropriate in this context)?
No, and you shouldn't, so your code is portable to other servers where files may be differently located.
3) Am I wrong for wanting to use the values without %22?
Yes, you are. Don't use invalid unescaped characters like " in routes.
The short answer is that $_GET['url'] doesn't magically exist in PHP. You need to have an entire framework setup and configured in the way you want for a value like this to exist.
In your case, you have some MVC router setup. So you should use the $_GET['url'] as it seems to be parsed by whatever framework you're using.
If you were to create a fresh PHP script with no dependencies or frameworks, $_GET['url'] will be undefined.
I prefer to parse Routes as so:
// Parse Request
$route = "";
$routes = [];
$url_components = explode('/', $_SERVER['REQUEST_URI']);
foreach($url_components as $key => $val)
{
if(empty($val))
{
if(!$key)continue;
$route .= 'index/';
continue;
}
$routes[] = $val;
$route .= "$val/";
}
// Examine Result
$_GET['url'] = $route;
echo "Route: $_GET[url]\n";
echo "Routes Array: <pre>".var_export($routes, true)."</pre>";
Hope this helps.

How to make a URL link like this http://stackoverflow.com/questions/tagged/php [duplicate]

When you edit a question on stackoverflow.com, you will be redirected to a URL like this:
https://stackoverflow.com/posts/1807421/edit
But usually, it should be
https://stackoverflow.com/posts/1807491/edit.php
or
https://stackoverflow.com/posts/edit.php?id=1807491
How was
https://stackoverflow.com/posts/1807421/edit
created?
I know that Stackoverflow.com was not created by using PHP, but I am wondering how to achieve this in PHP?
With apache and PHP, you might perform one of your examples using a mod_rewrite rule in your apache config as follows:
RewriteEngine On
RewriteRule ^/posts/(\d+)/edit /posts/edit.php?id=$1
This looks for URLs of the "clean" form, and then rewrites them so that they are internally redirected to a particular PHP script.
Quite often rules like this are used to route all requests into a common controller script, which might do something like instantiate a "PostsController" class and ask it to handle an edit request. This is a common feature of most PHP application frameworks.
It's called routing. Take a look at tutorials on the subject.
If you use a framework such as cake php it should be built in.
As #mr-euro stated you can use mod_rewrite but front controller is a far better solution.
You force every request to index.php and you write your application controlling in index.php.
You use Apache's .htaccess/mod_rewrite, and optionally a PHP file, which is the approach I like to take myself.
For the .htaccess, something like this:
RewriteEngine On
RewriteRule ^(.*)$ index.php
Then in your PHP file, you can do something like this:
The following should get everything after the first slash.
$url = $_SERVER['REQUEST_URI'];
You can then use explode to turn it into an array.
$split = explode('/', $url);
Now you can use the array to determine what to load:
if ($split[1] == 'home')
{
// display homepage
}
The array is starting from 1 since 0 will usually be empty.
It's indeed done by mod_rewrite, or with multiviews. But i prefer mod_rewrite.
First: you create a .htaccessfile with these contents:
RewriteEngine On
RewriteRule ^posts/([0-9])/(edit|delete)$ /index.php?page=posts&postId=$1&action=$2
Obvious, mod_rewrite must be enabled by your hostingprovider ;)
Using mod_rewrite this can be achieved very easily.
I am poor at this but i do know you can redirect urls using apache mod_rewrite and by touching config files. From what i remember htaccess can be used to redirect. Then internally when the user hits
http://stackoverflow.com/posts/1807421/edit it can use your page http://stackoverflow.com/edit.php?p=1807421 instead or whatever you want.
You could use htaccess + write an URI parser class.

how to use $_GET with this url format site.com/extension/rar

I am seeing this url format at most websites.
site.com/extension/rar
I wonder how they get the value='rar' using $_GET.
What I know is that $_GET can be use in here
site.com/extension/index.php?ext=rar
Now I wanted to change my way of calling a variable.
I wanted to apply what most websites do.
How can I call variable in the former?
Perhaps this works to get the "rar":
$name = basename($_SERVER['REQUEST_URI']);
I most likely being done using .htaccess
It is an Apache module that allows you "rewrite" urls at the engine level based on your own set of rules. So basically it rewrites URLs on the fly.
So, in your example you could have a file named .htaccess with the following contents: (there may be other options)
RewriteEngine On
RewriteRule ^extension/([a-z0-9]+)$ somefile.php?extension=$1 [L]
Basically, you are saying: If someone is looking for a URL that looks like "extension/somenumbers-and-letters" then show the contents of "somefile.php?extension=whatever-those-number-and-leters-are".
Do a search on Apache mod_rewrite to find more information.

How to create dynamic/friendly URLs using PHP?

Can anyone explain how to create friendly URLs? I mean URLs like http://store.steampowered.com/app/22600/ that doesn't have any pages like index.php visible.
If you only have cpanel use .htaccess.
If that doesn't work, you are left with parsing the url in php with a link like this:
http://server.com/router.php/search
You can do that with something like this.
<?
list($junk,$url) = explode("router.php",$_SERVER['REQUEST_URI']);
$paths = explode("/", $url);
if ($paths[0] == 'search')
{
Header("Location: /search.php");
}
?>
http://articles.sitepoint.com/article/search-engine-friendly-urls
http://www.alistapart.com/articles/succeed/
Search revealed dozens more
You need to look up apache mod_rewrite (assuming you are using apache for your web server). PHP itself doesn't do it for you the web server does most of the work. You need to tell your web server to use mod_rewrite to point all urls that match a certain pattern to point to what ever .php file you like. You can pass arguments in your url pattern what ever way you choose. e.g. using the / to delimit key values or just values. If you don't have root access to the server and its enabled you can usually put these mod rewrite rules in a .htaccess file at the root of your site.
Sitepoint have a good reference for beginners.
http://articles.sitepoint.com/article/guide-url-rewriting
if you're using apache this should work/is the idea:
RewriteRule ^(.*)$ /index.php?/$1 [L]
now your url will go to http://store.steampowered.com/index.php/app/22600/

How was a URL like http://stackoverflow.com/posts/1807421/edit created in PHP?

When you edit a question on stackoverflow.com, you will be redirected to a URL like this:
https://stackoverflow.com/posts/1807421/edit
But usually, it should be
https://stackoverflow.com/posts/1807491/edit.php
or
https://stackoverflow.com/posts/edit.php?id=1807491
How was
https://stackoverflow.com/posts/1807421/edit
created?
I know that Stackoverflow.com was not created by using PHP, but I am wondering how to achieve this in PHP?
With apache and PHP, you might perform one of your examples using a mod_rewrite rule in your apache config as follows:
RewriteEngine On
RewriteRule ^/posts/(\d+)/edit /posts/edit.php?id=$1
This looks for URLs of the "clean" form, and then rewrites them so that they are internally redirected to a particular PHP script.
Quite often rules like this are used to route all requests into a common controller script, which might do something like instantiate a "PostsController" class and ask it to handle an edit request. This is a common feature of most PHP application frameworks.
It's called routing. Take a look at tutorials on the subject.
If you use a framework such as cake php it should be built in.
As #mr-euro stated you can use mod_rewrite but front controller is a far better solution.
You force every request to index.php and you write your application controlling in index.php.
You use Apache's .htaccess/mod_rewrite, and optionally a PHP file, which is the approach I like to take myself.
For the .htaccess, something like this:
RewriteEngine On
RewriteRule ^(.*)$ index.php
Then in your PHP file, you can do something like this:
The following should get everything after the first slash.
$url = $_SERVER['REQUEST_URI'];
You can then use explode to turn it into an array.
$split = explode('/', $url);
Now you can use the array to determine what to load:
if ($split[1] == 'home')
{
// display homepage
}
The array is starting from 1 since 0 will usually be empty.
It's indeed done by mod_rewrite, or with multiviews. But i prefer mod_rewrite.
First: you create a .htaccessfile with these contents:
RewriteEngine On
RewriteRule ^posts/([0-9])/(edit|delete)$ /index.php?page=posts&postId=$1&action=$2
Obvious, mod_rewrite must be enabled by your hostingprovider ;)
Using mod_rewrite this can be achieved very easily.
I am poor at this but i do know you can redirect urls using apache mod_rewrite and by touching config files. From what i remember htaccess can be used to redirect. Then internally when the user hits
http://stackoverflow.com/posts/1807421/edit it can use your page http://stackoverflow.com/edit.php?p=1807421 instead or whatever you want.
You could use htaccess + write an URI parser class.

Categories