在PHP中使用curl加载Spotify URL时出现问题


Problems loading Spotify URL using curl in PHP

在我的localhost或我的服务器上运行时,我无法加载特定的外部页面。但是,如果我在浏览器中加载页面,它会加载,或者使用Postman,它会加载得很好。

我怎么能解决这个问题,Spotify是如何防止这种情况发生的?

我要加载的内容的URL是这个。

<?php
$url="https://embed.spotify.com/?uri=spotify:user:spotify:playlist:4hOKQuZbraPDIfaGbM3lKI";
$page = file_get_contents($url);
echo $page; //returns nothing
$page = get_data($url);
echo $page; //returns nothing with a http code of 0
$url="https://www.google.com";
$page = file_get_contents($url);
echo $page; //returns google
$page = get_data($url);
echo $page; //returns google with a http code of 200
/* gets the data from a URL */
function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $data = curl_exec($ch);
    echo curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $data;
}
?>

尝试设置CURLOPT_POSTFIELDS为true &CURLOPT_POSTFIELDS中的URL参数如下所示。注意URL的变化,因为参数现在在CURLOPT_POSTFIELDS中。我将参数设置为一个名为$post_fields的数组,因为我发现在调试时这样读更容易。

UPDATE: post参数不工作。但是将CURLOPT_SSL_VERIFYHOST设置为false以及CURLOPT_SSL_VERIFYPEER设置为false似乎对我来说是可行的。

这是我清理过的你的代码版本。删除您的测试&注释掉post参数的东西,我认为会帮助之前:

// Set the `url`.
$url="https://embed.spotify.com/?uri=spotify:user:spotify:playlist:4hOKQuZbraPDIfaGbM3lKI";
// Set the `post` fields.
$post_fields = array();
// $post_fields['uri'] = 'spotify:user:spotify:playlist:4hOKQuZbraPDIfaGbM3lKI';
// Set the `post` fields.
$page = get_data($url, $post_fields);
// Echo the output.
echo $page;
// Gets the data from a `url`.
function get_data($url, $post_fields) {
  $curl_timeout = 5;
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  // curl_setopt($ch, CURLOPT_POST, true);
  // curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_timeout);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  $data = curl_exec($ch);
  // echo curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  curl_close($ch);
  return $data;
}