PHP 收藏本站代码通常是指使用 PHP 编写的一段脚本,用于实现用户将当前网页添加到收藏夹的功能。这种功能通常通过 JavaScript 或者 PHP 与浏览器的交互来实现。
适用于任何希望用户能够方便收藏网页的网站,如新闻网站、博客、电子商务平台等。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>收藏本站</title>
</head>
<body>
<button onclick="addFavorite()">收藏本站</button>
<script>
function addFavorite() {
if (window.sidebar && window.sidebar.addPanel) { // Firefox
window.sidebar.addPanel(document.title, window.location.href, "");
} else if (window.external && ('AddFavorite' in window.external)) { // Internet Explorer
window.external.AddFavorite(location.href, document.title);
} else if (window.opera && window.print) { // Opera
return true;
} else { // Other browsers (Chrome, Safari)
alert('请按 Ctrl+D 手动添加到收藏夹。');
}
}
</script>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['url']) && isset($_POST['title'])) {
$url = $_POST['url'];
$title = $_POST['title'];
// 这里可以添加一些验证逻辑,确保 URL 和 Title 是合法的
echo json_encode(['status' => 'success', 'message' => '收藏成功']);
} else {
echo json_encode(['status' => 'error', 'message' => '请求不合法']);
}
?>
前端 HTML 和 JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>收藏本站</title>
</head>
<body>
<button onclick="addFavorite()">收藏本站</button>
<script>
async function addFavorite() {
const url = window.location.href;
const title = document.title;
const response = await fetch('path/to/your/php/script.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ url, title })
});
const data = await response.json();
if (data.status === 'success') {
alert(data.message);
} else {
alert('收藏失败,请重试。');
}
}
</script>
</body>
</html>
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云