欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

php访问带基本认证的页面

程序员文章站 2022-07-15 11:49:38
...
$host = '192.168.2.1'; //主机
$path = '/status.htm'; //路径
$user = 'admin'; //用户名
$pass = 'admin'; //密码
$queryString = '?a=1&b=2'; //query字串

//方法一,使用fsockopen
$authorizationToken = base64_encode("{$user}:{$pass}"); 
$fp = fsockopen('tcp://' . $host, 80, $errorNo, $errorMsg, 45);
//$fp = fsockopen('ssl://' . $host, 443, $errorNo, $errorMsg, 45); 
if (!$fp) {
    echo 'error: ', $errorNo, ' ', $errorMsg;
}
else {
    $header  = "GET {$path}{$queryString} HTTP/1.1\r\n";
    $header .= "Host: {$host}\r\n";
    //$header .= "User-Agent: {$_SERVER['HTTP_USER_AGENT']}\r\n";
    $header .= "Authorization: Basic {$authorizationToken}\r\n"; //认证
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-length: " . strlen($queryString) . "\r\n";
    $header .= "Connection: Close\r\n\r\n";
        
    fwrite($fp, $header);
    $return = '';
    while (!feof($fp)) {
        $return .= fgets($fp, 4096);
    }
    fclose($fp);
    echo $return;
}

//方法二,使用curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://{$host}{$path}{$queryString}");
curl_setopt($ch, CURLOPT_PORT, 443); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 15); 
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_USERPWD, "{$user}:{$pass}");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

$return = curl_exec($ch);
if (!$return) {
    echo curl_error($ch);
}
else {
    echo $return;
}
curl_close($ch);