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


How to grab username from the PHP Login Project

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

用户将图像上传到目录=根据用户名重命名图像=

当用户访问他的个人资料时,通过抓取他的用户名=来调用图像

因此,本质上,图像输出将看起来像这个<img src="avatars/$username.png" />

现在,由于我对PHP没有太多的经验,我决定使用一个名为"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链接。

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

尝试在Login.php第738行中使用此函数

<code>
    public function getUsername()
    {
        return $this->user_name;
    }
</code>

查看这些文件,登录函数将用户名存储在会话中。因此,您可以在上面的文件中调用这个会话,并使用它来分配给变量"$filename"。