0
我對PHP相當陌生,但我有一個「API」設置在我的Web服務器上以發送/接收數據到MySQL數據庫。
由於某種原因,當我向我的register.php文件(註冊入口點)發送http post請求時,$_POST
變量保持爲空。但是,在使用phpconfig()
並做了一些挖掘之後,我注意到我發送的參數存儲在$_REQUEST
變量中,所以我相應地更改了我的register.php並且它工作正常。
我的問題是爲什麼發生這種情況,以及是否使用$_REQUEST
是錯誤的。
我用angularjs' $ HTTP發送HTTP請求:
var link = 'http://www.temporaryurl.com/register.php'
$http.post(link, {'name': 'Adam'},{'email': '[email protected]'},{'password': 'testingPass!'}).then(function(response) {
console.log("Http success!");
console.log(response);
}, function(response) {
console.log("Http failure");
console.log(response);
});
這裏的register.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_REQUEST['name']) && isset($_REQUEST['email']) && isset($_REQUEST['password'])) {
// receiving the post params
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
// check if user is already existed with the same email
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = TRUE;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($name, $email, $password);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
echo("$email is not a valid email address");
$response["error"] = TRUE;
$response["error_msg"] = "Email is invalid!";
echo json_encode($response);
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters (name, email or password) is missing!";
echo json_encode($response);
}
?>
有一刻,我會更新我的帖子。 – awbasham
參考這篇文章http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined並嘗試。 – Perumal
'if(x === false)'是一個需要消除的反模式,只要使用'if(!x)'和'if(!x === false)'更加荒謬。這讀作爲三重否定:「如果不是字面上不假」。儘量避免像這樣毫無意義的雜技。同樣,我敢打賭,你的電子郵件「驗證」表達式會拒絕許多絕對有效的地址,因爲像'x @ google'這樣的技術在技術上是有效的,儘管看起來可能有多荒謬。 – tadman