php image type file

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

exif_imagetype — Определение типа изображения

Описание

exif_imagetype() считывает начальные байты изображения и проверяет их сигнатуру.

Список параметров

filename Изображение, тип которого требуется определить.

Возвращаемые значения

Список изменений

ВерсияОписание
5.3.0Добавлена поддержка иконок.

Предопределенные константы

Следующие определенные константы представляют возможные возвращаемые значения функции exif_imagetype() :

Imagetype константы

ЗначениеКонстанта
1 IMAGETYPE_GIF
2 IMAGETYPE_JPEG
3 IMAGETYPE_PNG
4 IMAGETYPE_SWF
5 IMAGETYPE_PSD
6 IMAGETYPE_BMP
7 IMAGETYPE_TIFF_II (порядок байт intel)
8 IMAGETYPE_TIFF_MM (порядок байт motorola)
9 IMAGETYPE_JPC
10 IMAGETYPE_JP2
11 IMAGETYPE_JPX
12 IMAGETYPE_JB2
13 IMAGETYPE_SWC
14 IMAGETYPE_IFF
15 IMAGETYPE_WBMP
16 IMAGETYPE_XBM
17 IMAGETYPE_ICO

Примеры

Пример #1 Пример использования exif_imagetype()

Смотрите также

Источник

image_type_to_mime_type

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

image_type_to_mime_type — Получение Mime-типа для типа изображения, возвращаемого функциями getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

Описание

Функция image_type_to_mime_type() определяет Mime-тип для константы IMAGETYPE.

Список параметров

Возвращаемые значения

Возвращаемые значения приведены ниже

Возвращаемые значения и Константы

image_typeВозвращаемое значение
IMAGETYPE_GIFimage/gif
IMAGETYPE_JPEGimage/jpeg
IMAGETYPE_PNGimage/png
IMAGETYPE_SWFapplication/x-shockwave-flash
IMAGETYPE_PSDimage/psd
IMAGETYPE_BMPimage/bmp
IMAGETYPE_TIFF_II (порядок байт intel)image/tiff
IMAGETYPE_TIFF_MM (порядок байт motorola)image/tiff
IMAGETYPE_JPCapplication/octet-stream
IMAGETYPE_JP2image/jp2
IMAGETYPE_JPXapplication/octet-stream
IMAGETYPE_JB2application/octet-stream
IMAGETYPE_SWCapplication/x-shockwave-flash
IMAGETYPE_IFFimage/iff
IMAGETYPE_WBMPimage/vnd.wap.wbmp
IMAGETYPE_XBMimage/xbm
IMAGETYPE_ICOimage/vnd.microsoft.icon
IMAGETYPE_WEBPimage/webp

Примеры

Пример #1 Пример использования image_type_to_mime_type()

Источник

filetype

(PHP 4, PHP 5, PHP 7, PHP 8)

filetype — Возвращает тип файла

Описание

Возвращает тип указанного файла.

Список параметров

Возвращаемые значения

Возвращает тип файла. Возможными значениями являются fifo, char, dir, block, link, file, socket и unknown.

Ошибки

Примеры

Пример #1 Пример использования функции filetype()

echo filetype ( ‘/etc/passwd’ ); // file
echo filetype ( ‘/etc/’ ); // dir

Примечания

Смотрите также

User Contributed Notes 6 notes

There are 7 values that can be returned. Here is a list of them and what each one means

block: block special device

char: character special device

fifo: FIFO (named pipe)

link: symbolic link

unknown: unknown file type

filetype() does not work for files >=2GB on x86 Linux. You can use stat as a workarround:

Note that stat returns diffenerent strings («regular file»,»directory». )

I use the CLI version of PHP on Windows Vista. Here’s how to determine if a file is marked «hidden» by NTFS:

This should work on any Windows OS that provides DOS shell commands.

Putting @ in front of the filetype() function does not prevent it from raising a warning (Lstat failed), if E_WARNING is enabled on your error_reporting.

The most common cause of filetype() raising this warning and not showing a filetype() in the output (it actually returns NULL) is, if you happened to pass just the ‘Dir or File Name’ and not the complete «Absolute or Relative Path» to that ‘file or Dir’. It may still read that file and return its filetype as «file» but for Dir’s it shows warning and outputs NULL.
eg:
$pathToFile = ‘/var/www’;
$file = ‘test.php’;
$dir = ‘somedir’;

Output for filetype($file) will be returned as ‘file’ and possibly without any warning, but for filetype($dir), it will return NULL with the warning «Lstat failed», unless you pass a complete path to that dir, i.e. filetype($pathToFile.’/’.$dir).

This happened to me and found this solution after a lot of trial and error. Thought, it might help someone.

Note there is a bug when using filetype with for example Japanese filenames :
https://bugs.php.net/bug.php?id=64699

The whole PHP interpreter comes crashing down without anyway to avoid it or capture an exception.

Источник

mime_content_type

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mime_content_type — Detect MIME Content-type for a file

Description

