今天我在我的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