php - 是否有使用 $stmt->close(); 的正确方法?
问题描述
我的网站上有很多声明,我想知道您何时以及如何$stmt->close();
正确使用。它会通过保持开放来打开漏洞吗?
在这个例子中,关闭语句的正确位置是第 23 行吗?
// First, check if the email and code exists
if (isset($_GET['email'], $_GET['code'])) {
if ($stmt = $con->prepare('SELECT * FROM accounts WHERE email = ? AND activation_code = ?')) {
$stmt->bind_param('ss', $_GET['email'], $_GET['code']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// Account exists with the requested email and code
if ($stmt = $con->prepare('UPDATE accounts SET activation_code = ? WHERE email = ? AND activation_code = ?')) {
// Set the new activation code to 'activated', this is how we can check if the user has activated their account
$newcode = 'activated';
$stmt->bind_param('sss', $newcode, $_GET['email'], $_GET['code']);
$stmt->execute();
header('Location: messages.php?message=activated');
exit;
}
} else {
header('Location: messages.php?message=activated-error');
exit;
}
}
}
这里有两个语句,我要关闭它们吗?或者我只是在底部关闭它们?另外,正如我使用header('Location:')
的那样,$stmt->close();
实际执行了吗?
解决方案
你根本不需要使用$stmt->close();
。您几乎不需要在 PHP 中手动关闭任何内容。一旦不再需要,PHP 会为您关闭它。如果您正确地构建代码,PHP 会在最佳状态时为您关闭所有内容。
使用header('Location:')
不会影响 mysqli 对象。当您exit
编写代码时,整个脚本将停止,如果尚未关闭,PHP 将关闭所有内容。
你真的应该使用一些封装。不要直接使用 mysqli 方法。创建一些将从这个接口抽象出来的函数或类,这样你就更容易使用它了。如果你做得正确,那么你根本不需要担心关闭对象。
推荐阅读
- oracle - 如何在 Docker 中连接到外部 Oracle 数据库
- php - 如何在 Symfony Messenger 的中间件上禁用日志“信息”?
- algorithm - 如何使用机器学习计算文本中的单词
- javascript - 如何通过特定对象键对数组中的值求和?
- python - 使用 PyTorch LSTM,我的 hidden_size 可以与 input_size 不同吗?
- rest-assured - 放心。是否可以将所有测试的主体记录在 ResponseSpecification 中?
- django - Django 项目架构建议
- python - Pytorch:合并两个模型(nn.Module)
- arrays - 使用设计将数组列添加到数据库
- linux - Perf 中的奇怪回溯