如果客户登录,WordPress -服务图像


WordPress - serving images if customer is logged in

我有一份杂志要在网上提供给那些买了它的人。我需要在<img src="...">中使用某种serve-image.php?img=page1.jpg,它将从公众无法访问的目录中提取图像。这部分解决了。没有弄清楚的是,如果用户登录到WordPress(并购买了这个东西),我如何从这个serve-image.php文件检查。我需要为此创建一些简单的API吗?是不是有什么我没想起来的?

谢谢你的回答!

我建议以下方法:

在受保护的图像文件夹中创建一个.htaccess文件,该文件将所有调用重定向到索引,并使用请求的图像路径(您可能使用相对路径)作为参数serve_image:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index'.php$ - [L]
RewriteRule (.*) /index.php?serve_image=$1 [L]
</IfModule>
Options All -Indexes
IndexIgnore *

然后,在您的插件或functions.php中通过将其连接到parse_request动作来包含访问检查(这是您将在serve-image.php -文件中使用的代码):

add_action('parse_request', 'check_file_access');
// function to check access and serve image
function check_file_access() {
    if(!isset($_GET['serve_image')){
        return false;
    }
    // Check access
    if(!is_user_logged_in()){
        die('Sorry! No access!');
    }
    // sanitize here (only allow paths that are inside your specified folder)
    $image_path = $_GET["serve_image"];
    // get content type
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $content_type = finfo_file($finfo, $image_path);
    finfo_close($finfo);
    // construct file name
    $filename = basename($image_path,'.'.$finfo['extension']);
    header('Content-type: '.$content_type);
    header("Content-Disposition: attachment; filename=".$filename);
    readfile($image_path);
    exit();
}

现在,如果您想要显示一个受保护的图像,您可以简单地使用src属性中的图像的常规路径。对于没有访问权限的用户,将拒绝该图像源。