php 如何在php中创建友好的URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/812571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:56:05  来源:igfitidea点击:

How to create friendly URL in php?

phpurlfriendly-url

提问by Peter

Normally, the practice or very old way of displaying some profile page is like this:

通常,显示一些个人资料页面的做法或非常古老的方式是这样的:

www.domain.com/profile.php?u=12345

where u=12345is the user id.

u=12345用户 ID在哪里。

In recent years, I found some website with very nice urls like:

近年来,我发现一些网站的网址非常好,例如:

www.domain.com/profile/12345

How do I do this in PHP?

我如何在 PHP 中做到这一点?

Just as a wild guess, is it something to do with the .htaccessfile? Can you give me more tips or some sample code on how to write the .htaccessfile?

就像一个疯狂的猜测,这与.htaccess文件有关吗?你能给我更多关于如何编写.htaccess文件的提示或一些示例代码吗?

回答by cgp

According to this article, you want a mod_rewrite (placed in an .htaccessfile) rule that looks something like this:

根据这篇文章,您需要一个.htaccess看起来像这样的 mod_rewrite(放置在文件中)规则:

RewriteEngine on
RewriteRule ^/news/([0-9]+)\.html /news.php?news_id=

And this maps requests from

这映射了来自

/news.php?news_id=63

to

/news/63.html

Another possibility is doing it with forcetype, which forces anything down a particular path to use php to eval the content. So, in your .htaccessfile, put the following:

另一种可能性是使用forcetype,这会强制任何东西沿着特定路径使用 php 来评估内容。因此,在您的.htaccess文件中,输入以下内容:

<Files news>
    ForceType application/x-httpd-php
</Files>

And then the index.php can take action based on the $_SERVER['PATH_INFO']variable:

然后 index.php 可以根据$_SERVER['PATH_INFO']变量采取行动:

<?php
    echo $_SERVER['PATH_INFO'];
    // outputs '/63.html'
?>

回答by Jordan S. Jones

I recently used the following in an application that is working well for my needs.

我最近在一个非常适合我的需求的应用程序中使用了以下内容。

.htaccess

.htaccess

<IfModule mod_rewrite.c>
# enable rewrite engine
RewriteEngine On

# if requested url does not exist pass it as path info to index.php
RewriteRule ^$ index.php?/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?/ [QSA,L]
</IfModule>

index.php

索引.php

foreach (explode ("/", $_SERVER['REQUEST_URI']) as $part)
{
    // Figure out what you want to do with the URL parts.
}

回答by Piyush

I try to explain this problem step by step in following example.

我尝试在以下示例中逐步解释此问题。

0) Question

0) 问题

I try to ask you like this :

我试着这样问你:

i want to open page like facebook profile www.facebook.com/kaila.piyush

我想打开像 facebook 个人资料 www.facebook.com/kaila.piyush 这样的页面

it get id from url and parse it to profile.php file and return featch data from database and show user to his profile

它从 url 获取 id 并将其解析为 profile.php 文件并从数据库返回 featch 数据并将用户显示到他的个人资料

normally when we develope any website its link look like www.website.com/profile.php?id=username example.com/weblog/index.php?y=2000&m=11&d=23&id=5678

通常当我们开发任何网站时,它的链接看起来像 www.website.com/profile.php?id=username example.com/weblog/index.php?y=2000&m=11&d=23&id=5678

now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink

现在我们用新样式更新而不是重写我们使用 www.website.com/username 或 example.com/weblog/2000/11/23/5678 作为永久链接

http://example.com/profile/userid (get a profile by the ID) 
http://example.com/profile/username (get a profile by the username) 
http://example.com/myprofile (get the profile of the currently logged-in user)

1) .htaccess

1).htaccess

Create a .htaccess file in the root folder or update the existing one :

在根文件夹中创建一个 .htaccess 文件或更新现有文件:

Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
#  Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php

What does that do ?

那有什么作用?

If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.

如果请求是针对真实目录或文件(服务器上存在的目录或文件),则不会提供 index.php,否则每个 url 都会重定向到 index.php。

2) index.php

2)index.php

Now, we want to know what action to trigger, so we need to read the URL :

现在,我们想知道要触发什么操作,因此我们需要读取 URL:

In index.php :

在 index.php 中:

