복붙노트

PHP에서 친숙한 URL을 만드는 방법?

PHP

PHP에서 친숙한 URL을 만드는 방법?

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

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

여기서 u = 12345는 사용자 ID입니다.

최근 몇 년 동안 나는 다음과 같은 아주 멋진 URL을 가진 웹 사이트를 발견했다.

www.domain.com/profile/12345

PHP로 어떻게 할 수 있습니까?

야생의 추측과 마찬가지로 .htaccess 파일과 관련이 있습니까? .htaccess 파일을 작성하는 방법에 대한 팁이나 샘플 코드를 줄 수 있습니까?

해결법

  1. ==============================

    1.

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

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

    그리고 이것은

    /news.php?news_id=63
    

    /news/63.html
    

    또 다른 가능성은 forcetype을 사용하는 것입니다. forcetype은 특정 경로를 따라 무엇이든 강제 실행하여 PHP를 사용하여 컨텐츠를 평가합니다. 따라서 .htaccess 파일에 다음을 입력하십시오.

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

    그런 다음 index.php는 $ _SERVER [ 'PATH_INFO'] 변수를 기반으로 작업을 수행 할 수 있습니다.

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

    2.

    나는 최근에 나의 필요를 위해 잘 작동하는 응용 프로그램에서 다음을 사용했다.

    .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.
    }
    
  3. ==============================

    3.

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

    0) 질문

    나는 너에게 이렇게 물어 보려고한다.

    나는 facebook profile www.facebook.com/kaila.piyush와 같은 페이지를 열고 싶다.

    그것은 url에서 id를 얻고 그것을 profile.php 파일로 구문 분석하고 데이터베이스로부터 feat 데이터를 반환하고 사용자를 그의 프로필에 보여줍니다.

    일반적으로 우리는 어떤 웹 사이트도 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 permalink로 사용합니다.

    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);
    }
    
  4. ==============================

    4.

    이것을하는 간단한 방법. 이 코드를 사용해보십시오. htaccess 파일에 코드 삽입 :

    Options +FollowSymLinks
    
    RewriteEngine on
    
    RewriteRule profile/(.*)/ profile.php?u=$1
    
    RewriteRule profile/(.*) profile.php?u=$1   
    

    이 유형의 예쁜 URL을 만듭니다.

    더 많은 htaccess를 위해 예쁜 URL : http : //www.webconfs.com/url-rewriting-tool.php

  5. ==============================

    5.

    사실 PHP가 아닙니다. mod_rewrite를 사용하는 아파치입니다. 그 사람이 www.example.com/profile/12345 링크를 요청하면 apache는 다시 작성 규칙을 사용하여 www.example.com/profile.php?u=12345처럼 보이게 만듭니다. 섬기는 사람. 자세한 내용은 여기를 참조하십시오 : 재 작성 안내서

  6. ==============================

    6.

    Mod_Rewrite가 유일한 답이 아닙니다. 또한 .htaccess에서 Options + MultiViews를 사용하고 $ _SERVER REQUEST_URI를 확인하여 URL에있는 모든 것을 찾을 수 있습니다.

  7. ==============================

    7.

    이를 수행하는 여러 가지 방법이 있습니다. 한 가지 방법은 앞서 언급 한 RewriteRule 기술을 사용하여 쿼리 문자열 값을 마스크하는 것입니다.

    내가 좋아하는 방법 중 하나는 전면 컨트롤러 패턴을 사용하는 경우 http://yoursite.com/index.php/path/to/your/page/here와 같은 URL을 사용하여 $ _SERVER의 값을 파싱 할 수 있다는 것입니다. [ 'REQUEST_URI'].

    다음 코드를 사용하여 / path / to / your / page / here 비트를 쉽게 추출 할 수 있습니다.

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

    거기에서, 당신은 당신을 만족시키지 만 그것을 파싱 할 수는 있지만, 피트를 위해서 당신이 그것을 위생적으로하는지 확인하십시오;)

  8. ==============================

    8.

    RESTful 웹 서비스에 대해 이야기하는 것 같습니다.

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

    .htaccess 파일은 모든 URI를 하나의 컨트롤러를 가리 키도록 다시 작성하지만이 시점에서 얻으려는 것이 더 자세합니다. 리세 스를보고 싶을 수도 있습니다.

    그것은 PHP에서 모두 RESTful 프레임 워크입니다.

  9. from https://stackoverflow.com/questions/812571/how-to-create-friendly-url-in-php by cc-by-sa and MIT lisence