HTML отображается как текст - PullRequest
0 голосов
/ 27 апреля 2020

У меня есть файл . php, содержащий код html. У меня проблема в том, что он отображается как текст, а не как элементы html. Я нашел несколько других вопросов, касающихся этой проблемы:

Почему это HTML отображается в виде обычного текста в браузере?

Браузер показывает простой текст вместо HTML в ма c

Страница показывает код, не отображающий

Однако я считаю, что все, что там предлагалось людьми, относится к моему коду .

Мой код:

<?php
// required headers
header("Access-Control-Allow-Origin: null");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// files needed to connect to database
include_once '../config/database.php';

// get database connection
$database = new Database();
$conn = $database->getConnection();

$error = "";
if (isset($_GET["key"]) && isset($_GET["email"]) && isset($_GET["action"]) && ($_GET["action"]=="reset") && !isset($_POST["action"])) {
    $key = $_GET["key"];
    $email = $_GET["email"];
    $curDate = date("Y-m-d H:i:s");

    $query = "SELECT * FROM password_reset_temp WHERE email=:email AND `key`=:key";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(":key", $key);
    $stmt->bindParam(":email", $email);
    try {
        $stmt->execute();
    } catch (PDOException $e) {
        echo json_encode(array("message" => $e->getMessage()));
    }
    if ($stmt->rowCount() == 0) {
        $error .= '<h2>Invalid Link</h2>
        <p>The link is invalid/expired. Either you did not copy the correct link
        from the email, or you have already used the key in which case it is 
        deactivated.</p>
        <p><a href="...">
        Click here</a> to reset password.</p>';
    } else {
        $row = $stmt->fetch();
        $expDate = $row['expDate'];
        if ($expDate >= $curDate){
// the part that is not showing begins here                
?>
            <br />
            <form method="post" action="" name="update">
            <input type="hidden" name="action" value="update" />
            <br /><br />
            <label><strong>Enter New Password:</strong></label><br />
            <input type="password" name="pass1" maxlength="15" required />
            <br /><br />
            <label><strong>Re-Enter New Password:</strong></label><br />
            <input type="password" name="pass2" maxlength="15" required/>
            <br /><br />
            <input type="hidden" name="email" value="<?php echo $email;?>"/>
            <input type="submit" value="Reset Password" />
            </form>
            <?php
        } else {
            $error .= "<h2>Link Expired</h2>
            <p>The link is expired. You are trying to use the expired link which 
            as valid only 24 hours (1 days after request).<br /><br /></p>";
        }
    }
    if($error!=""){
        echo "<div class='error'>".$error."</div><br />";
    } 
} // isset email key validate end


if(isset($_POST["email"]) && isset($_POST["action"]) &&
 ($_POST["action"]=="update")){
$error="";
$pass1 = mysqli_real_escape_string($con,$_POST["pass1"]);
$pass2 = mysqli_real_escape_string($con,$_POST["pass2"]);
$email = $_POST["email"];
$curDate = date("Y-m-d H:i:s");
if ($pass1!=$pass2){
$error.= "<p>Password do not match, both password should be same.<br /><br /></p>";
  }
  if($error!=""){
echo "<div class='error'>".$error."</div><br />";
}else{
$pass1 = md5($pass1);
mysqli_query($con,
"UPDATE `users` SET `password`='".$pass1."', `trn_date`='".$curDate."' 
WHERE `email`='".$email."';"
);

mysqli_query($con,"DELETE FROM `password_reset_temp` WHERE `email`='".$email."';");

echo '<div class="error"><p>Congratulations! Your password has been updated successfully.</p>
<p><a href="...">
Click here</a> to Login.</p></div><br />';
   } 
}
?>

Мой .htaccess выглядит так

# Turn on the rewrite engine
RewriteEngine  on
# If the request doesn't end in .php (Case insensitive) continue processing rules
RewriteCond %{REQUEST_URI} !\.php$ [NC]
# If the request doesn't end in a slash continue processing the rules
RewriteCond %{REQUEST_URI} [^/]$
# Rewrite the request with a .php extension. L means this is the 'Last' rule
RewriteRule ^(.*)$ $1.php [L]

Вывод:

<br />
            <form method="post" action="" name="update">
            <input type="hidden" name="action" value="update" />
            <br /><br />
            <label><strong>Enter New Password:</strong></label><br />
            <input type="password" name="pass1" maxlength="15" required />
            <br /><br />
            <label><strong>Re-Enter New Password:</strong></label><br />
            <input type="password" name="pass2" maxlength="15" required/>
            <br /><br />
            <input type="hidden" name="email" value="..."/>
            <input type="submit" value="Reset Password" />
            </form>

Все остальные . php файлы в этом каталоге работают отлично. Если вам нужна какая-либо другая информация, дайте мне знать.

1 Ответ

3 голосов
/ 27 апреля 2020
header("Content-Type: application/json; charset=UTF-8");

Вы сказали, что это JSON, а не HTML.

Браузер пытается обработать его как JSON, терпя неудачу и показывая его как текст вместо этого.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...