PHP remote image capturing tutorial

Source: Internet
Author: User
PHP remote image capturing tutorial (including pictures without a suffix) before login and development, we found that there is no suffix in the avatar image, the traditional image capturing method does not work, and requires special crawling. Therefore, we combined various situations and encapsulated them into a class for sharing.

Create a project

As a demonstration, we create the project grabimg in the www root directory, create a class GrabImage. php and an index. php.

Write class code

We define a class with the same file name: GrabImage

class GrabImage{}

Attribute

Next we will define several required attributes.

1. first define an image address to be captured: $ img_url

2. define another $ file_name to store the file name, but do not carry the extended name. because it may involve the replacement of the extended name, we will split the definition here.

3. the extended name $ extension

4. then we define a $ file_dir. the function of this attribute is that the directory stored after the remote image is captured to the local directory, generally starting with the position of the PHP entry file. However, this path is generally not saved to the database.

5. Finally, we define a $ save_dir. as the name suggests, this path is the Directory of the database for direct storage. Here, we do not directly store the file storage path to the database. it is generally used to prepare for a later migration if the system is migrated to facilitate the replacement of the path. Here, $ save_dir is generally used as the date + file name. if you need to use it, put the required path in the front.

Method

After the attributes are completed, we will start crawling.

First, we define an open method getInstances to obtain some data, such as image capture address and local storage path. Put it into the attribute at the same time.

