Have you noticed that we can rename the file extension from many kinds of image files to others, and Windows still can show these images ?
Actually, when you rename, for instance, the image "YourPicture.Bmp" to "YourPicture.Jpg", the whole file remains intact, just the file extension was changed. When Windows opens that picture, it finds at the image header in the beginning of the file the information, a specific signature that tells the real type of image it is dealing with.
Tore Bleken, from Norway, created this simple but very useful function that searches for some specific information in the file header. He simply used a hex editor, and checked several files. Many thanks to Tore for the code and for allowing to publish it here!
FUNCTION filetype
LPARAMETERS lcData
LOCAL lcReturn,lcContents
IF PCOUNT()=0 OR VARTYPE(lcData)#'C'
lcReturn=''
ELSE
IF ADIR(laDummy,lcData)>0 && File
lcContents=FILETOSTR(lcData)
ELSE && Memory variable
lcContents=lcData
ENDIF
DO CASE
CASE LEN(lcContents)<4
lcReturn=''
CASE LEFT(lcContents,3)=CHR(0xFF)+CHR(0xD8)+CHR(0xFF)
lcReturn='JPG'
CASE LEFT(lcContents,3)='GIF'
lcReturn='GIF'
CASE SUBSTR(lcContents,42,3)='EMF'
lcReturn='EMF'
CASE LEFT(lcContents,4)=CHR(0xD7)+CHR(0xCD)+CHR(0xC6)+CHR(0x9A)
lcReturn='WMF'
CASE LEFT(lcContents,4)=CHR(0x4D)+CHR(0x4D)+CHR(0x00)+CHR(0x2A)
lcReturn='TIF'
CASE LEFT(lcContents,4)=CHR(0x89)+'PNG'
lcReturn='PNG'
CASE LEFT(lcContents,2)='BM'
lcReturn='BMP'
CASE LEFT(lcContents,3)='CWS' AND ASC(SUBSTR(lcContents,4,1))<16
lcReturn='SWF'
CASE LEFT(lcContents,3)='FWS' AND ASC(SUBSTR(lcContents,4,1))<16
lcReturn='SWF'
OTHERWISE
lcReturn=''
ENDCASE
ENDIF
RETURN lcReturn