尝试使用 file_get_contents 访问 WP 自定义端点时出现 401 错误

问题描述 投票:0回答:1

我已经设置了一个自定义端点:

function xyz_property_api_route() {
    register_rest_route('xyz/v1', 'property/(?P<slug>[a-zA-Z0-9-]+)', array(
        'methods' => 'GET',
        'callback' => 'get_property_by_slug',
        'permission_callback' => '__return_true'
    ));
}

当我直接访问 URL 时,我会得到正确的 JSON 输出。

但是,我在非 WordPress 网站上有一个脚本,我需要访问该 URL,但收到以下错误:

( ! ) Warning: file_get_contents(http://my-site-here.com/wp-json/xyz/v1/property/property_slug): Failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized in my-script.php on line 8
Call Stack
#   Time    Memory  Function    Location
1   0.0015  422960  {main}( )   .../my-script.php:0
2   0.0015  423072  file_get_contents( $filename = 'hhttp://my-site-here.com/wp-json/xyz/v1/property/property_slug' )   .../my-script.php:8
API Request Failed

这是我的脚本:

<?php
    $property_slug = $_GET['property'];

    // Construct the API URL using the property slug
    $api_url = 'http://my-site-here.com/wp-json/xyz/v1/property/' . $property_slug;

    // Fetch data from the API
    $response = file_get_contents($api_url);

    if ($response !== false) {
        $data = json_decode($response, true);
        if (!empty($data)) {
            echo "GOT STUFF";
        } else {
            echo "NOT GOT STUFF";
        }
    } else {
        echo "API Request Failed";
    }
?>

对此有什么想法吗?

谢谢, 尼尔

wordpress rest file-get-contents wordpress-rest-api
1个回答
0
投票

如果您在该应用程序中尝试,Postman 将为您提供一个基本的 cURL

<?php
  $property_slug = $_GET['property'];

  // Construct the API URL using the property slug
  $api_url = 'http://my-site-here.com/wp-json/xyz/v1/property/' . $property_slug;
    
  $curl = curl_init();

  curl_setopt_array($curl, array(
    CURLOPT_URL => $api_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
  ));

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    $result = json_decode($response);
    echo '<pre>';
    print_r($result);
    echo '</pre>';
  }
?>

© www.soinside.com 2019 - 2024. All rights reserved.