核心邏輯已獲取永久鏈接,本節實現 send_post() 方法:構建推送數組、調用百度站長 API、記錄推送日誌。對比原生 cURL 與 Typecho 內置 Typecho_Http_Client 兩種實現,推薦後者兼容性更好。
public static function send_post($url, $options) {
$api = $options->plugin('BaiduSubmitTest')->api;
$urls = is_array($url) ? $url : array($url);
$ch = curl_init();
$opts = 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, $opts);
$result = curl_exec($ch);
file_put_contents('/tmp/send_log', date('H:i:s') . ' ' . $result . "\n", FILE_APPEND);
}
返回示例:{"remain":48,"success":1} 表示當日剩餘配額 48、本次成功推送 1 條。
public static function send_post($url, $options) {
$api = $options->plugin('BaiduSubmitTest')->api;
$urls = is_array($url) ? $url : array($url);
// 環境檢查:需 curl 擴展或 allow_url_fopen
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", FILE_APPEND);
}
fopen 流上下文,兼容性極強。setData()/setHeader()/send() 鏈式調用,代碼更清晰。Typecho_Plugin_Exception,符合插件規範,後台可捕獲展示。$options->plugin('BaiduSubmitTest')->log_path。目前邏輯分散在 send()(獲取鏈接)與 send_post()(推送),下一步將合併優化:send() 內部直接調用 send_post(),異常統一捕獲、重試機制、批量推送合併(單次最多 2000 條),構建生產級推送模塊。