如何从 PHP 登录项目中获取用户名

How to grab username from the PHP Login Project

好的,所以需要做一些解释。所以,让我们从我在这里想要实现的目标开始。我正在尝试为用户创建一个头像功能来上传图像以用于他们的个人资料。这是我的概念;

User Uploads image to directory = Image is renamed according to their username =

When a user visits his profile the image is called by grabbing his username =

So essentially, the image output will look like this <img src="avatars/$username.png" />

现在,由于我对 PHP 没有太多经验,我决定使用名为“The PHP Login-Project”的预建 PHP 登录脚本.它使事情变得更快。

但我的问题是,我不知道如何访问用户名信息以在我的上传图片 php 文件中使用(此文件名为 upload.php。)因此,目前,upload.php 允许用户上传图片,然后用一串随机数字重命名,我不希望这样。相反,代替数字的是用户的用户名。这是 upload.php 文件;

<?php
$rand = rand(10000000, 999999999);
$file_name = $rand.$_FILES["fileToUpload"]["name"];
$target_dir = "avatars/";
$target_file = $target_dir . $file_name;
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        //echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        //echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        header('Location: http://1.testing.uk.to/PROJECT_SPACE/edit.php');
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

这里是 PHP 登录项目的 GitHub 页面:GitHub Link

现在,如果您没有 used/seen PHP 登录项目,这个问题可能不太容易理解。所以如果你已经看过它并且知道它是如何工作的,这就是我要问的问题,我如何获取用户的用户名并将其添加到我的 upload.php 文件中,重命名上传的文件以匹配用户名?有经验的 PHP 开发人员也可能理解这个问题,但建议查看 PHP Login-Project 的代码。希望我已经以一种可以帮助我解决问题的方式解释了我想要的东西。感谢您提供的任何帮助。

查看文件,登录函数将用户名存储在会话中。所以你可以在上面的文件中调用这个会话并用它来分配给变量“$filename”。

尝试在Login.php第738行

使用这个函数
<code>
    public function getUsername()
    {
        return $this->user_name;
    }
</code>