簡體   English   中英

無論什么情況,使用header()重定向都將無效

[英]Redirection with header() won't work no matter what

(花了整整一整天的時間,部分原因是PHP,Eclipse和Web編程通常不是我的專長。也許有人可以提供幫助)。

我在register.php代碼不會重定向到verify.php 這是代碼:

header ( "Location: verify.php" );
die ( "Redirecting to activation" );

它僅在瀏覽器中顯示Redirecting to activation ,並保留在register.php

我已經嘗試過的事情:

  • 我已經確保代碼實際上執行了直到header行上方的所有操作。
  • 我的文件在<?php塊之前沒有任何html或空格。
  • 在頂部添加ob_start()似乎沒有任何改變。
  • <?php塊沒有任何echoprint

編輯

根據要求,這是整個register.php

<?php
require 'config.php';

function isValid() {
    try {
        $url = 'https://www.google.com/recaptcha/api/siteverify';

        $data = array (
                'secret' => 'asdf4234234kljsd32902341',
                'response' => $_POST ['g-recaptcha-response'],
                'remoteip' => $_SERVER ['REMOTE_ADDR']
        );

        $options = array (
                'http' => array (
                        'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                        'method' => 'POST',
                        'content' => http_build_query ( $data )
                )
        );

        $context = stream_context_create ( $options );
        $result = file_get_contents ( $url, false, $context );
        return json_decode ( $result )->success;
    } catch ( Exception $e ) {
        return $e->getMessage ();
    }
}
function RunScalarQuery($db, $q, $params) {
    try {
        $stmt = $db->prepare ( $q );
        $result = $stmt->execute ( $params );
    } catch ( PDOException $ex ) {
        die ( "Failed to run query: " . $ex->getMessage () );
    }

    $row = $stmt->fetch ();
    if ($row)
        return $row [0];
        else
            return null;
}
function SendMail($smtpServer, $username, $pwd, $port, $from, $fromName, $to, $toName, $cc, $bcc, $subject, $body, $altBody) {
    require 'PHPMailerAutoload.php';

    $mail = new PHPMailer ();

    $mail->isSMTP (); // Set mailer to use SMTP
    $mail->Host = $smtpServer; // Specify main and backup SMTP servers
    $mail->SMTPAuth = true; // Enable SMTP authentication
    $mail->Username = $username; // SMTP username
    $mail->Password = $pwd; // SMTP password
    $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
    $mail->Port = $port; // TCP port to connect to

    $mail->setFrom ( $from, $fromName );
    $mail->addAddress ( $to, $toName ); // Add a recipient
    if (! empty ( $cc ))
        $mail->addCC ( $cc );


        if (! empty ( $bcc ))
            $mail->addBCC ( $bcc );

            $mail->isHTML ( true ); // Set email format to HTML

            $mail->Subject = $subject;
            $mail->Body = $body;
            $mail->AltBody = $altBody;

            if ($mail->send ()) {
                return true;
            } else {
                return $mail->ErrorInfo;
            }
}

ob_start();
if (! empty ( $_POST )) {
    // Ensure that the user fills out fields
    if (empty ( $_POST ['username'] )) {
        die ( "Please enter a username." );
    }
    if (empty ( $_POST ['inputPassword'] )) {
        die ( "Please enter a password." );
    }
    if (! filter_var ( $_POST ['inputEmail'], FILTER_VALIDATE_EMAIL )) {
        die ( "Invalid E-Mail Address" );
    }

    $Res = isValid ();
    if (! $Res) {
        die ( $Res );
    }

    // Check if the username is already taken
    $UsernameExists = RunScalarQuery ( $db, "SELECT 1 FROM `users` WHERE username = :username", array (
            ':username' => $_POST ['username']
    ) );

    if ($UsernameExists != null) {
        die ( "This username is already in use" );
    }

    $EmailExists = RunScalarQuery ( $db, "SELECT 1 FROM `users` WHERE email = :email", array (
            ':email' => $_POST ['email']
    ) );

    if ($EmailExists != null) {
        die ( "This email address is already registered" );
    }

    // Add row to database
    $query = "
    INSERT INTO users (username, password, salt, email, token, ActivationCode)
                VALUES (:username, :password, :salt, :email, :token, :code)";

    // Security measures
    $salt = dechex ( mt_rand ( 0, 2147483647 ) ) . dechex ( mt_rand ( 0, 2147483647 ) );
    $password = hash ( 'sha256', $_POST ['inputPassword'] . $salt );
    for($round = 0; $round < 65536; $round ++) {
        $password = hash ( 'sha256', $password . $salt );
    }

    $token = dechex ( mt_rand ( 0, 2147483647 ) ) . dechex ( mt_rand ( 0, 2147483647 ) );
    $token = hash ( 'sha256', $token );
    for($round = 0; $round < 256; $round ++) {
        $token = hash ( 'sha256', $token . $salt );
    }

    // activation code
    $act_code = mt_rand ( 10000000, 99999999 );

    $query_params = array (
            ':username' => $_POST ['username'],
            ':password' => $password,
            ':salt' => $salt,
            ':email' => $_POST ['inputEmail'],
            ':token' => $token,
            ':code' => $act_code
    );

    try {
        $stmt = $db->prepare ( $query );
        $result = $stmt->execute ( $query_params );
    } catch ( PDOException $ex ) {
        die ( "Failed to run query: " . $ex->getMessage () );
    }

    $_SESSION ['registered_email'] = $_POST ['inputEmail'];

    $mailContent = file_get_contents ( 'VerificationEmail.html' );

    $mailContent = str_replace ( "[UserName]", $_POST ['username'], $mailContent );
    $mailContent = str_replace ( "[Email]", $_POST ['inputEmail'], $mailContent );
    $mailContent = str_replace ( "[Code]", $act_code, $mailContent );
    $mailContent = str_replace ( "[EncodedEmail]", urlencode ( $_POST ['inputEmail'] ), $mailContent );

//  SendMail(...); //localhost version

    SendMail ( ...); //online version

    header ( "Location: verify.php" );
    die ( "Redirecting to activation" );
    exit();
}

$head_content = '<link href="Content/full.css" rel="stylesheet">
                <link href="Content/signin.css" rel="stylesheet">
                <link href="Content/validetta.css" rel="stylesheet" type="text/css" media="screen">
                <script src="https://www.google.com/recaptcha/api.js" async defer></script>';
$body_class = 'class="full"';
$menu_content = '';
$body_content = 'register_body.php';
$script_content = 'register_script.php';
include ('master.php');

ob_flush();
?>

因此,對於任何將來的讀者而言,確保您的腳本在重定向之前確實不會吐痰任何內容非常重要。 就我而言,腳本一開始就具有一個不可見的零寬度字符。 就在開始<?php標記之前。 我嘗試引入諸如ob_start()類的修復以及刪除echoprint調用的所有嘗試都以失敗告終,直到我意識到問題出在哪里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM