You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过PHP获取Local Storage数据并存入MySQL?

关于PHP获取浏览器Local Storage数据并存入MySQL的解决方案

核心结论

PHP作为服务器端语言,无法直接读取浏览器的Local Storage数据——Local Storage是浏览器端的本地存储,仅能通过前端JavaScript访问。要将其存入MySQL,必须通过前端把数据传递到后端PHP。

实现流程

  • 用JavaScript读取Local Storage中的目标数据
  • 通过表单提交或AJAX请求将数据发送至PHP接口
  • PHP接收数据后完成验证、处理,再写入MySQL数据库

你的PHP代码问题修正

你的代码存在几处关键错误,导致无法正常运行:

  1. PHP超全局变量大小写敏感:$_post应改为$_POST
  2. 变量与表单字段不匹配:判断条件里的$_POST['username']和后续赋值的$_POST['nom']不一致;$_POST['pwr']未赋值给$mdp
  3. 加密逻辑错误:错误地对email做哈希处理,实际应加密密码字段
  4. 空值判断冗余:!empty(isset($_POST['xxx']))可简化为!empty($_POST['xxx'])

修正后的代码示例:

<?php
if (isset($_POST['cree'])) {
    require('/config/connexion.php');
    // 修正空值判断与字段匹配
    if (!empty($_POST['email']) && !empty($_POST['pwr']) && !empty($_POST['number']) && !empty($_POST['nom'])) {
        $email = htmlspecialchars($_POST['email']);
        $tel = htmlspecialchars($_POST['number']);
        $nom = htmlspecialchars($_POST['nom']);
        // 修正:对密码进行哈希,而非邮箱
        $mdp = password_hash($_POST['pwr'], PASSWORD_DEFAULT);
        
        $test = $bdd->prepare("SELECT * FROM user WHERE email=?");
        $test->execute(array($email));
        if ($test->rowCount() == 0) {
            $req = $bdd->prepare('INSERT INTO user(email,mdp,nom,tel) VALUES(?,?,?,?) ');
            $req->execute(array($email,$mdp,$nom,$tel));
            $req->closeCursor();
            $success = "You have been successfully registered";
        } else {
            $msg = "A user with email " . $email . " already exists on this platform";
        }
    } else {
        $msg = "Please fill in all fields";
    }
}
?>

前端传递Local Storage数据示例(JS+表单)

如果要把Local Storage里的user_token字段传递给PHP,可通过隐藏表单字段实现:

<form method="POST" action="你的PHP文件路径">
    <!-- 其他原有表单字段 -->
    <input type="hidden" id="localStorageData" name="local_storage_data">
    <button type="submit" name="cree">提交</button>
</form>

<script>
// 读取Local Storage数据并赋值给隐藏字段
document.getElementById('localStorageData').value = localStorage.getItem('user_token') || '';
</script>

之后在PHP中可通过$_POST['local_storage_data']获取该值,按需存入数据库即可。

内容的提问来源于stack exchange,提问作者Warano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 15:43:35