When I was doing WeChat login development before, I found that WeChat avatar pictures did not have a suffix name. The traditional image capture method did not work and required special capture processing. Therefore, various situations were later combined, encapsulated into a class, and shared.
Create 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 name as the file: GrabImage
class GrabImage{}
Attributes
Next define several attributes that need to be used.
1. First define an image address that needs to be captured: $img_url
2. Then define a $file_name to store the name of the file, but does not carry the extension name, because it may involve extension name replacement, so I will unpack it here. Definition
3, followed by the extension name $extension
4, and then we define a $file_dir. The function of this attribute is to store the directory where the remote image is captured to the local, generally relative to the location of the PHP entry file. as a starting point. 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 used to save directly. To explain here, we do not directly store the file saving path in the database. This is usually to prepare for the convenience of changing the path if the system is migrated later. Our $save_dir here is generally the date + file name. If you need to use it, take it out and spell the required path in front.
Method
Attributes are finished, now we officially start the crawling work.
First we define an open method getInstances to obtain some data, such as the address of the captured image and the local save path. Also put it in properties.
public function getInstances($img_url , $base_dir) { $this->img_url = $img_url; $this->save_dir = date("Ym").'/'.date("d").'/'; // 比如:201610/19/ $this->file_dir = $base_dir.'/'.$this->save_dir.'/'; // 比如:./uploads/image/2016/10/19/ }
The picture saving path is spliced. Now we have to pay attention to a question, whether the directory exists. The date goes by day by day, but the directory is not automatically created. Therefore, before saving the image, you need to check it first. If the current directory does not exist, we need to create it immediately.
We create the set directory method setDir. We set the attribute to private, which is safe
/** * 檢查圖片需要保持的目錄是否存在 * 如果不存在,則立即創(chuàng)建一個(gè)目錄 * @return bool */ private function setDir() { if(!file_exists($this->file_dir)) { mkdir($this->file_dir,0777,TRUE); } $this->file_name = uniqid().rand(10000,99999);// 文件名,這里只是演示,實(shí)際項(xiàng)目中請(qǐng)使用自己的唯一文件名生成方法 return true; }
The next step is to capture the core code
The first step is to solve a problem. The images we need to capture may not have a suffix name. According to the traditional crawling method, it is not feasible to crawl the image first and then intercept the suffix name.
We must get the image type through other methods. The method is to obtain the file header information from the file stream information, thereby judging the file mime information, and then you can know the file suffix name.
For convenience, first define a mime and file extension mapping.
$mimes=array( 'image/bmp'=>'bmp', 'image/gif'=>'gif', 'image/jpeg'=>'jpg', 'image/png'=>'png', 'image/x-icon'=>'ico' );
In this way, when I get the type of image/gif, I can know that it is a .gif picture.
Use the php function get_headers to obtain file stream header information. When its value is not false, we assign it to the variable $headers
and take out the value of Content-Type which is the value of mime.
if(($headers=get_headers($this->img_url, 1))!==false){ // 獲取響應(yīng)的類型 $type=$headers['Content-Type']; }
Using the mapping table we defined above, we can easily obtain the suffix name.
$this->extension=$mimes[$type];
Of course, the $type obtained above may not exist in our mapping table, which means that this type of file is not what we want. Just discard it and ignore it.
The following steps are the same as traditional grabbing files.
$file_path = $this->file_dir.$this->file_name.".".$this->extension; // 獲取數(shù)據(jù)并保存 $contents=file_get_contents($this->img_url); if(file_put_contents($file_path , $contents)) { // 這里返回出去的值是直接保存到數(shù)據(jù)庫的路徑 + 文件名,形如:201610/19/57feefd7e2a7aY5p7LsPqaI-lY1BF.jpg return $this->save_dir.$this->file_name.".".$this->extension; }
First get the full path of the local saved image $file_path, then use file_get_contents to grab the data, and then use file_put_contents to save to the file path just now.
Finally we return a path that can be saved directly to the database instead of a file storage path.
The complete version of this crawling method is:
private function getRemoteImg() { // mime 和 擴(kuò)展名 的映射 $mimes=array( 'image/bmp'=>'bmp', 'image/gif'=>'gif', 'image/jpeg'=>'jpg', 'image/png'=>'png', 'image/x-icon'=>'ico' ); // 獲取響應(yīng)頭 if(($headers=get_headers($this->img_url, 1))!==false) { // 獲取響應(yīng)的類型 $type=$headers['Content-Type']; // 如果符合我們要的類型 if(isset($mimes[$type])) { $this->extension=$mimes[$type]; $file_path = $this->file_dir.$this->file_name.".".$this->extension; // 獲取數(shù)據(jù)并保存 $contents=file_get_contents($this->img_url); if(file_put_contents($file_path , $contents)) { // 這里返回出去的值是直接保存到數(shù)據(jù)庫的路徑 + 文件名,形如:201610/19/57feefd7e2a7aY5p7LsPqaI-lY1BF.jpg return $this->save_dir.$this->file_name.".".$this->extension; } } } return false; }
最后,為了簡單,我們想在其他地方只要調(diào)用其中一個(gè)方法就可以完成抓取。所以,我們將抓取動(dòng)作直接放入到getInstances中,在配置完路徑后,直接抓取,所以,在初始化配置方法getInstances里新增代碼。
if($this->setDir()) { return $this->getRemoteImg(); } else { return false; }
測試
我們?nèi)倓倓?chuàng)建的index.php文件內(nèi)試試。
<?php require_once 'GrabImage.php'; $object = new GrabImage(); $img_url = "http://www.bidianer.com/img/icon_mugs.jpg"; // 需要抓取的遠(yuǎn)程圖片 $base_dir = "./uploads/image"; // 本地保存的路徑 echo $object->getInstances($img_url , $base_dir); ?>
惹,的確抓取過來了
完整代碼
* @link bidianer.com */ class GrabImage{ /** * @var string 需要抓取的遠(yuǎn)程圖片的地址 * 例如:http://www.bidianer.com/img/icon_mugs.jpg * 有一些遠(yuǎn)程文件路徑可能不帶拓展名 * 形如:http://www.xxx.com/img/icon_mugs/q/0 */ private $img_url; /** * @var string 需要保存的文件名稱 * 抓取到本地的文件名會(huì)重新生成名稱 * 但是,不帶拓展名 * 例如:57feefd7e2a7aY5p7LsPqaI-lY1BF */ private $file_name; /** * @var string 文件的拓展名 * 這里直接使用遠(yuǎn)程圖片拓展名 * 對(duì)于沒有拓展名的遠(yuǎn)程圖片,會(huì)從文件流中獲取 * 例如:.jpg */ private $extension; /** * @var string 文件保存在本地的目錄 * 這里的路徑是PHP保存文件的路徑 * 一般相對(duì)于入口文件保存的路徑 * 比如:./uploads/image/201610/19/ * 但是該路徑一般不直接存儲(chǔ)到數(shù)據(jù)庫 */ private $file_dir; /** * @var string 數(shù)據(jù)庫保存的文件目錄 * 這個(gè)路徑是直接保存到數(shù)據(jù)庫的圖片路徑 * 一般直接保存日期 + 文件名,需要使用的時(shí)候拼上前面路徑 * 這樣做的目的是為了遷移系統(tǒng)時(shí)候方便更換路徑 * 例如:201610/19/ */ private $save_dir; /** * @param string $img_url 需要抓取的圖片地址 * @param string $base_dir 本地保存的路徑,比如:./uploads/image,最后不帶斜杠"/" * @return bool|int */ public function getInstances($img_url , $base_dir) { $this->img_url = $img_url; $this->save_dir = date("Ym").'/'.date("d").'/'; // 比如:201610/19/ $this->file_dir = $base_dir.'/'.$this->save_dir.'/'; // 比如:./uploads/image/2016/10/19/ return $this->start(); } /** * 開始抓取圖片 */ private function start() { if($this->setDir()) { return $this->getRemoteImg(); } else { return false; } } /** * 檢查圖片需要保持的目錄是否存在 * 如果不存在,則立即創(chuàng)建一個(gè)目錄 * @return bool */ private function setDir() { if(!file_exists($this->file_dir)) { mkdir($this->file_dir,0777,TRUE); } $this->file_name = uniqid().rand(10000,99999);// 文件名,這里只是演示,實(shí)際項(xiàng)目中請(qǐng)使用自己的唯一文件名生成方法 return true; } /** * 抓取遠(yuǎn)程圖片核心方法,可以同時(shí)抓取有后綴名的圖片和沒有后綴名的圖片 * * @return bool|int */ private function getRemoteImg() { // mime 和 擴(kuò)展名 的映射 $mimes=array( 'image/bmp'=>'bmp', 'image/gif'=>'gif', 'image/jpeg'=>'jpg', 'image/png'=>'png', 'image/x-icon'=>'ico' ); // 獲取響應(yīng)頭 if(($headers=get_headers($this->img_url, 1))!==false) { // 獲取響應(yīng)的類型 $type=$headers['Content-Type']; // 如果符合我們要的類型 if(isset($mimes[$type])) { $this->extension=$mimes[$type]; $file_path = $this->file_dir.$this->file_name.".".$this->extension; // 獲取數(shù)據(jù)并保存 $contents=file_get_contents($this->img_url); if(file_put_contents($file_path , $contents)) { // 這里返回出去的值是直接保存到數(shù)據(jù)庫的路徑 + 文件名,形如:201610/19/57feefd7e2a7aY5p7LsPqaI-lY1BF.jpg return $this->save_dir.$this->file_name.".".$this->extension; } } } return false; } }

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHP provides an input basis for AI models by collecting user data (such as browsing history, geographical location) and pre-processing; 2. Use curl or gRPC to connect with AI models to obtain click-through rate and conversion rate prediction results; 3. Dynamically adjust advertising display frequency, target population and other strategies based on predictions; 4. Test different advertising variants through A/B and record data, and combine statistical analysis to optimize the effect; 5. Use PHP to monitor traffic sources and user behaviors and integrate with third-party APIs such as GoogleAds to achieve automated delivery and continuous feedback optimization, ultimately improving CTR and CVR and reducing CPC, and fully implementing the closed loop of AI-driven advertising system.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway
