文章發布/更新時自動通知百度,加速收錄。返回 XML 中 <int>0</int> 表示成功。
<?php
$pingUrl = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$arcPing = new Ping('站點標題', $pingUrl, get_domain(), 'https://www.example.com/rss.xml');
$arcPing->pingBaidu();
?>
<?php
class Ping {
private $title, $hostUrl, $artUrl, $rssUrl, $baiduXml, $baiduRpc = 'https://ping.baidu.com/ping/RPC2';
public function __construct($title, $artUrl, $hostUrl, $rssUrl) {
if (empty($title) || empty($artUrl)) return false;
$this->title = $title;
$this->artUrl = $artUrl;
$this->hostUrl = $hostUrl;
$this->rssUrl = $rssUrl;
$this->baiduXml = '<?xml version="1.0" encoding="UTF-8"?>';
$this->baiduXml .= '<methodCall><methodName>weblogUpdates.extendedPing</methodName><params>';
$this->baiduXml .= '<param><value><string>' . $this->hostUrl . '</string></value></param>';
$this->baiduXml .= '<param><value><string>' . $this->title . '</string></value></param>';
$this->baiduXml .= '<param><value><string>' . $this->artUrl . '</string></value></param>';
$this->baiduXml .= '<param><value><string>' . $this->rssUrl . '</string></value></param>';
$this->baiduXml .= '</params></methodCall>';
}
public function pingBaidu() {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $this->baiduRpc,
CURLOPT_HEADER => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => [
'User-Agent: request',
'Host: ping.baidu.com',
'Content-Type: text/xml',
],
CURLOPT_POSTFIELDS => $this->baiduXml,
]);
$res = curl_exec($ch);
curl_close($ch);
return strpos($res, '<int>0</int>') !== false;
}
}
function get_domain() {
$protocol = 'https://';
if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
elseif (isset($_SERVER['HTTP_HOST'])) $host = $_SERVER['HTTP_HOST'];
else {
$port = '';
if (isset($_SERVER['SERVER_PORT'])) {
$port = ':' . $_SERVER['SERVER_PORT'];
if (($port === ':80' && $protocol === 'https://') || ($port === ':443' && $protocol === 'https://')) $port = '';
}
$host = (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : $_SERVER['SERVER_ADDR']) . $port;
}
return $protocol . $host;
}
?>