Home >Backend Development >PHP Tutorial >Typecho plug-in writing tutorial (6): calling interface, typecho plug-in_PHP tutorial
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
Let’s combine the code provided by Baidu webmaster.
/** * 发送数据 * @param $url 准备发送的url * @param $options 系统配置 */ public static function send_post($url, $options){ //获取API $api = $options->plugin('BaiduSubmitTest')->api; //准备数据 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); //记录日志 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 code The code is as follows:
{"remain":48,"success":1}
Good! It seems there is no problem! However, to be on the safe side, I overridden this method using the http class that comes with typecho.
public static function send_post($url, $options){ //获取API $api = $options->plugin('BaiduSubmitTest')->api; //准备数据 if( is_array($url) ){ $urls = $url; }else{ $urls = array($url); } //为了保证成功调用,老高先做了判断 if (false == Typecho_Http_Client::get()) { throw new Typecho_Plugin_Exception(_t('对不起, 您的主机不支持 php-curl 扩展而且没有打开 allow_url_fopen 功能, 无法正常使用此功能')); } //发送请求 $http = Typecho_Http_Client::get(); $http->setData(implode("\n", $urls)); $http->setHeader('Content-Type','text/plain'); $result = $http->send($api); //记录日志 file_put_contents('/tmp/send_log', date('H:i:s') . $result . "\n"); } }
Now our plug-in can basically run, but the structure can be further optimized!