如何更正 PHP 在本地服务器中重定向次数过多的说法?

How can I correct PHP saying redirected too many times in local server?

我是新手,遇到一些问题需要帮助。 我如何更正 PHP 导致本地服务器出现“无连接”或“重定向次数过多”错误的代码? 我有 register.php 文件以及 index.php 和 errors.php 文件。 这是 server.php 代码。我不知道该怎么办。

<?php
session_start();

// initializing variables
$username = "";
$phone = "";
$email    = "";
$gender = "";
$errors = array();

// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'work');

// REGISTER USER
if (isset($_POST['reg_user'])) {
  // receive all input values from the form
  $username = 
mysqli_real_escape_string($db, $_POST['username']);
  $phone = 
mysqli_real_escape_string($db, $_POST['phone']);
  $email = 
mysqli_real_escape_string($db, $_POST['email']);
  $password_1 = 
mysqli_real_escape_string($db, $_POST['password_1']);
  $password_2 = 
mysqli_real_escape_string($db, $_POST['password_2']);
  $gender = 
mysqli_real_escape_string($db, $_POST['gender']);
  $occupation = 

  // form validation: ensure that the form is correctly filled ...

  // by adding (array_push()) corresponding error unto $errors array

  if (empty($username)) 
{ array_push($errors, "Username is required"); }
  if (empty($phone)) 
{ array_push($errors, "Phone is required"); }
  if (empty($password_1)) 
{ array_push($errors, "Password is required"); }
  if ($password_1 != $password_2) {
  array_push($errors, "The two passwords do not match");}
  if (empty($gender)) 
{ array_push($errors, "Gender is required"); }

  // first check the database to make sure 

  // a user does not already exist with the same username and/or phone

  $user_check_query = "SELECT * FROM register WHERE phone='$phone' LIMIT 1";
  $result = mysqli_query($db, $user_check_query);
  $user = mysqli_fetch_assoc($result);
  
  if ($user['phone'] === $phone) {
      array_push($errors, "Phone No already used");
  }
 }
  // Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
    $password = md5($password_1);//encrypt the password before saving in the database
  $query = "INSERT INTO register (username, phone, password, gender) 
      VALUES('$username', '$phone', '$password', '$gender')";
  mysqli_query($db, $query);
  $_SESSION['phone'] = $phone;
  $_SESSION['success'] = "You are now logged in";
header('location: index.php');
  }
// ...
?>

谢谢

我的猜测是,代码向您发出有关 "too many redirects" 警告的原因是调用 if (count($errors) == 0) { 时没有进行任何测试以查看是否存在合适的 POSTed数据,此时 $errors 数组是空的 - 所以如果你碰巧 POST 到与表单相同的页面,你会得到一个无限循环(因此重定向太多)

一个解决方案是将处理 insert 的那部分代码移动到 IF 块内,如此处快速完成。

你真的,真的应该使用 Prepared Statement 并避免 mysqli_real_escape_string 这可能会改变数据。

<?php
    session_start();

    $username = "";
    $phone = "";
    $email    = "";
    $gender = "";
    $errors = array();

    $db = mysqli_connect('localhost', 'root', '', 'work');

    
    
    if (isset($_POST['reg_user'])) {
    
        $username = mysqli_real_escape_string($db, $_POST['username']);
        $phone = mysqli_real_escape_string($db, $_POST['phone']);
        $email = mysqli_real_escape_string($db, $_POST['email']);
        $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
        $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
        $gender = mysqli_real_escape_string($db, $_POST['gender']);
        $occupation = 


        if (empty($username)) { 
            array_push($errors, "Username is required"); 
        }
        if (empty($phone)) { 
            array_push($errors, "Phone is required"); 
        }
        if (empty($password_1)) { 
            array_push($errors, "Password is required"); 
        }
        if ($password_1 != $password_2) {
            array_push($errors, "The two passwords do not match");
        }
        if (empty($gender)) { 
            array_push($errors, "Gender is required"); 
        }


        $user_check_query = "SELECT * FROM register WHERE phone='$phone' LIMIT 1";
        $result = mysqli_query($db, $user_check_query);
        $user = mysqli_fetch_assoc($result);

        if ($user['phone'] === $phone) {
            array_push($errors, "Phone No already used");
        }
      
        if (count($errors) == 0) {
        
            $password = md5($password_1);//encrypt the password before saving in the database
            $query = "INSERT INTO register (username, phone, password, gender) VALUES('$username', '$phone', '$password', '$gender')";
            mysqli_query($db, $query);
            
            $_SESSION['phone'] = $phone;
            $_SESSION['success'] = "You are now logged in";
            header('location: index.php');
        }   
    }
?>

使用 prepared statements 并略微改变逻辑的非常仓促的修改版本 ~ 完全未经测试,因此可能存在错误

<?php
    session_start();
    
    $db = mysqli_connect('localhost', 'root', '', 'work');
    
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
        $_POST['username'],
        $_POST['phone'],
        $_POST['email'],
        $_POST['password_1'],
        $_POST['password_2'],
        $_POST['gender']
    )){
        # the errors array only exists within the POST logic block
        # a standard GET request (ie: redirect ) will not enter this
        # block of code.
        
        $errors = array();
        
        
        $username = $_POST['username'];
        $phone = $_POST['phone'];
        $email = $_POST['email'];
        $gender = $_POST['gender'];
        $pwd1=$_POST['password_1'];
        $pwd2=$_POST['password_2'];
        
        
        if( empty($username) )$errors[]='username is required';
        if( empty($phone) )$errors[]='phone is required';
        if( empty($email) )$errors[]='email is required';
        if( empty($gender) )$errors[]='gender is required';
        if( empty($pwd1) )$errors[]='password 1 is required';
        if( empty($pwd1) )$errors[]='password 2 is required';
        
        if( $pwd1!==$pwd2 )$errors[]='Passwords do not match';

        
        # No errors at this stage - proceed to check phone number
        # to my mind this is odd - more usual to test an email than
        # a phone number but hey...
        
        if( empty( $errors ) ){
            
            # use a `Prepared Statement` ...
            $sql='select `phone` from `users` where `phone`=?';
            $stmt=$db->prepare( $sql );
            $stmt->bind_param('s',$phone);
            $res=$stmt->execute();
            
            if( $res ){
                $stmt->bind_result( $cphone );
                if( empty( $cphone ) ){
                
                    $sql='INSERT INTO `register` ( `username`, `phone`, `password`, `gender` ) VALUES (?, ?, ?, ?)';
                    $hash=password_hash($pwd,PASSWORD_DEFAULT);
                    
                    $stmt=$db->prepare($sql);
                    $stmt->bind_param('ssss',$username,$phone,$hash,$gender);
                    
                    $res=$stmt->execute();
                    $stmt->close();
                    
                    if( $res ){
                    
                        $_SESSION['username']=$username;
                        $_SESSION['phone'] = $phone;
                        $_SESSION['success'] = "You are now logged in";
                        
                        exit( header('Location: index.php') );  
                    }
                }
            }
        }else{
            foreach( $errors as $error ){
                printf('<div>%s</div>',$error);
            }
        }
    }
    

?>

你能加出口吗?重定向后

header('location: index.php');
exit;