PHP重定向无法正常工作 [英] php redirection not working

查看:101
本文介绍了PHP重定向无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有了这个注册脚本,该脚本将信息放入mysql数据库中.现在一切正常,当有人做错了事时会说出错误(例如未定义用户名")

Ive got this register script that puts the information into a mysql database. now it all works fine and when someone does something wrong its says the error (e.g. "Username not defined")

但是当它出错时,它看起来不是很好,因为它只在空白页面上显示消息,所以我想我将使其重定向到表单页面并在此处显示消息.

but when it goes wrong it does not look very good because it just displays the message on an empty page, so i thought i would make it redirect to the form page and display the message there.

这是工作脚本

$forename = $_POST['forename'];      
$surname = $_POST['surname'];       
$email = $_POST['email'];    
$password = $_POST['password'];    
$username = $_POST['username'];

$errors = array();

 if(!$username) {

    $errors[] = "Username is not defined";

 }

 if(!$password) {

    $errors[] = "Password is not defined";

 }

,然后继续.

现在我只是以为我可以做到

now i just thought i could do this

 $errors = array();

 if(!$username) {

    $errors[] = header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' ) ;

 }

 if(!$password) {

    $errors[] = "Password is not defined";

 }

但不,它所做的就是忽略它.

but no, all it does is ignore it.

有人可以帮我吗

如果需要,请随时要求更多脚本

please feel free to ask for more of the script if you need it

非常感谢康纳

推荐答案

它看起来不是很好,因为它只是在空白页上显示消息

it does not look very good because it just displays the message on an empty page,

出什么问题了?
为什么不再次显示该表单?字段已填写.
这将是一个用户友好的界面.

What's the problem?
Why not to show the form again? with fields already filled.
This is going to be a user-friendly interface.

只需将您的表单包含在已填充字段的同一页面中即可.
这比重定向到空白表格更常见.

Just include your form in the same page with fields populated.
That's more common way than your redirects to blank form.

这称为 POST/重定向/GET 模式,这里简短介绍的例子:

This is called POST/Redirect/GET pattern and here goes a short example of it:

代码

<?  
if ($_SERVER['REQUEST_METHOD']=='POST') {  

  $err = array();
  //performing all validations and raising corresponding errors
  if (empty($_POST['name']) $err[] = "Username field is required";  
  if (empty($_POST['text']) $err[] = "Comments field is required";  

  if (!$err) {  
    // if no errors - saving data 
    // and then redirect:
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
  }  else {
    // all field values should be escaped according to HTML standard
    foreach ($_POST as $key => $val) {
      $form[$key] = htmlspecialchars($val);
    }
} else {
  $form['name'] = $form['comments'] = '';  
}
include 'form.tpl.php';
?>  

模板

<? if ($err): ?>
  <? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
  <? endforeach ?>
<? endif ?>
<form>
  <input type="text" name="name" value="<?=$form['name']?>">
  <textarea name="comments"><?=$form['comments']?></textarea>
  <input type="submit">
</form>

这篇关于PHP重定向无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