PHP登录报错:Array to string conversion问题求助(附代码)
Hey there! I know spending two days troubleshooting this must be frustrating—let's get this sorted out for you right away.
问题根源
The "Array to string conversion" error pops up because in welcome.php, you're trying to echo $_SESSION['user'] directly, but this variable is an array (you stored $fullname as an array with firstname and lastname in Login.php). PHP can't automatically convert an array to a string, hence the notice.
快速修复方案
You have two simple ways to fix this:
方案1:修改welcome.php,输出数组里的具体字段
Instead of echoing the entire array, access the firstname and lastname keys separately. I also added a check to avoid errors if the user isn't logged in:
<?php session_start(); // 注意:必须放在任何输出之前,包括被include的文件 include('includes/head.php'); include('includes/nav2.php'); if(isset($_SESSION['user'])) { echo 'Welcome ' . $_SESSION['user']['firstname'] . ' ' . $_SESSION['user']['lastname']; } else { echo 'Please log in first.'; } echo '<br><br>'; ?>
方案2:在Login.php中直接存储字符串而不是数组
If you don't need firstname and lastname as separate values later, combine them into a string before storing in the session:
// 替换Login.php里的这两行 $fullname = $row['firstname'] . ' ' . $row['lastname']; $_SESSION['user'] = $fullname;
Then your original echo 'Welcome '. $_SESSION['user']; in welcome.php will work perfectly.
额外的代码优化建议
While we're fixing things, let's tidy up a few other details to make your code more robust and secure:
- Session位置问题:In
Login.php,session_start()should be at the very top of the file—before any includes or HTML output. Otherwise, you might hit "headers already sent" errors when redirecting. Update it like this:
<?php session_start(); // 移到最顶部 require_once('connect.php'); include('includes/head.php'); // ... rest of your code ?>
- 数组键名规范:Your array definition in
Login.phpuses unquoted keys (firstname=>...). PHP will let this slide for now, but it's bad practice (it treats unquoted keys as constants). Always quote your array keys:
$fullname = array('firstname' => $row['firstname'], 'lastname' => $row['lastname']);
- 密码安全问题:Storing plain-text passwords in your database is extremely risky. Use PHP's built-in
password_hash()when creating user accounts, andpassword_verify()during login. Here's how to update your login logic:
// 当创建用户时,存储哈希后的密码 $hashed_password = password_hash($user_password, PASSWORD_DEFAULT); // 插入数据库时用$hashed_password代替明文密码 // 登录时验证密码 $query = "SELECT * FROM user where username='$username'"; $result = mysqli_query($connection, $query); $row = mysqli_fetch_array($result); if(mysqli_num_rows($result) == 1 && password_verify($password, $row['password'])) { // 验证成功,创建session }
总结
The core fix is either accessing the array elements individually in welcome.php or storing a string in the session instead of an array. The extra tips will help avoid future bugs and keep your user data safe.
内容的提问来源于stack exchange,提问作者SilentChef187

