今天我在我的web服務中創建了一個函數,用於從mysql表中刪除用戶。 我使用SLIM框架來構建我的RESTful API。PHP:如何在不刪除「身份驗證」功能的情況下刪除用戶
這是我班的用戶功能:
public function deleteUser($user_id)
{
$stmt = $this->conn->prepare("DELETE
FROM users
WHERE user_id = ?");
if($stmt == FALSE)
{
die($this->conn->error);
}
else
{
$stmt->bind_param("i", $user_id);
$stmt->execute();
$num_affected_rows = $stmt->affected_rows;
$stmt->close();
return $num_affected_rows > 0;
}
}
,這是我的index.php中的代碼
$app->delete('/users/:user_id', 'authenticate', function() use($app)
{
global $user_id;
$db = new User();
$response = array();
$result = $db->deleteUser($user_id);
if ($result)
{
// user deleted successfully
$response["error"] = false;
$response["message"] = "User deleted succesfully";
}
else
{
// user failed to delete
$response["error"] = true;
$response["message"] = "User failed to delete. Please try again!";
}
echoRespnse(200, $response);
});
的問題是我的身份驗證功能得到用戶表的USER_ID置於標題授權中。
function authenticate(\Slim\Route $route)
{
// Getting request headers
$headers = apache_request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
// Verifying Authorization Header
if (isset($headers['Authorization']))
{
$db = new User();
// get the api key
$api_key = $headers['Authorization'];
// validating api key
if (!$db->isValidApiKey($api_key))
{
// api key is not present in users table
$response["error"] = true;
$response["message"] = "Access Denied. Invalid Api key";
echoRespnse(401, $response);
$app->stop();
}
else
{
global $user_id;
// get user primary key id
$user_id = $db->getUserId($api_key);
}
}
else
{
// api key is missing in header
$response["error"] = true;
$response["message"] = "Api key is misssing";
echoRespnse(400, $response);
$app->stop();
}
}
所以每次我試圖刪除與「USER_ID」的用戶,它總是出錯,因爲系統會刪除用戶依賴於它在頭部授權submited API密鑰。
我的目標是:刪除功能將刪除與用戶ID的用戶。
有誰知道如何解決它?
謝謝:)
非常感謝!有用 ! – 2014-11-04 16:52:19
我會添加到這個答案,你真的應該擺脫習慣使用'全局'聲明贊成依賴注入。這將幫助您避免範圍問題,如完全這樣。 – 2014-11-04 16:53:51
是的,我同意你@MikeBrant:D – 2014-11-04 18:22:02