// index.php    

// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/', $_SERVER[‘REQUEST_URI']);
$scriptName = explode(‘/',$_SERVER[‘SCRIPT_NAME']);

for ($i= 0; $i < sizeof($scriptName); $i++)
{
    if ($requestURI[$i] == $scriptName[$i])
    {
        unset($requestURI[$i]);
    }
}

$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :

$command = array(
    [0] => 'profile',
    [1] => 19837,
    [2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :

// index.php

require_once("profile.php"); // We need this file
switch($command[0])
{
    case ‘profile' :
        // We run the profile function from the profile.php file.
        profile($command([1]);
        break;
    case ‘myprofile' :
        // We run the myProfile function from the profile.php file.
        myProfile();
        break;
    default:
        // Wrong page ! You could also redirect to your custom 404 page.
        echo "404 Error : wrong page.";
        break;
}

2) profile.php

2)profile.php

Now in the profile.php file, we should have something like this :

现在在 profile.php 文件中,我们应该有这样的内容:

// profile.php

function profile($chars)
{
    // We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)

    if (is_int($chars)) {
        $id = $chars;
        // Do the SQL to get the $user from his ID
        // ........
    } else {
        $username = mysqli_real_escape_string($char);
        // Do the SQL to get the $user from his username
        // ...........
    }

    // Render your view with the $user variable
    // .........
}

function myProfile()
{
    // Get the currently logged-in user ID from the session :
    $id = ....

    // Run the above function :
    profile($id);
}

回答by Hemal Halari

Simple way to do this. Try this code. Put code in your htaccessfile:

做到这一点的简单方法。试试这个代码。将代码放入您的htaccess文件中:

Options +FollowSymLinks

RewriteEngine on

RewriteRule profile/(.*)/ profile.php?u=

RewriteRule profile/(.*) profile.php?u=   

It will create this type pretty URL:

它将创建这种类型的漂亮 URL:

http://www.domain.com/profile/12345/

http://www.domain.com/profile/12345/

For more htaccess Pretty URL:http://www.webconfs.com/url-rewriting-tool.php

更多 htaccess 漂亮网址:http: //www.webconfs.com/url-rewriting-tool.php

回答by jacobangel

It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide

它实际上不是 PHP,它是使用 mod_rewrite 的 apache。发生的情况是该人请求链接 www.example.com/profile/12345,然后 apache 使用重写规则将其切碎,使其看起来像这样,www.example.com/profile.php?u=12345,到服务器。您可以在此处找到更多信息:重写指南

回答by empi

ModRewrite is not the only answer. You could also use Options +MultiViews in .htaccess and then check $_SERVER REQUEST_URIto find everything that is in URL.

ModRewrite 不是唯一的答案。您还可以在 .htaccess 中使用 Options +MultiViews 然后检查$_SERVER REQUEST_URI以查找 URL 中的所有内容。

回答by Shabbyrobe

There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.

有很多不同的方法可以做到这一点。一种方法是使用前面提到的 RewriteRule 技术来屏蔽查询字符串值。

One of the ways I really like is if you use the front controllerpattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/hereand parse the value of $_SERVER['REQUEST_URI'].

我真正喜欢的方法之一是,如果您使用前端控制器模式,您还可以使用像http://yoursite.com/index.php/path/to/your/page/here这样的 url并解析 $_SERVER 的值['REQUEST_URI']。

You can easily extract the /path/to/your/page/here bit with the following bit of code:

您可以使用以下代码轻松提取 /path/to/your/page/here 位:

$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));

From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)

从那里,您可以随心所欲地解析它,但为了皮特的缘故,请确保对其进行消毒;)

回答by ryanday

It looks like you are talking about a RESTful webservice.

看起来您在谈论 RESTful Web 服务。

http://en.wikipedia.org/wiki/Representational_State_Transfer

http://en.wikipedia.org/wiki/Representational_State_Transfer

The .htaccess file does rewrite all URIs to point to one controller, but that is more detailed then you want to get at this point. You may want to look at Recess

.htaccess 文件确实重写了所有 URI 以指向一个控制器,但这比您此时想要获得的要详细得多。你可能想看看Recess

It's a RESTful framework all in PHP

这是一个 RESTful 框架,全部使用 PHP