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

129 Views Asked by At

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.

3

There are 3 best solutions below

1
radsectors On BEST ANSWER

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.

0
Otávio Barreto On

This will solve

$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);

so in your file concatenate the variables

echo $path.'.'.$ext;
1
A l w a y s S u n n y On

This should work for you if you use name instead of tmp_name

$path_parts = pathinfo($_FILES["TaxFile"]['name']);
$extension = $path_parts['extension'];
echo $extension;