Create a Catch-All Handler in PHP?

2019-02-05 07:15发布

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!

5条回答
疯言疯语
2楼-- · 2019-02-05 07:26

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楼-- · 2019-02-05 07:41

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

查看更多
唯我独甜
4楼-- · 2019-02-05 07:44

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.

查看更多
狗以群分
5楼-- · 2019-02-05 07:44

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.

查看更多
我想做一个坏孩纸
6楼-- · 2019-02-05 07:44

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

查看更多
登录 后发表回答