dongli1920 2012-07-01 12:21
浏览 59
已采纳

检索跨域数据php

What I'd like to do is retrieve some data from wikipedia, with ajax. I left the client-side scripting for afterwards and tried retrieving some random content. I tried with the fopen() and fread() methods but it didn't work, and then I came around some article that had the code for internet-providers that used proxies. Since it's my case I tried the code below but it didn't give any response.

<?php
$opts = array('http' => array('proxy' => 'tcp://10.10.10.101:8080', 'request_fulluri' => true));
$context = stream_context_create ($opts);
$data = file_get_contents('http://www.php.net', false, $context);   
echo $data;
?>

Ok so I tried the code suggested, with the proper proxy values:

<?php


$url = 'http://www.php.net';
$proxy = '10.10.10.101:8080';
//$proxyauth = 'user:password';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);

echo $curl_scraped_page;

But it gives me this error: HTTP/1.0 403 Forbidden Date: Mon, 02 Jul 2012 09:41:20 GMT Server: Apache Content-Type: text/plain Destination host forbidden

I don't get why it doesn't work, and how I could solve the problem.

  • 写回答

2条回答 默认 最新

  • dongzhiqi0332 2012-07-01 12:37
    关注

    it's not really a cross domain problem because you are loading the data from the server not the browser.

    To load a web page from PHP via a proxy - it's best to use cURL (a PHP http client: http://php.net/manual/en/book.curl.php).

    Here is an example - it is taken from a similar question (http://stackoverflow.com/questions/5211887/how-to-use-curl-via-a-proxy):

    <?php
    
    
    $url = 'http://www.php.net';
    $proxy = '10.10.10.101:8080';
    //$proxyauth = 'user:password';
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_PROXY, $proxy);
    //curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    $curl_scraped_page = curl_exec($ch);
    curl_close($ch);
    
    echo $curl_scraped_page;
    

    If your proxy needs authentication - you can set the $proxyauth var...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?