[英]PHP: How to grab a variable from _POST in an other php file (using slim)
ERS
我正在嘗試學習如何使用苗條的框架為網站創建注冊和身份驗證。 我的目標是創建一個POST處理程序,並在正確驗證身份后,將保存網站以及用戶名和名稱。 這樣,下次用戶訪問該頁面時,網站就會通過說出他們的名字來問候他們。 我將通過兩個單獨的PHP文件進行此操作,但是我認為問題出在此PHP文件中。
這是我目前擁有的:
$app->post('/users', function (Request $request, Response $response, array $args) {
$user = array('username'=> $_POST['username'], 'password' => $_POST['password'], 'name' => $_POST['name']);
$res = saveUser($user);
if($result === true) { return $response->withRedirect('login.html', 302); }
return $response->withRedirect('registration.html#',$result,302); });
$app->post('/auth', function (Request $request, Response $response, array $args) {
if(isset($_POST['username']) {
return $response->withRedirect('welcome.php', 302);
}
if(authUser($_POST['username'], $_POST['password']) === true) {
$_SESSION["username"] = $_POST['username'];
$_SESSION["name"] = $_POST['name'];
return $response->withRedirect('welcome.php', 302);
}
else { //authentication doesn't work, destroy session and go to login page
session_destroy();
return $response->withRedirect('login.html',302);
}
據我了解,用戶名,密碼和用戶的真實姓名應保存在_POST中。 但是,當我使用:
var_dump($_POST);
密碼和用戶名是被調用時唯一顯示的內容。 這使我相信這就是為什么我的“ welcome.php”不歡迎用戶的原因。
這是我的welcome.php的內容:
<?php session_start(); ?>
!DOCTYPE html
<title> Welcome! </title>
<h1> Welcome Page </h1>
<section>
<p>
<?php
if(isset($_SESSION['name'])) { echo "Grettings " . $_SESSION['name']. "! ";}
?> Click <a href="login.html">here to login</a> OR <a href="registration.html"> here for registration</a>.
</p>
</section>
我認為我的錯誤一定是我嘗試如何調用它或在isset函數中,但是同樣,我也不知道為什么名稱沒有正確保存。
通常認為以這種方式訪問全局變量是錯誤的形式。 當您運行苗條時,它們已經有一個請求對象供您使用,因為您已經傳遞了:
$myArgs = $request->getQueryParams();
foreach($myArgs as $key => $value){
echo $key . '=>' . $value . PHP_EOL;
}
就是說,您的問題的原因是:
$response->withRedirect(..)
這會將返回到瀏覽器的http 302重定向到瀏覽器。 這是第二擊。 第一個匹配項是對/ auth的POST,第二個匹配項是對/welcome.php的GET請求
讓我大吃一驚的是您在/ auth上的邏輯路徑。 如果在$ _POST中設置了“用戶名”,則首先要將它們發送給welcome.php,其他代碼(如對authUser(..)函數的調用)將永遠不會執行。 由於您從未將$ _SESSION ['username']設置為任何值,因此它仍然為空。
我要說的最后一件事只是風格點; 我個人嘗試盡可能在字符串上使用單引號(')並避免使用雙引號(“),因為雙引號告訴PHP字符串中可能包含特殊標記,可能需要對其進行解析。如果您不解析標記,則只需使用單引號。除此之外,歡迎使用PHP,很高興看到您的作品!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.