Using get_headers with a proxy

冷暖自知 提交于 2019-12-06 03:47:13

问题


In order to check if an URL is an image, I use the PHP function get_headers. In normal conditions, it works very well.

But when I'm behind a proxy, it causes a timeout exception. I had the same problem with file_put_contents but I solved it by adding a context parameter. However, the get_headers function hasn't a similar argument.

Do you know how to do please ?


回答1:


Use stream_context_set_default function.

This blog post explains how to use it. Here is the code from that page.

<?php
// Edit the four values below
$PROXY_HOST = "proxy.example.com"; // Proxy server address
$PROXY_PORT = "1234";    // Proxy server port
$PROXY_USER = "LOGIN";    // Username
$PROXY_PASS = "PASSWORD";   // Password
// Username and Password are required only if your proxy server needs basic authentication

$auth = base64_encode("$PROXY_USER:$PROXY_PASS");
stream_context_set_default(
 array(
  'http' => array(
   'proxy' => "tcp://$PROXY_HOST:$PROXY_PORT",
   'request_fulluri' => true,
   'header' => "Proxy-Authorization: Basic $auth"
   // Remove the 'header' option if proxy authentication is not required
  )
 )
);

$url = "http://www.pirob.com/";

print_r( get_headers($url) );

echo file_get_contents($url);
?>


来源:https://stackoverflow.com/questions/17111112/using-get-headers-with-a-proxy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!