Home >Backend Development >PHP Tutorial >Typecho plug-in writing tutorial (6): calling interface_PHP tutorial
This article mainly introduces the typecho plug-in writing tutorial (6): Calling the interface. This is the last article in the series. , friends in need can refer to it
In this article, we start to call the interface. We define a new method in the plug-in class, named send_post. In the method, we obtain the interface calling address through the system configuration.
The example given by Baidu uses php's CURL. For more advanced usage, you can learn the PHP_cURL initialization and execution method
Now let’s combine the code provided by Baidu webmaster.
?
|
/** * Send data * @param $url The url to be sent * @param $options system configuration */ public static function send_post($url, $options){ //Get API $api = $options->plugin('BaiduSubmitTest')->api; //Prepare data if( is_array($url) ){ $urls = $url; }else{ $urls = array($url); } $ch = curl_init(); $options = array( CURLOPT_URL => $api, CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => implode("n", $urls), CURLOPT_HTTPHEADER => array('Content-Type: text/plain'), ); curl_setopt_array($ch, $options); $result = curl_exec($ch); //Record log file_put_contents('/tmp/send_log', date('H:i:s') . $result . "n"); } |
Since we haven’t established a logging system yet, we will write the log to a file first and see the effect first!
Return value:
Copy the code. The code is as follows:
{"remain":48,"success":1}
Good! It seems there is no problem! But just to be on the safe side, I overridden this method using the http class that comes with typecho.
?
2 3 11 12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
public static function send_post($url, $options){ //Get API $api = $options->plugin('BaiduSubmitTest')->api; //Prepare data if( is_array($url) ){ $urls = $url; }else{ $urls = array($url); } //In order to ensure a successful call, Lao Gao made a judgment first if (false == Typecho_Http_Client::get()) { throw new Typecho_Plugin_Exception(_t('Sorry, your host does not support the php-curl extension and the allow_url_fopen function is not turned on, so this function cannot be used normally')); } //Send request $http = Typecho_Http_Client::get(); $http->setData(implode("n", $urls)); $http->setHeader('Content-Type','text/plain'); $result = $http->send($api); //Record log file_put_contents('/tmp/send_log', date('H:i:s') . $result . "n"); } } |