如何让php程序通过代理服务器获取服务器无法直接访问的网页

phpfool 2005-11-24 10:53:12
类似ie里面那样设置一个代理服务器的ip和端口就能访问
...全文
2308 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
pakey 2010-06-09
  • 打赏
  • 举报
回复
学习了
phpfool 2005-11-24
  • 打赏
  • 举报
回复
多谢共享
xuzuning 2005-11-24
  • 打赏
  • 举报
回复
方法一 使用sock函数,这个方法无须加载任何扩展就可使用
<?php
//配置代理服务器
$proxy_host = "代理服务器域名或ip";
$proxy_port = "代理服务器端口";
//配置欲打开的网页
$url="http://bbs.yzvod.com/index.asp";//注意要加"http://"

//对路径的处理,如果前面没有/,就加一个
function slashUrl($url) {
if(!ereg("^/",$url)) {
return "/".$url;
}else {
return $url;
}
}
//对获得内容进行处理,去掉头部信息
function trimHeader($content){
$array=split("\n\r",$content,"2");
return trim($array["1"]);
}

function http_fopen($host,$port="80"){
global $proxy_host;
global $proxy_port;
if(empty($proxy_host)){
$conn_host = $host;
$conn_port = $port;
}else {
$conn_host = $proxy_host;
$conn_port = $proxy_port;
}
$path = slashurl($path);
$abs_url = $host;
//$abs_url="http://".$host.":".$port.$path;
$query = "GET $abs_url HTTP/1.0\r\n".
//"HOST:$host:$port\r\n".
"User-agent:PHP/class http 0.1\r\n".
"\r\n";
$fp = fsockopen($conn_host,$conn_port);
if(!$fp){
return false;
}else{
fputs($fp,$query);
while(!feof($fp)) {
$cc .= fgets($fp);
}
fclose($fp);
$content=trimHeader($cc);
return $content;
}
}

//前面是主机地址,第二个参数是具体的目标
$http = http_fopen($url);
if(!$http){
echo"对不起,连接代理服务器出错!";
exit;
}else {
echo $http;
}


?>

方法二 这个方法需要加载curl扩展
<?php
// create a new curl resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_PROXY, "代理服务器地址:端口");
curl_setopt($ch, CURLOPT_URL, "http://www.phpx.com/happy/frm4.html");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);

echo curl_error ($ch);
// close curl resource, and free up system resources
curl_close($ch);
?>

blueonly 2005-11-24
  • 打赏
  • 举报
回复
up

21,891

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