Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

Simple PHP Post-Redirect-Get code example

I have found many sites that describes PRG, but no simple PHP code example.


Here's what I implemented:

  1. The form.php has an action: validate.php.
  2. The validate.php is never seen by the user; if validates all $_GET and, if valid writes it to database and generates the HTML of a confirmation page / if not valid, it generates the HTML of an error page explaining what is wrong.
  3. Whichever HTML is generated get stored in a $_SESSION variable and then validate.php calls header('Location: <as appropriate>);.
  4. The submitted.php of invalid_input.php (in case the user reads the URL) consists only of echo $_SESSION['form_html'];.

That seems to me like protection against both page reload and back button problems.

Did I goof by trying to reinvent the wheel?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simplest scenario:

if ($_POST) {
   // Execute code (such as database updates) here.

   // Redirect to this page.
   header( "Location: {$_SERVER['REQUEST_URI']}", true, 303 );
   exit();
}

Use REQUEST_URI. Do not use PHP_SELF as in most CMS systems and frameworks PHP_SELF would refer to /index.php.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...