upload only txt files

20,636

Solution 1

You can test the filetype:

if ($_FILES['file']['type'] == 'text/plain') // this file is TXT

Also, you can verify the mime-type of a file using the function mime_content_type.

Solution 2

if(preg_match('\.txt$', $filename))

This will return true if the file ends with .txt

Solution 3

If you want to check the actual file MIME type, try PHP's finfo_file function. (See example #1 on that page. If the string returned isn't "text/html," then it's not a text file.)

Edit: Bear in mind that the mime_content_type function has been depreciated. Use finfo_file instead.

Share:
20,636
Alexander Girndt
Author by

Alexander Girndt

Updated on July 05, 2022

Comments

  • Alexander Girndt
    Alexander Girndt almost 2 years

    how do check so ONLY .txt files are uploaded to the server and not other files in php.

  • sdot257
    sdot257 over 13 years
    but it could be a JPG file w/ a diff extension.
  • CrociDB
    CrociDB over 13 years
    After the upload, use the mime_content_type function I posted.
  • J V
    J V over 13 years
    Any other method requires trusting the user or uploading the whole file first to find out. Besides, most browsers will just open it as a text file despite mime type
  • ajreal
    ajreal over 13 years
    @Alexander Girndt - @Jake is right, please don't assume *.txt is same as plain text file
  • Powerlord
    Powerlord over 13 years
    finfo_file is only standard in PHP 5.3 and newer. Prior to this, you needed a PECL extension for it.
  • www139
    www139 almost 9 years
    Isn't it more secure to match the file type using preg_match instead of mime-type?
  • The_Puzzler
    The_Puzzler about 4 years
    @www139 I'd say no because preg_match will be looking at the text which is there, and the extentions like .gif can easily be faked or have the file saved like that, which would mess up the result provided by preg_match. Checking mime types isn't a perfect solution but the extensions alone is a bad check