Public function getInstances ($ img_url, $ base_dir) {$ this-> img_url = $ img_url; $ this-> save_dir = date ("Ym "). '/'. date ("d "). '/'; // for example: 201610/19/$ this-> file_dir = $ base_dir. '/'. $ this-> save_dir. '/'; // for example :. /uploads/image/2016/10/19 /}

After splicing the image storage path, we need to check whether the directory exists. The date is on a daily basis, but the directory is not automatically created. Therefore, before saving the image, you must first check that if the current directory does not exist, we need to create it immediately.

The setDir directory method is created. Private and secure attributes are set.

/*** Check whether the directory to be maintained for the image exists * if not, create a directory * @ return bool */private function setDir () {if (! File_exists ($ this-> file_dir) {mkdir ($ this-> file_dir, 0777, TRUE) ;}$ this-> file_name = uniqid (). rand (names, 99999); // file name. this is just a demonstration. in actual projects, use your own unique file name generation method to return true ;}

The next step is to capture the core code

The first step is to solve the problem. The image to be crawled may have no suffix. According to the traditional method of capturing images, it is not feasible to capture images first and then extract the suffix.

We must use other methods to obtain the image type. The method is to obtain the file header information from the file stream information, so as to determine the file mime information, you can know the file suffix.

For convenience, first define a mime and file extension name ING.

$mimes=array(    'image/bmp'=>'bmp',    'image/gif'=>'gif',    'image/jpeg'=>'jpg',    'image/png'=>'png',    'image/x-icon'=>'ico');

In this way, when I obtain an image or GIF image of the type, I can know that it is a. gif image.

Use the php function get_headers to obtain the file stream header information. When its value is not false, we assign it to the variable $ headers.

The value of Content-Type is the mime value.

If ($ headers = get_headers ($ this-> img_url, 1 ))! = False) {// response type $ Type = $ headers ['content-type'];}

Using the ing table we defined above, we can easily get the suffix name.

$this->extension=$mimes[$type];

Of course, the $ type obtained above may not exist in our ing table, indicating that this type of file is not what we want, just discard it directly, don't worry about it.

The following steps are the same as traditional file capturing.

$ File_path = $ this-> file_dir. $ this-> file_name. ". ". $ this-> extension; // get data and save $ contents = file_get_contents ($ this-> img_url); if (file_put_contents ($ file_path, $ contents )) {// the returned value is the path + file name saved directly to the database, for example, 201610/19/57feefd7e2a7aY5p7LsPqaI-lY1BF.jpg return $ this-> save_dir. $ this-> file_name. ". ". $ this-> extension ;}

First, obtain the complete path $ file_path for saving the local image. Then, use file_get_contents to capture data and then use file_put_contents to save it to the file path.

Finally, we return a path that can be directly saved to the database, rather than the file storage path.

The full version of this method is:

Private function getRemoteImg () {// mime ing of mime and extension $ mimes = array ('image/bmp '=> 'bmp', 'image/GIF' => 'GIF ', 'image/jpeg '=> 'jpg', 'image/png '=> 'PNG', 'image/x-icon '=> 'ico '); // Obtain the response header if ($ headers = get_headers ($ this-> img_url, 1 ))! = False) {// response type $ Type = $ headers ['content-type']; // if the desired type is met, if (isset ($ mimes [$ type]) {$ this-> extension = $ mimes [$ type]; $ file_path = $ this-> file_dir. $ this-> file_name. ". ". $ this-> extension; // get data and save $ contents = file_get_contents ($ this-> img_url); if (file_put_contents ($ file_path, $ contents )) {// the returned value is the path + file name saved directly to the database, for example, 201610/19/57feefd7e2a7aY5p7LsPqaI-lY1BF.jpg return $ this-> save_dir. $ this-> file_name. ". ". $ this-> extension; }}return false ;}

Finally, for simplicity, we want to call one of the methods in other places to complete the capture. Therefore, we put the capture action directly into getInstances and directly crawl it after configuring the path. Therefore, we add code in the initialization configuration method getInstances.

if($this->setDir()){    return $this->getRemoteImg();}else{    return false;}

Test

Let's try it in the index. php file just created.

 GetInstances ($ img_url, $ base_dir);?>

You did capture it.

Complete Code

 * @ Link bidianer.com */class GrabImage {/*** @ var string the address of the remote image to be crawled * example: http://www.bidianer.com/img/icon_mugs.jpg * Some remote file paths may not contain extended names *, for example: http://www.xxx.com/img/icon_mugs/q/0 */Private $ img_url;/*** @ var string the name of the file to be saved * the file to be crawled to the local file name will be regenerated * However, without an extended name * for example: 57feefd7e2a7aY5p7LsPqaI-lY1BF */private $ file_name;/*** @ var string file extension name * use remote image extension name here * for remote images without extension name, it will be obtained from the File Stream * for example :. jpg */private $ extension; /*** @ var string file stored in the local directory * the path here is the path for saving the file in PHP * generally relative to the path saved in the entry file * for example :. /uploads/image/201610/19/* but this path is generally not directly stored in the database */private $ file_dir;/*** @ var string database file directory * This path is the image path directly saved to the database * generally, the date + file name are saved directly, you need to use the preceding path * to migrate the system. * For example, 201610/19/*/private $ save_dir; /*** @ param string $ img_url address of the image to be captured * @ param string $ base_dir local save path, for example :. /uploads/image, without the slash "/" * @ return bool | int */public function getInstances ($ img_url, $ base_dir) {$ this-> img_url = $ img_url; $ this-> save_dir = date ("Ym "). '/'. date ("d "). '/'; // for example: 201610/19/$ this-> file_dir = $ Base_dir. '/'. $ this-> save_dir. '/'; // for example :. /uploads/image/2016/10/19/return $ this-> start ();}/*** start image capturing */private function start () {if ($ this-> setDir () {return $ this-> getRemoteImg ();} else {return false ;}} /*** check whether the directory to be maintained for the image exists * if not, create a directory * @ return bool */private function setDir () {if (! File_exists ($ this-> file_dir) {mkdir ($ this-> file_dir, 0777, TRUE) ;}$ this-> file_name = uniqid (). rand (steps, 99999); // file name. here is only a demonstration. in actual projects, use your own unique file name generation method to return true;}/*** capture remote image core method, you can simultaneously capture images with extensions and images without extensions ** @ return bool | int */private function getRemoteImg () {// mime ing of mime and extension $ mimes = array ('image/bmp '=> 'bmp', 'image/GIF' => 'GIF ', 'image/jpeg '=> 'jpg', 'image/png '=> 'PNG', 'image/x-icon '=> 'ico ');/ /Obtain the response header if ($ headers = get_headers ($ this-> img_url, 1 ))! = False) {// response type $ Type = $ headers ['content-type']; // if the desired type is met, if (isset ($ mimes [$ type]) {$ this-> extension = $ mimes [$ type]; $ file_path = $ this-> file_dir. $ this-> file_name. ". ". $ this-> extension; // get data and save $ contents = file_get_contents ($ this-> img_url); if (file_put_contents ($ file_path, $ contents )) {// the returned value is the path + file name saved directly to the database, for example, 201610/19/57feefd7e2a7aY5p7LsPqaI-lY1BF.jpg return $ this-> save_dir. $ this-> file_name. ". ". $ this-> extension ;}}return false ;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.