【问题标题】:Allow the users to upload profile images in PHP允许用户在 PHP 中上传个人资料图片
【发布时间】:2017-12-06 09:29:41
【问题描述】:

我已经有一个合适的图片上传系统。它将图片上传并存储在文件夹/uploads/ 中,现在我需要跟踪上传个人资料图片的人员,并且我想在我的用户个人资料页面上显示该图片。

这是我的upload.php:

<?php
include('db.php');

// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
  $_SESSION['message'] = "You must log in before viewing your profile page!";
  header("location: error.php");    
}

if (isset($_POST['submit'])) {
    $file = $_FILES['file'];

    $fileName = $file['name'];
    $fileTmpName = $file['tmp_name'];
    $fileSize = $file['size'];
    $fileError = $file['error'];
    $fileType = $file['type'];

    $fileExt = explode('.', $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array('jpg', 'jpeg', 'png', 'pdf');

    if (in_array($fileActualExt, $allowed)) {
        if ($fileError === 0) {
            if ($fileSize < 1000000) {
                $fileNameNew = uniqid('', true).".".$fileActualExt;
                $fileDestination = 'uploads/'.$fileNameNew;
                move_uploaded_file($fileTmpName, $fileDestination);
                header("Location: user.php");
            } else {
                echo "Your file is too big!";
            }
        } else {
            echo "There was an error uploading your file!";
        }
    } else {
        echo "You cannot upload files of this type!";
    }
}

这是HTML

<form action="upload.php" method="POST" enctype="multipart/form-data" >
<div class="specialcontainer">
    <input type="file" name="file" id="file" class="inputfile">
</div>
  <div class="inner"></div>
    <button type="submit" name="submit" class="uploadbuttonstyle">Upload</button>
</form>
</div>

为此,我有 2 个表,一个处理用户名、fname、lname、电子邮件、密码、用户描述等。我希望第二个显示他们的个人资料图像的状态,即如果他们上传了图像, status 将为 1,如果没有,则 status 为 0。如果 status 为 0,则将显示来自目录 /uploads/profiledefault.jpg 的图像,这是新用户的默认配置文件图像。当谈到 PHP 时,我仍然是初学者。希望有人能告诉我这里的路。

【问题讨论】:

    标签: php mysql image file-upload


    【解决方案1】:

    您不需要为此使用另一个表。只需在您的第一个表中再添加一列“profile_image”并将图像保存在该表中

     if (move_uploaded_file($fileTmpName, $fileDestination)) {
     // save/update "profile_image" field here.
    }
    

    当您想显示个人资料图片时,只需检查 profile_image 列是否为空白。如果是则显示默认图像“/uploads/profiledefault.jpg”,否则显示“profile_image”列中的个人资料图像。

    【讨论】:

    • 我猜我将不得不使用 UPDATE 查询来更新 profile_image 列,并且 WHERE 子句将包含每个用户的唯一值,例如他/她的电子邮件?
    【解决方案2】:

    我相信您有名为 User 的实体。在此实体中添加属性profileImage 并在上传后保存图像的路径。您获取当前用户并将文件路径添加到他的属性profileImage。每次注册新用户时,您只需向profileImage 提供默认图像/uploads/profiledefault.jpg 的路径。这意味着在每一点用户都会有 profileImage 并且不需要检查它。

    【讨论】:

      猜你喜欢
      • 2011-05-20
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 2020-11-02
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多