brunoinds/link-preview-detector

检测请求是否为生成预览

v1.0.0 2023-11-28 08:10 UTC

This package is auto-updated.

Last update: 2024-09-11 03:51:11 UTC


README

用例

这个工具解决了现代网络开发中的一个常见问题:如何检测请求是否为生成链接预览?

假设你的网页需要为Facebook、WhatsApp和Twitter等平台生成链接预览。这些预览是通过meta标签生成的,这可能会减慢你的页面加载时间。理想情况下,你只想在这些平台的机器人请求时生成这些meta标签,而不是当普通用户打开页面时。

这个工具提供了一个简单的函数,允许你确定页面请求是用于生成链接预览还是普通用户访问。这样,你可以通过仅在必要时生成链接预览来优化页面加载时间。

如何安装它?

您可以通过composer安装此包

composer require brunoinds/link-preview-detector

如何使用它?

方法1:自动识别

这种方法会自动捕获请求来源和用户代理,并检测是否为链接预览。

use Brunoinds\LinkPreviewDetector\LinkPreviewDetector;

$response = LinkPreviewDetector::isForLinkPreview();
//returns a boolean (true/false). If it is true, it means the request is coming from a link preview crawler.

方法2:手动识别

使用这种方法,你可以传递特定的User-Agent,并判断是否为链接预览爬虫

use Brunoinds\LinkPreviewDetector\LinkPreviewDetector;

$userAgent = $_SERVER['HTTP_USER_AGENT'];

$response = LinkPreviewDetector::isForLinkPreviewUserAgent($userAgent);

如何实现它(示例)

以下示例表明你只能在需要时发送元数据。

use Brunoinds\LinkPreviewDetector\LinkPreviewDetector;
$isForLinkPreview = LinkPreviewDetector::isForLinkPreview();

if ($isForLinkPreview)
{
  echo '<meta property="og:title" content="Your Website Title" />';
  echo '<meta property="og:description" content="Your Website Description" />';
  echo '<meta property="og:image" content="URL to the image" />';
  echo '<meta property="og:url" content="URL to your website" />';
}

这个库的一个关键优势是,它允许你根据请求类型优化服务器的响应。当一个请求专门用于生成链接预览时,你不需要发送整个网页内容。相反,你可以只发送生成链接预览所需的元数据。这意味着你可以避免发送不必要的如JavaScript文件、图片和其他HTML内容的数据。这可以显著提高服务器性能和链接预览生成速度。以下是如何使用此库实现这一点的示例

use Brunoinds\LinkPreviewDetector\LinkPreviewDetector;

$isForLinkPreview = LinkPreviewDetector::isForLinkPreview();

if ($isForLinkPreview) {
  // Send only the meta-data required for link preview
  echo '<meta property="og:title" content="Your Website Title" />';

} else {
  // Send the entire webpage
   echo '
    <!DOCTYPE html>
    <html>
      <head>
        <title>Your Website Title</title>
        <script src="your-script.js"></script>
      </head>
      <body>
        <h1>Welcome to My Website</h1>
        <p>This is a sample paragraph.</p>
      </body>
    </html>';
}