文章摘要
这篇文章介绍了一段用于在Bing、IndexNow和Yandex(易 acids)搜索引擎上主动推送链接的PHP代码。代码旨在配置网站主域名、生成验证密钥,并通过curl函数发送请求到目标搜索引擎。文章强调了代码的灵活性和配置部分的详细说明,并提供了在网页中引用代码的示例。此外,文章还简要提到了如何通过开发者工具调试以及解决常见错误的方法。
如果你的网站打算将链接主动推送到 bing\indexnow\yandex 搜索引擎,你可以使用下面的代码来自动推送。
基本php版本越高越好
下面的代码 去掉了PHP新版本语法,理论上php>=7即可使用。
<?php
// 配置
// 网站的主域名
$host = 'www.4414.cn';
// 配置的key,自己生成32位字符串
$key = 'c29f72027ef343988ef0d1cdcdcc40ee';
// 给平台验证key的链接,名称随意,不一定叫mykey.txt。但是这个文件里的内容就是你自己生成的 32位字符串 key
$keyLocation = 'https://www.4414.cn/mykey.txt';
$messages = [];
if (!empty($_SERVER['HTTP_REFERER'])) {
$url = $_SERVER['HTTP_REFERER'];
$messages[] = '推送链接:' . $url;
$result = indexNowPush('www.bing.com', [
'http://www.example.com/'
]);
$messages[] = 'www.bing.com 推送结果:' . ($result ? '成功' : '失败');
$result = indexNowPush('api.indexnow.org', [
'http://www.example.com/'
]);
$messages[] = 'api.indexnow.org 推送结果:' . ($result ? '成功' : '失败');
$result = indexNowPush('yandex.com', [
'http://www.example.com/'
]);
$messages[] = 'yandex.com 推送结果:' . ($result ? '成功' : '失败');
} else {
$messages[] = '没有读取到推送链接,无需推送';
}
header('Content-Type: application/javascript');
foreach ($messages as $message) {
echo 'console.log("' . $message . '");';
}
/**
* indexnow推送
* @param string $searchengine 推送的搜索引擎,api.indexnow.org、www.bing.com、yandex.com
* @param array $urls 推送网址
* @return bool
*/
function indexNowPush($searchengine, $urls)
{
global $host;
global $key;
global $keyLocation;
if (empty($urls)) {
return false;
}
$data = [
'host' => $host,
'key' => $key,
'keyLocation' => $keyLocation,
'urlList' => $urls
];
$data = json_encode($data, JSON_UNESCAPED_UNICODE);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://' . $searchengine . '/indexnow');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Host: ' . $searchengine,
'Content-Type: application/json',
'Content-Length:' . strlen($data)
]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($ch);
$httpCode = 0;
if (!curl_errno($ch)) {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
curl_close($ch);
return $httpCode === 200;
}
使用说明:将上面代码保存到某个php文件内容里,例如:indexnow.php。然后将这个php文件上传到你的服务器可以运行的位置,放在网站根目录即可。
修改上面代码中的配置部分。
// 配置 // 网站的主域名 $host = 'www.4414.cn'; // 配置的key,自己生成32位字符串 $key = 'c29f72027ef343988ef0d1cdcdcc40ee'; // 给平台验证key的链接,名称随意,不一定叫mykey.txt。但是这个文件里的内容就是你自己生成的 32位字符串 key $keyLocation = 'https://www.4414.cn/mykey.txt';
然后在你的网站每个页面加入引用代码,类似于js引用。
<script src="http://192.168.1.100:5004/indexnow.php"></script>
上面那个链接地址换成你的网站indexnow.php链接地址。
下面是完整的示例。
访问你的网站页面地址,然后按f12打开开发者调试工具,控制台会打印推送结果。
如果出现php错误41的问题。可以尝试以下方法解决
你可以将这行代码改一下:function indexNowPush(string $searchengine, array $urls): bool
改为:function indexNowPush($searchengine, $urls)

Villain博客
