user2055774
user2055774

Reputation: 1

Need Help Having PHP File Upload To Upload File Under The User's Username

I have a program that requires each user to upload their own image. That image must be, (their username).png. For example: testuser123.png. The PHP script that automatically enter's the user's username is

<?=$_SESSION['Username']?>

Basically, I need the file to be saved as

<?=$_SESSION['Username']?>.png

How would I do this with this certain script though? Any help would be greatly appreciated! The problem I have is I don't know where to put that part of the code, and I'm not sure if it would even work. I know my code has to be edited a bit, but I don't know how.

<?php
$allowedExts = array("png");
$extension = end(explode(".", $_FILES["file"]["name"]));
|| ($_FILES["file"]["type"] == "image/png")
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
  }
else
  {
  echo "Invalid file";
  }
?> 

Upvotes: 0

Views: 92

Answers (1)

Drew
Drew

Reputation: 472

When you upload a file through a form, it's uploaded to the server's temp directory. You need to move it to a proper directory in your website or it will be removed when the server does garbage collection. To do this, you'll need to use move_uploaded_file(). Here's what you would need, given your script as it is:

<?php
$allowedExts = array("png");
$extension = end(explode(".", $_FILES["file"]["name"]));
|| ($_FILES["file"]["type"] == "image/png")
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];

    $path = "/path/to/directory";
    move_uploaded_file($_FILES["file"]["tmp_name"], $path."/".$_SESSION['Username'].".png");

    }
  }
else
  {
  echo "Invalid file";
  }
?>

Upvotes: 2

Related Questions