UFO ET IT

PHP에서 친숙한 URL을 만드는 방법은 무엇입니까?

ufoet 2020. 11. 24. 20:39
반응형

PHP에서 친숙한 URL을 만드는 방법은 무엇입니까?


일반적으로 일부 프로필 페이지를 표시하는 관행 또는 아주 오래된 방법은 다음과 같습니다.

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

u=12345사용자 ID는 어디에 있습니까 ?

최근 몇 년 동안 다음과 같은 매우 멋진 URL이있는 웹 사이트를 찾았습니다.

www.domain.com/profile/12345

PHP에서 어떻게합니까?

거친 추측처럼 .htaccess파일 과 관련이 있습니까? .htaccess파일 작성 방법에 대한 팁이나 샘플 코드를 더 줄 수 있습니까 ?


이 기사 에 따르면 .htaccess다음과 같은 mod_rewrite ( 파일에 배치 ) 규칙이 필요합니다.

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

그리고 이것은

/news.php?news_id=63

...에

/news/63.html

또 다른 가능성은을 사용하여 수행하는 것입니다forcetype .이 경우 특정 경로에있는 모든 작업이 php를 사용하여 콘텐츠를 평가하도록합니다. 따라서 .htaccess파일에 다음을 입력하십시오.

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

그런 다음 index.php는 $_SERVER['PATH_INFO']변수 에 따라 조치를 취할 수 있습니다 .

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

최근에 내 요구에 잘 맞는 응용 프로그램에서 다음을 사용했습니다.

.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?/$1 [QSA,L]
</IfModule>

index.php

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

다음 예제에서이 문제를 단계별로 설명하려고합니다.

0) 질문

나는 당신에게 이렇게 물어 보려고 노력합니다 :

나는 페이스 북 프로필 www.facebook.com/kaila.piyush와 같은 페이지를 열고 싶다

URL에서 ID를 가져와 profile.php 파일로 구문 분석하고 데이터베이스에서 featch 데이터를 반환하고 사용자를 자신의 프로필에 표시합니다.

일반적으로 웹 사이트를 개발할 때 링크는 www.website.com/profile.php?id=username example.com/weblog/index.php?y=2000&m=11&d=23&id=5678과 같습니다.

이제 다시 작성하지 않고 새 스타일로 업데이트합니다. 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

루트 폴더에 .htaccess 파일을 생성하거나 기존 파일을 업데이트합니다.

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

그게 무엇을합니까?

요청이 실제 디렉토리 또는 파일 (서버에있는 파일)에 대한 것이면 index.php가 제공되지 않고 그렇지 않으면 모든 URL이 index.php로 리디렉션됩니다.

2) index.php

이제 어떤 작업을 트리거할지 알고 싶으므로 URL을 읽어야합니다.

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

이제 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);
}

이를 수행하는 간단한 방법입니다. 이 코드를 사용해보십시오. htaccess파일에 코드를 넣으십시오 .

Options +FollowSymLinks

RewriteEngine on

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

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

이 유형의 예쁜 URL을 생성합니다.

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

더 많은 htaccess Pretty URL : http://www.webconfs.com/url-rewriting-tool.php


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


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


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

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

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

$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 ;)


It looks like you are talking about a RESTful webservice.

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

It's a RESTful framework all in PHP

참고URL : https://stackoverflow.com/questions/812571/how-to-create-friendly-url-in-php

반응형