Search code examples
phpformsfilepathinfo

How do I correctly display a file extension from an HTML POST file using PHP?


I am attempting to echo the extension of an uploaded tax document. The document can be any image or a pdf. I plan on using the extension to rename the file with its proper extension later in the code.

Currently it does not echo the extension.

I have attempted a few different methods and looked at documentation and forums. I seem to still be doing something wrong.

My HTML:

<input type="file" class="" id="TaxFile" name="TaxFile" accept="image/*,application/pdf" ><br /><br />

My PHP:

$taxpath = pathinfo($_FILES["TaxFile"]["tmp_name"]); echo $taxpath['extension'] . "\n123";

echos '123'

My Alternative PHP:

$taxpath = $_FILES["TaxFile"]["tmp_name"]; $ext = pathinfo($taxpath, PATHINFO_EXTENSION); echo $ext;

echos nothing

I expected to see the echo: "pdf 123" and "pdf"

*My later code does in fact save the file to its destination using move_uploaded_file($_FILES["TaxFile"]["tmp_name"], $target_file). It's just that $target_file wont include the proper extension.


Solution

  • tmp_name is the temporary name/location of the file on disk.

    Try using $_FILES["TaxFile"]["name"] to get the original filename.

    Otherwise, your method for grabbing the extension with pathinfo() and PATHINFO_EXTENSION was correct.