In ASP.Net we have Httphandlers which can parse a request and accordingly redirect the user, mostly we use them for url-rewriting etc.
I would like to know do we have such functionality in PHP as well, if yes a example which explains it will be very helpful.
For instance if I am requesting a image file on some server , I would like to redirect it to some page if the request if from server x
some of the php frameworks offer similar functionality. if you want to redirect in php you would set the headers directly
eg
header('Location: http://www.invalid.com/newpage.pgp');
exit; // make sure to exit or the script will keep executing
if you want the current url etc, you would need to query the $_SERVER var
try this, and see what information you can get from your server
var_dump($_SERVER);
You would have to implement your own mechanism or use a framework. Zend Framework's Requests go through a similar concept but still quite different than the handlers.
If I understand HTTPHandlers correctly, this is generally done by a bit of trickery. Obviously any request that comes in to a web server (IIS,Apache,etc.) is going to try and match to a file.
GET /index.php HTTP 1.1
This request will reach the index.php
file, PHP will process that file, and then the response will be sent to the client. Obviously the client will see whatever output PHP produces.
HTTPHandlers work by seeing the incoming request and mapping that request to a segment of code (perhaps a function), but it has the luxury of telling the web server how a client should access that code via configuration.
The following is an example borrowed from microsoft which illustrates the mapping.
<httpHandlers>
<add verb="*" path="*.sync" type="MyHandler.SyncHandler, MyHandler" />
</httpHandlers>
In PHP, this can be done in a two step process. First, the web server needs to route all requests to a single PHP file. And second, that PHP file must direct the program flow.
In Apache you can configure the routing bit with a .htaccess
file in the root of your website. This example will route anything that doesn't exist on disk to index.php
.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ /index.php [NC,L]
From there, PHP just needs to know what url the user was looking for, and decide what to do. This can be done by using the REQUEST_URI
value passed from Apache.
$_SERVER['REQUEST_URI'];
So, if a user requests:
GET /profile/settings HTTP 1.1
REQUEST_URI
would be:
$url = $_SERVER['REQUEST_URI'];
echo $url; // => "/index.php/profile/settings"
Beyond that, a person could apply a regex to REQUEST_URI
and switch between a number of functions to handle the request.