Using get_headers with a proxy

2019-04-10 01:52发布

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条回答
Summer. ? 凉城
2楼-- · 2019-04-10 02:34

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);
?>
查看更多
登录 后发表回答