Home  >  Article  >  Backend Development  >  How to convert files to binary output in PHP

How to convert files to binary output in PHP

藏色散人
藏色散人Original
2020-07-28 10:00:585530browse

PHP method to convert files to binary: first set "header("Content-type: image/jpeg");"; then open and read the file through the fopen and fread functions; finally convert the image file to binary Just output the stream to the client.

How to convert files to binary output in PHP

Recommended: "PHP Tutorial"

php converts files into binary output

header( "Content-type: image/jpeg");
$PSize = filesize('1.jpg');
$picturedata = fread(fopen('1.jpg', "r"), $PSize);
echo $picturedata;

With just a few words, the picture is output to the client in the form of a binary stream, which is no different from opening a picture. It should be noted that the header sent should be determined according to the specific situation. Not necessarily all image/jpeg. JPG is it, but PNG is image/png. Different pictures output different headers.

Purpose:

OSS supports uploading file streams by default, but the input form returns a file by default:

 /**
    * 支持文件类型上传到OSS
    */
    public static  function uploadFile($filename, $ext = 'jpg', $type = Enum_OSS_File_Type::IMG) {
        $content = static::file2content($filename);
        return static::upload($content, $ext, $type);
    }
    
    public static  function file2content($filename) {
        return fread(fopen($filename, 'r'), filesize($filename));
    }

The above is the detailed content of How to convert files to binary output in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn