3

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["Artwork"]["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!

1
  • 1
    Don't use the ['type'] field. That's user-provided data and is trivial to forge. use something server-side, such as FileInfo, to get a mime-type. Still not 100%, but much better than the 0% reliability of the ['type'] field. Commented Aug 23, 2011 at 14:31

3 Answers 3

8

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";
    }
Sign up to request clarification or add additional context in comments.

Comments

1
$ext = last(explode('.', $_FILES['Artwork']['name']));
$custom_name = 'something';
$imageName = $custom_name.'.'.$ext;

Comments

0

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) : '')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.