PHP upload files and give a custom name
I am using this function to upload my files:
if ((($_FILES["Artwork"]["type"] == "image/gif")
|| ($_FILES["Artwork"]["type"] == "image/jpeg")
|| ($_FILES["Artwork"]["type"] == "image/jpg")
|| ($_FILES["Artwork"]["type"] == "image/pjpeg"))
&& ($_FILES["Artwork"]["size"] < 20000000))
{
if ($_FILES["Ar开发者_StackOverflowtwork"]["error"] > 0)
{
//echo "Return Code: " . $_FILES["Artwork"]["error"] . "<br />";
}else{
$imageName = $_FILES['Artwork']['name'];
move_uploaded_file($_FILES["Artwork"]["tmp_name"],
$path_image . $imageName);
}
}else{
//echo "invalid file";
}
How do I change $imageName = $_FILES['Artwork']['name'];
with a custom name, but mantaining the file extension in the name, so for example: myCustomName.jpg
?
Thanks!
The only line you need modified in your code is:
$imageName = 'CustomName.' . pathinfo($_FILES['Artwork']['name'],PATHINFO_EXTENSION);
Where 'CustomName.' is the new name you want for the image. pathinfo if the PHP function to handle the operations with paths and files names.
You whole code would be:
if ((($_FILES["Artwork"]["type"] == "image/gif")
|| ($_FILES["Artwork"]["type"] == "image/jpeg")
|| ($_FILES["Artwork"]["type"] == "image/jpg")
|| ($_FILES["Artwork"]["type"] == "image/pjpeg"))
&& ($_FILES["Artwork"]["size"] < 20000000))
{
if ($_FILES["Artwork"]["error"] > 0)
{
//echo "Return Code: " . $_FILES["Artwork"]["error"] . "<br />";
}else{
$imageName = 'CustomName.' . pathinfo($_FILES['Artwork']['name'],PATHINFO_EXTENSION);
move_uploaded_file($_FILES["Artwork"]["tmp_name"],
$path_image . $imageName);
}
}else{
//echo "invalid file";
}
$ext = last(explode('.', $_FILES['Artwork']['name']));
$custom_name = 'something';
$imageName = $custom_name.'.'.$ext;
I think you're making it too complicated. It's as simple as splitting the filename by the dot and using the last element:
$parts = explode('.', $_FILES['Artwork']['name']);
$newname = "myCustomName" . (size($parts) > 1 ? '.' . last($parts) : '')
精彩评论