Returns the MIME content type for a file as determined by using information from the magic.mime file.

Parameters

Path to the tested file.

Return Values

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Examples

Example #1 mime_content_type() Example

The above example will output:

See Also

User Contributed Notes 21 notes

Fast generation of uptodate mime types:

echo
generateUpToDateMimeArray ( APACHE_MIME_TYPES_URL );
?>

Output:
$mime_types = array(
‘123’ => ‘application/vnd.lotus-1-2-3’,
‘3dml’ => ‘text/vnd.in3d.3dml’,
‘3g2’ => ‘video/3gpp2’,
‘3gp’ => ‘video/3gpp’,
‘7z’ => ‘application/x-7z-compressed’,
‘aab’ => ‘application/x-authorware-bin’,
‘aac’ => ‘audio/x-aac’,
‘aam’ => ‘application/x-authorware-map’,
‘aas’ => ‘application/x-authorware-seg’,
.

There is a composer package that will do this:
https://github.com/ralouphie/mimey

= new \ Mimey \ MimeTypes ;

For me mime_content_type didn’t work in Linux before I added

to php.ini (remember to find the correct path to mime.magic)

Lukas V is IMO missing some point. The MIME type of a file may not be corresponding to the file suffix.

Another example is files fetched via a distant server (wget / fopen / file / fsockopen. ). The server can issue an error, i.e. 404 Not Found, wich again is text/html, whatever you save the file to (download_archive.rar).

His provided function should begin by the test of the function existancy like :

function MIMEalternative($file)
<
if(function_exists(‘mime_content_type’))
return mime_content_type($file);
else
return ($file);
>

Regarding serkanyersen’s example : It is advisable to change the regular expression to something more precise like

This makes sure that only the last few characters are taken. The original expression would not work if the filename is a relative path.

if(! function_exists ( ‘mime_content_type’ )) <

Here’s a simple function to return MIME types, based on the Apache mime.types file. [The one in my previous submission, which has since been replaced by this one] only works properly if mime.types is formatted as Windows text. The updated version below corrects this problem. Thanks to Mike for pointing this out.

[2] First param is the filename (required). Second parameter is path to mime.types file (optional; defaults to home/etc/).

[3] Based on MIME types registered with IANA (http://www.iana.org/assignments/media-types/index.html). Recognizes 630 extensions associated with 498 MIME types.

[4] Asserts MIME type based on filename extension. Does not examine the actual file; the file does not even have to exist.

[5] Examples of use:
>> echo get_mime_type(‘myFile.xml’);
>> application/xml
>> echo get_mime_type(‘myPath/myFile.js’);
>> application/javascript
>> echo get_mime_type(‘myPresentation.ppt’);
>> application/vnd.ms-powerpoint
>> echo get_mime_type(‘http://mySite.com/myPage.php);
>> application/x-httpd-php
>> echo get_mime_type(‘myPicture.jpg’);
>> image/jpeg
>> echo get_mime_type(‘myMusic.mp3’);
>> audio/mpeg
and so on.

On Windows, PHP 7.0.30 gave the error message «Fatal error: Uncaught Error: Call to undefined function mime_content_type()». I saw the following interesting line in my Apache configuration:

#LoadModule mime_magic_module modules/mod_mime_magic.so

so I tried uncommenting it and restarting the Apache service, but still got the same error. A Web search shows that this function is deprecated. It appears to have been removed from PHP. Not sure why, but can be worked around with a user function.

The correct little correction:

exec will return the mime with a newline at the end, the trim() should be called with the result of exec, not the other way around.

I added these two lines to my magic.mime file:

// Here is a working version of a function that fetches the meme types from apache’s built in mime list and creates an array of which the keys are the file extensions:

function generateUpToDateMimeArray($url) <
$return = array();
$mimes = file_get_contents(‘http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types’); // make sure that allow_url_fopen is enabled!

I also had issues with this function.

The issue was that it would almost always return «text/plain».

echo ini_get(‘mime_magic.magicfile’); // returns /etc/httpd/conf/magic

I found that I needed the OS’ magic.mime file instead.

You can either copy it to the existing location, or update your php.ini, you cannot use ini_set().

[root@blade conf]# mv magic magic.old
[root@blade conf]# cp /usr/share/magic.mime magic
[root@blade conf]# apachectl graceful

Note: you will see that I have gracefully restarted apache to ensure it has taken affect.

Источник

imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

imagecreatefromstring — Создание нового изображения из потока представленного строкой

Описание

Список параметров

Строка содержащая данные изображения.

Возвращаемые значения

Ошибки

imagecreatefromstring() вызывает ошибку уровня E_WARNING, если данные в неподдерживаемом формате.

Список изменений

ВерсияОписание
8.0.0В случае успешного выполнения функция теперь возвращает экземпляр GDImage ; ранее возвращался ресурс ( resource ).
7.3.0Добавлена поддержка WEBP (если поддерживается используемой libgd).

Примеры

Пример #1 Пример использования imagecreatefromstring()

Результатом выполнения данного примера будет что-то подобное:

php image type file. Смотреть фото php image type file. Смотреть картинку php image type file. Картинка про php image type file. Фото php image type file

Смотрите также

User Contributed Notes 17 notes

While downloading images from internet, it’s easiest to let php decide what is the file type. So, forget using imagecreatefromjpg, imagecreatefromgif and imagecreatefrompng. Instead, this is the way to go:

My site allows anonymous uploads to a web-accessible location (that will execute a script if it finds one).

Naturally, I need to verify that only harmless content is accepted. I am expecting only images, so I use:

So you guys don’t spend an hour trying to figure out why your script keeps running out of memory when you’re using this or the other imagecreatefrom functions. GD uncompresses the image when you use these functions, and this can lead to your script running out of memory.

If you download a rawimage save it on your computer to jpeg so the file size comes down, GD will automatically convert it to the raw and you can possibly run out of memory.

[Editor’s note: BMP will be supported as of PHP 7.2.0.]

In case it’s not obvious from the lack of «imagecreatefrombmp()» in GD, this function cannot handle plain old BMP files either.

I know a lot of people have been having trouble using images from the Sprint PPC6700 with GD. The jpeg library always thows an error about 16 bytes of extraneous data. I decided to poke around in a hex editor and found those extraneous bytes occur right at the end of the exif data.

By removing this extraneous data, images can easily be manipulated by GD and the EXIF extension as a normal images. This also removes any problems using the images with GIMP which must rely on the same jpeg libraries.

Here is a function that will check to see if an image is from the PPC6700 and then remove the extraneous data for you. The result can successully be used with imagecreatefromstring

Author: Paul Visco
IM: paulsidekick
Created: 2-12-06

//get the file contents
$data = file_get_contents($orig);

I use dynamically generated images that require a little touch-up before being displayed. So essentially I do some base work, then store the images in a memory cache (APC), reload the images again from the cache later on «into» GD, do final processing and then display the image.
Since I wanted to avoid a lot of disc access I used the output buffering functions:

// Do your image processing stuff

// Put stuff into cache

// Do final editing stuff and output image
?>

Of course this is a condensed example but I just wanted to share the idea.

An easy example to help understanding this function.

The function will try to auto-determine file format (jpg, gif, png. ), and will return false if fails.

Create an image resource from file, without knowing image type:

A note to the previous question (if you still don’t know it :)).

GIF’s are 256 colors (or 8 bit), and the resample function needs true color I guess. that’s why it works with JPG’s and not with GIF’s.

Next thing. you take a string, write it to file, open the file (imagecreatefromgif), and delete the file again.

if you do imagecreatefromstring($string) you can skip the temporary file part.

If you let them, the PHP function will return an error «Data is not in a recognized format in».

If you have this situation :

$image_string=str_replace(«data:image/png;base64,»,»»,$image_string);
$image_string = base64_decode($image_string);
$img = imagecreatefromstring($image_string);

I run a blogging site that allowed users to publish images from their cell phones. For some reason, the nokia 3220 produces jpegs with extrandeous data before the EOF 0xFFF9

I wrote this class to allow you to fix the images so that they can be used with GD to resize and manipulate. Without applying the fix both GD and gimp report errors for the file. If basically keeps eating bytes from the junk part till the file is a valid jpeg. Here is an example bunk pic written by a nokia 3220 that you cna test it with http://www.shawnrider.com/moblog/cache/0854747001121624103.jpg

/*
Author: Paul Visco
Hompage: http://www.elmwoodstrip.com?u=paul
AIM: paulsidekick
Notes: The file allows you fix the jpegs created by the Nokia 3220 picture phone so that they can be manipulated using the GD library with PHP.

Usage: Simply instanitiate the class and then call the fix method for each image.
e.g.
$nokia = new nokia;
$nokia->debug =»y»;
$nokia->fix(«yourpic.jpg»);
*/

//load the file into a string
$this->str = file_get_contents($this->file);

//test to see if it is a nokia image or if it has been corrupted previously
if (substr_count($this->str, chr(0x28).chr(0x36).chr(0x28).chr(0x2B)) == 0 || @imagecreatefromstring($this->str))
<
if ($this->debug ==»y»)
<
echo «\n
«.$this->file.» is not a corrupted Nokia pic»;
>

//strip out the funk e crap from the file
$this->eat($this->str);

//return true for fixed
return true;

//check the image
$this->img = @imagecreatefromstring($this->str);

//check the image again
$this->img = @imagecreatefromstring($this->str);
>

if ($this->debug ==»y»)
<
//notify the user it’s fixed
echo «\n
Nasty bits eaten!! «.$this->file.» is fixed now thanks to p:labs!»;
>
return true;
>

The only way I managed to resolve the loading of image files from file data either on local site or from off-site protocols is as follows. I hope this saves someone else the two hours of debugging and looking for good examples.
[PHP]

Here is the code I did to create a thumbnail image from the database blob field. The trick is to use «imagecreatefromstring()» to create an image file.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *