表单处理后 PHP 重定向


PHP redirect after form processing

我一直盯着代码太久了,但是当我使用一个简单的脚本来保存表单时:

endif;
header('Location: http:/mysite.com/evo/codesaveindex.php');
?>

最后,页面重定向回自身很好,但是现在我这里有一个更长的脚本,我无法弄清楚在哪里或如何编码我的重定向:

<?php
  session_start();
  $directory = 'users/'.$_SESSION['username'].'/';
  //here you can even check if user selected 'Delete' option:
  if($_POST['Action'] == "DELETE"){
      $file_to_delete = $_POST['CodeList'];
      if(unlink($directory.'/'.$file_to_delete))
         echo $file_to_delete." deleted.";
      else
         echo "Error deleting file ".$file_to_delete;
  }
   if($_POST['Action'] == "SAVE"){
     //  If a session already exists, this doesn't have any effect.
session_start();
//  Sets the current directory to the directory this script is running in
chdir(dirname(__FILE__));
//  Breakpoint
if( empty($_SESSION['username']) || $_SESSION['username'] == '' ) echo 'There is no session username';
if( empty($_POST['CodeDescription']) || $_POST['CodeDescription'] == '' ) echo 'There is no POST desired filename';
//  This is assuming we are working from the current directory that is running this PHP file.
$USER_DIRECTORY = 'users/'.$_SESSION['username'];
//  Makes the directory if it doesn't exist
if(!is_dir($USER_DIRECTORY)):
    mkdir($USER_DIRECTORY);
endif;
//  Put together the full path of the file we want to create
$FILENAME = $USER_DIRECTORY.'/'.$_POST['CodeDescription'].'.txt';
if( !is_file( $FILENAME ) ):
    // Open the text file, write the contents, and close it.
    file_put_contents($FILENAME, $_POST['Code']);   
   endif;
   }
  ?>
可能是

你应该在重定向时使用查询字符串变量。

if($_POST['Action'] == "DELETE") {
    $file_to_delete = $_POST['CodeList'];
    if(unlink($directory.'/'.$file_to_delete)) {
        header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=1&file='.$file_to_delete);
    } else {
        header('Location: http:/mysite.com/evo/codesaveindex.php?deleted=0&              file='.$file_to_delete);
    }
}

在代码保存索引中.php:

if(isset($_GET['deleted'])&& $_GET['deleted']==1) {
    echo $file_to_delete." deleted.";
} elseif(isset($_GET['deleted'])&& $_GET['deleted']==0) {
    echo "Error deleting file ".$file_to_delete; 
}
如果输出了

html 之后的页面,则无法重定向。您需要使用输出缓冲或使用 javascript 重定向,或者组织它,以便在显示 HTML 之前进行重定向。

我有一个为这样的事情编写的类,应该非常易于使用class.route.php只需在您想要重定向的地方执行此操作:route::redirect('page', http_status);