Reputation:
I'm currently wanting to use the w3schools image uploading code until I can find the one I coded a while back. Anyway:
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_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 "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
Basically what I want to happen is when the user uploads the file it renames the file name to $username and not the original name so all it would be is username.png instead of what I currently have username-38474.png
Any help?
Upvotes: 1
Views: 14663
Reputation: 23787
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
This line of code basically renames the image to a new location: to "upload/".$_FILES["file"]["name"]
, so replace this line by:
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$username.".".$extension);
Upvotes: 8
Reputation: 53338
So just pass different parameter to move_uploaded_file
:
$extension = explode("/", $_FILES["file"]["type"]); //Use proper mime type here, $_FILES contents can be faked by remote user
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $username.".".$extension[1]);
Upvotes: 0