php网站广告实现
广告投放基础实现
在PHP网站中实现广告功能通常需要结合数据库存储广告信息,并通过PHP动态调用展示。以下是基础实现方式:
创建广告数据表结构:
CREATE TABLE ads (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255),
image_url VARCHAR(255),
target_url VARCHAR(255),
start_date DATETIME,
end_date DATETIME,
impression_count INT DEFAULT 0,
click_count INT DEFAULT 0,
is_active BOOLEAN DEFAULT 1
);
随机广告展示
从数据库随机获取有效广告并展示:
function displayRandomAd() {
$currentDate = date('Y-m-d H:i:s');
$query = "SELECT * FROM ads
WHERE is_active = 1
AND start_date <= '$currentDate'
AND end_date >= '$currentDate'
ORDER BY RAND() LIMIT 1";
// 执行查询并输出广告HTML
if ($ad = fetchFromDatabase($query)) {
echo '<a href="track_click.php?id='.$ad['id'].'" target="_blank">';
echo '<img src="'.$ad['image_url'].'" alt="'.$ad['title'].'">';
echo '</a>';
// 更新展示次数
updateImpression($ad['id']);
}
}
点击跟踪功能
创建track_click.php处理点击统计:
$adId = $_GET['id'] ?? 0;
if ($adId) {
$query = "UPDATE ads SET click_count = click_count + 1 WHERE id = $adId";
executeQuery($query);
// 获取实际广告链接并跳转
$target = getAdTargetUrl($adId);
header("Location: $target");
exit;
}
轮播广告实现
使用JavaScript实现多广告轮播展示:
function getActiveAds() {
$currentDate = date('Y-m-d H:i:s');
return fetchAll("SELECT * FROM ads
WHERE is_active = 1
AND start_date <= '$currentDate'
AND end_date >= '$currentDate'
LIMIT 5");
}
前端轮播代码示例:
let currentAd = 0;
const ads = document.querySelectorAll('.ad-item');
setInterval(() => {
ads[currentAd].classList.remove('active');
currentAd = (currentAd + 1) % ads.length;
ads[currentAd].classList.add('active');
}, 5000);
广告权重控制
按权重概率展示不同广告:
function getWeightedAd() {
$query = "SELECT *, (RAND() * weight) AS sort_order
FROM ads
WHERE is_active = 1
ORDER BY sort_order DESC
LIMIT 1";
return fetchFromDatabase($query);
}
需要在ads表中添加weight字段:
ALTER TABLE ads ADD COLUMN weight INT DEFAULT 10;
第三方广告集成
集成Google AdSense示例:
function showGoogleAd() {
echo '<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-YOUR_PUBLISHER_ID"
data-ad-slot="YOUR_AD_SLOT"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>';
}
广告效果统计
创建统计报表页面:
function getAdPerformanceReport() {
return fetchAll("SELECT
id,
title,
impression_count,
click_count,
ROUND((click_count/impression_count)*100, 2) AS ctr
FROM ads
ORDER BY impression_count DESC");
}
广告缓存优化
使用Redis缓存热门广告:
function getCachedAd($position) {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
if (!$ad = $redis->get("ad:$position")) {
$ad = getWeightedAdForPosition($position);
$redis->setex("ad:$position", 3600, serialize($ad));
} else {
$ad = unserialize($ad);
}
return $ad;
}






