Create a Catch-All Handler in PHP?

允我心安 提交于 2019-12-03 13:43:09

问题


I want to have a PHP file catch and manage what's going to happen when users visit:

http://profiles.mywebsite.com/sometext

sometext is varying.

E.g. It can be someuser it can be john, etc. then I want a PHP file to handle requests from that structure.

My main goal is to have that certain PHP file to redirect my site users to their corresponding profiles but their profiles are different from that URL structure. I'm aiming for giving my users a sort of easy-to-remember profile URLs.

Thanks to those who'd answer!


回答1:


Either in Apache configuration files [VirtualHost or Directory directives], or in .htaccess file put following line:

Options -MultiViews

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L,NC,QSA]
</IfModule>

It will silently redirect all incoming requests that do not correspond to valid filename or directory (RewriteCond's in the code above make sure of that), to index.php file. Additionally, as you see, MultiViews option also needs to be disabled for redirection to work - it generally conflicts with these two RewriteCond's I put there.

Inside index.php you can access the REQUEST_URI data via $_SERVER['REQUEST_URI'] variable. You shouldn't pass any URIs via GET, as it may pollute your Query-String data in an undesired way, since [QSA] parameter in our RewriteRule is active.




回答2:


You should use a rewrite rule..

In apache (.htaccess), something like this:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ /index.php?url=$1 [QSA,L]
</IfModule>

Then in your index.php you can read $_GET['url'] in your php code.




回答3:


You can use a .htaccess file (http://httpd.apache.org/docs/1.3/howto/htaccess.html) to rewrite your url to something like profiles.websites.com/index.php?page=sometext . Then you can do what you want with sometext in index.php.




回答4:


An obvious way to do this would be via the 404 errorDocument - saves all that messing about with mod_rewrite.




回答5:


If you have not heard about MVC, its time you hear it, start with CodeIgniter, its simplest and is quite fast, use default controller and you can have URLs like
domain.com/usernam/profile
domain.com/usernam/profile/edit
domain.com/usernam/inbox
domain.com/usernam/inbox/read/messageid Or use .htaccess wisely



来源:https://stackoverflow.com/questions/5218213/create-a-catch-all-handler-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!