原贴 百度站长推送php,获取随机100条网址并推送 - 经验分享
写的很不错,我只是借花献佛,在原贴的代码基础上,增加了网站安全,防止SQL注入,对代码进行优化
geturl.php的代码
<?php
// 添加错误报告
error_reporting(E_ALL);
ini_set('display_errors', 1);
$config = include("application/database.php");
// 添加连接错误处理
$conn = mysqli_connect($config['hostname'], $config['username'], $config['password'], $config['database']);
if (!$conn) {
die("数据库连接失败: " . mysqli_connect_error());
}
mysqli_query($conn, "SET NAMES UTF8");
// 使用预处理语句
$stmt = mysqli_prepare($conn, "SELECT aid, typeid FROM ey_archives WHERE author != '' ORDER BY RAND() LIMIT 100");
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$urls = [];
while ($row = mysqli_fetch_array($result)) {
$typeid = $row['typeid'];
// 使用预处理语句
$stmt2 = mysqli_prepare($conn, "SELECT dirpath FROM ey_arctype WHERE id = ?");
mysqli_stmt_bind_param($stmt2, "i", $typeid);
mysqli_stmt_execute($stmt2);
$result1 = mysqli_stmt_get_result($stmt2);
if ($row1 = mysqli_fetch_row($result1)) {
$urls[] = $web . $row1[0] . '/' . $row['aid'] . '.html';
}
}
?>
tuisong.php的代码
<?php
include("geturl.php");
$api = 'http://data.zz.baidu.com/urls?site=你的网址&token=你的token';
$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'),
CURLOPT_TIMEOUT => 30 // 添加超时设置
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if ($result === false) {
// 记录错误日志
file_put_contents('push_error.log', date('Y-m-d H:i:s') . ' - ' . curl_error($ch) . "\n", FILE_APPEND);
} else {
// 记录成功日志
file_put_contents('push_success.log', date('Y-m-d H:i:s') . ' - ' . $result . "\n", FILE_APPEND);
}
curl_close($ch);
echo $result;
?>
上面这两个PHP代码,作了一下SQL的防注入,如果放在易优网站的目录,防SQL注入就更为重要了。感谢原贴作者。