복붙노트

간단한 포스트 리디렉션 - 코드 예제보기

PHP

간단한 포스트 리디렉션 - 코드 예제보기

PRG를 설명하는 사이트가 많이 있지만 간단한 PHP 코드 예제는 없습니다.

여기에 제가 구현 한 것이 있습니다 :

그것은 페이지 재로드 및 뒤로 버튼 문제에 대한 보호 기능을 좋아하는 것 같습니다.

나는 바퀴를 재발 명하려고 노력하여 멍청 했니?

해결법

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

    1.가장 단순한 시나리오 :

    가장 단순한 시나리오 :

    if ($_POST) {
       // Execute code (such as database updates) here.
    
       // Redirect to this page.
       header("Location: " . $_SERVER['REQUEST_URI']);
       exit();
    }
    

    REQUEST_URI를 사용하십시오. 대부분의 CMS 시스템 및 프레임 워크에서 PHP_SELF를 사용하지 마십시오. PHP_SELF는 /index.php를 참조합니다.

  2. ==============================

    2.코드 스 니펫 :

    코드 스 니펫 :

    if (count($_POST)) {
        // process the POST data
        // your code here- so for example to log a user in, register a new account..
        // ...make a payment...etc
    
        // redirect to the same page without the POST data, including any GET info you
        // want, you could add a clause to detect whether processing the post data has 
        // been successful or not, depending on your needs
    
        $get_info = "?status=success";
    
        // if not using rewrite
        // header("Location: ".$_SERVER['PHP_SELF'].$get_info);
    
        // if using apache rewrite
        header("Location: ".$_SERVER['REQUEST_URI'].$get_info);
        exit();
    }
    
  3. ==============================

    3.

        Browser
       HTML form
      method=POST
           |
           v
        PHP app
      reads $_POST
    sends 303 header
           |
           v
        Browser
    receives header
     redirected to
       new page
           |
           v
        PHP app
      reads $_GET
     does whatever
    

    일반적인 사용은 로그인 인증입니다. 이것이 사용자가 로그인 양식을 제출할 때의 프로세스 흐름입니다. PHP 앱은 $ _POST vars를 통해 사용자를 인증합니다. 사용자가 성공적으로 인증 한 경우 303 헤더를 다시 브라우저로 보냅니다. 따라서 사용자는 새 페이지로 리디렉션됩니다.

  4. ==============================

    4.Caller.htm

    Caller.htm

    <form method="post" action="Callee.php?Query1">
        <input type="text"   name="PostData" />
        <input type="submit" value="Go"      />
    </form>
    

    Callee.php (두 번 호출됩니다.)

    if ($_POST) {
        header("Location: ". $_SERVER['REQUEST_URI']. 'Query2'); 
        // PART1: Use $_POST and $_GET to execute database updates here...
    
        // Now any display (i.e. echo or print) will come after the header.
        // ...
    
    
       die;  // When done, GET 'myself' to execute PART2 below.
    }
    
    
    // PART2: Results page goes here...
    echo 'PART 2 display output: '; var_dump($_GET);
    

    두 개의 쿼리 문자열이 관련되어 있습니다.

    var_dump가 $ _GET에 대해 말하는 것을보세요 :

    PART 2 display output: array(1) { ["Query1Query2"]=> string(0) "" } 
    

    다음과 같이 POST 섹션의 끝에 헤더를 넣는 문제 :

    header("Location: ". $_SERVER['REQUEST_URI']. 'Query2'); die;
    

    php 매뉴얼은 다음과 같이 말합니다 : "실제 HTML 태그, 파일의 빈 줄 또는 PHP에서 실제 출력을 보내기 전에 header ()를 호출해야합니다. include를 사용하여 코드를 읽는 것은 매우 일반적인 오류입니다. require, functions 또는 다른 파일 액세스 함수를 사용하고 header ()가 호출되기 전에 공백이나 빈 줄이 출력됩니다. 하나의 PHP / HTML 파일을 사용할 때도 같은 문제가 발생합니다. "

    그러나 POST 섹션에서 일어난 일을 기반으로 'Query2'를 빌드해야하는 경우 POST 섹션의 맨 아래에 있어야합니다. 에코를 삽입하려고하지 않는 한 괜찮습니다. 테스트를 위해서조차도 아닙니다.

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

    5.더 큰 규모로 프레임 워크에서 훨씬 더 자세하게 사용되는 방법을 소개하고자합니다.

    더 큰 규모로 프레임 워크에서 훨씬 더 자세하게 사용되는 방법을 소개하고자합니다.

    index.php라는 파일이 있습니다.

    <?php
    if (!isset($_SESSION)) session_start();
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        switch ($_POST['submit']) {
            case 'add':
                // This is where our first POST will end up
                // We can perform actions such as checking the data here
    
                // After that we will add the POST data to a session
                $_SESSION['postdata'] = $_POST;
                // and unset the $_POST afterwards, to prevent refreshes from resubmitting.
                unset($_POST);
    
                // Now we will redirect...
                header("Location: ".$_SERVER['PHP_SELF']);
                break;
            case 'confirm':
                // We can now insert the data into the database or email it
    
                // Then we will unset the session and redirect back
                unset($_SESSION['postdata']);
    
                // This is to display our notification
                $_SESSION['success'] = true;
    
                // And there we go again...
                header("Location: ".$_SERVER['PHP_SELF']);
                break;
        }
        // We will exit here because we don't want the script to execute any further.
        exit;
    }
    ?>
    
    <?php if (isset($_SESSION['success']) && $_SESSION['success'] == true): ?>
        <p>Our data has been processed succesfully</p>
        <?php unset($_SESSION['success']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['postdata'])): ?>
        <p>
            You want to add the following data:<br />
            <pre><?php print_r($_SESSION['postdata']); ?></pre>
            Is this correct?<br />
            <form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
                <button type="submit" value="confirm">Yes</button>
            </form>
        </p>
    <?php else: ?>
        <p>
            <form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
                <input type="text" name="..."><br />
                <input type="text" name="..."><br />
                <input type="text" name="..."><br />
                <input type="text" name="..."><br />
                <button type="submit" value="add">Add something</button>
            </form>
        </p>
    <?php endif; ?>
    
  6. ==============================

    6.다음은 form.php입니다.

    다음은 form.php입니다.

    <?php
    session_start();
    // 1) _____________________________________________ POST _____________________________
    if ( count($_POST) ) {
        $ermsg ='';
        …
        check data, write some data to database(s), set error message(s) if any
        …
        $userdata1 = $_POST['htUserdata1'];
        $userdata2 = $_POST['htUserdata2'];
        …
    
        $_SESSION['PRG'] = array('field1'=>$userdata1,'field2'=>$userdata1,…,'ermsg'=>$ermsg);
        session_write_close();
        header('Location: ' . $_SERVER['REQUEST_URI'].'?z',true,303);
        exit;
    // 2) _____________________________________________ REDIRECT ________________________
    } else if ( array_key_exists('PRG',$_SESSION) ) {
        $userdata1 = $_SESSION['PRG']['field1'];
        $userdata2 = $_SESSION['PRG']['field2'];
        …
        $ermsg = $_SESSION['PRG']['ermsg'];
        unset($_SESSION['PRG']);
    // 3) _____________________________________________ GET ______________________________
    } else {
        …
        retrieve data from database(s)
        …
        $userdata1 = dbGet1();
        $userdata2 = dbGet2();
        …
        $ermsg = '';
    }
    // 4) _____________________________________________ DISPLAY _________________________
    ?>
    <!DOCTYPE html>
    <html lang="fr">
        …
    <form method="post" action="form.php" accept-charset="utf-8">
            <input id="htUserdata1" name="htUserdata1" type="text"/>
            <input id="htUserdata2" name="htUserdata2" type="text"/>
            …
    </form>
    <script language="javascript">
    "use strict";
    <?php
    $G['htUserdata1'] = $userdata1;
    $G['htUserdata2'] = $userdata2;
        …
    $G['ermsg'] = $ermsg;
    $myJSON = json_encode($G);
    echo "var G=$myJSON;";
    ?>
    document.getElementById('htUserdata1').value = G.htUserdata1;
    document.getElementById('htUserdata2').value = G.htUserdata2;
        …
    if ( G.ermsg !=='')    alert(G.ermsg);
    </script></body></html>
    
  7. from https://stackoverflow.com/questions/4142809/simple-post-redirect-get-code-example by cc-by-sa and MIT license