2012-05-31 2 views
3

Когда я запускаю этот скрипт (http://bizonbytes.com/miscellaneous/sharrre.php?url=https://bizonbytes.com & type = googlePlus):CURLOPT_FOLLOWLOCATION не может быть активирован, если safe_mode включен или open_basedir установлен в

<?php 
    //Sharrre by Julien Hany 
    $json = array('url'=>'','count'=>0); 
    $json['url'] = $_GET['url']; 
    $url = urlencode($_GET['url']); 
    $type = urlencode($_GET['type']); 

    if(filter_var($_GET['url'], FILTER_VALIDATE_URL)){ 
    if($type == 'googlePlus'){ //source http://www.helmutgranda.com/2011/11/01/get-a-url-google-count-via-php/ 
     $content = parse("https://plusone.google.com/u/0/_/+1/fastbutton?url=".$url."&count=true"); 

     $dom = new DOMDocument; 
     $dom->preserveWhiteSpace = false; 
     @$dom->loadHTML($content); 
     $domxpath = new DOMXPath($dom); 
     $newDom = new DOMDocument; 
     $newDom->formatOutput = true; 

     $filtered = $domxpath->query("//div[@id='aggregateCount']"); 
     $json['count'] = str_replace('>', '', $filtered->item(0)->nodeValue); 
    } 
    else if($type == 'stumbleupon'){ 
     $content = parse("http://www.stumbleupon.com/services/1.01/badge.getinfo?url=$url"); 

     $result = json_decode($content); 
     $json['count'] = $result->result->views; 
     if(!isset($json['count'])) $json['count'] = 0; 
    } 
    else if($type == 'pinterest'){ 
     $content = parse("http://api.pinterest.com/v1/urls/count.json?callback=&url=$url"); 

     $result = json_decode(str_replace(array('(', ')'), array('', ''), $content)); 
     $json['count'] = $result->count; 
     if(!isset($json['count'])) $json['count'] = 0; 
    } 
    } 
    echo str_replace('\\/','/',json_encode($json)); 

    function parse($encUrl){ 
    $options = array(
     CURLOPT_RETURNTRANSFER => true, // return web page 
     CURLOPT_HEADER => false, // don't return headers 
     CURLOPT_FOLLOWLOCATION => true, // follow redirects 
     CURLOPT_ENCODING => "", // handle all encodings 
     CURLOPT_USERAGENT => 'sharrre', // who am i 
     CURLOPT_AUTOREFERER => true, // set referer on redirect 
     CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect 
     CURLOPT_TIMEOUT => 10, // timeout on response 
     CURLOPT_MAXREDIRS => 3, // stop after 10 redirects 
     CURLOPT_SSL_VERIFYHOST => 0, 
     CURLOPT_SSL_VERIFYPEER => false, 
    ); 
    $ch = curl_init(); 

    $options[CURLOPT_URL] = $encUrl; 
    curl_setopt_array($ch, $options); 

    $content = curl_exec($ch); 
    $err = curl_errno($ch); 
    $errmsg = curl_error($ch); 

    curl_close($ch); 

    if ($errmsg != '' || $err != '') { 
     /*print_r($errmsg); 
     print_r($errmsg);*/ 
    } 
    return $content; 
    } 
?> 

я получаю следующее сообщение об ошибке:

Warning: curl_setopt_array() [function.curl-setopt-array]: CURLOPT_FOLLOWLOCATION cannot be activated when safe_mode is enabled or an open_basedir is set in C:\Inetpub\vhosts\bizonbytes.com\httpdocs\miscellaneous\sharrre.php on line 56 
{"url":"https://bizonbytes.com","count":""} 

Важные замечания

  • У меня нет опыта работы с PHP Я просто нужно запустить этот скрипт (sharrre.php)
  • Я смотреть на другом подобном случае, но могу выяснить проблему.
  • меня открыть окна/php.ini и убедились, что safe_mode = Off
  • I Обратите внимание, что open_basedir устанавливается так, open_basedir =
  • мне нужно добавить что-то в open_basedir ли?
  • Это ссылка на подробную информацию о установленной версии php. См http://bizonbytes.com/miscellaneous/test.php

Спасибо всем за вашу помощь в этом вопросе

+0

PHP может иметь несколько .ini файлов и различные уровни, на которых можно выполнить переопределение ини типа. Запустите 'phpinfo()' где-то внутри вашего скрипта, чтобы узнать, что такое фактические локальные настройки. –

+0

@MarcB, когда вы запускаете http://bizonbytes.com/misciety/test.php, вы получаете, я думаю, что информация. – Yannick

ответ

10

Пожалуйста, обратите внимание, что это предупреждение о безопасности. Используя cURL, веб-сайт может перенаправить скрипт на что-то вроде file:///etc/passwd и возиться с вещами. Чтобы предотвратить это, всякий раз, когда open_basedir установлен, cURL не следует за местоположениями. Вам нужно будет следовать за ними вручную и вручную проверить, безопасны ли все последующие местоположения.

This comment on php.net реализует пример реализации того, что:

function curl_exec_follow(/*resource*/ $ch, /*int*/ &$maxredirect = null) { 
    $mr = $maxredirect === null ? 5 : intval($maxredirect); 
    if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) { 
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0); 
     curl_setopt($ch, CURLOPT_MAXREDIRS, $mr); 
    } else { 
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); 
     if ($mr > 0) { 
      $newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); 

      $rch = curl_copy_handle($ch); 
      curl_setopt($rch, CURLOPT_HEADER, true); 
      curl_setopt($rch, CURLOPT_NOBODY, true); 
      curl_setopt($rch, CURLOPT_FORBID_REUSE, false); 
      curl_setopt($rch, CURLOPT_RETURNTRANSFER, true); 
      do { 
       curl_setopt($rch, CURLOPT_URL, $newurl); 
       $header = curl_exec($rch); 
       if (curl_errno($rch)) { 
        $code = 0; 
       } else { 
        $code = curl_getinfo($rch, CURLINFO_HTTP_CODE); 
        if ($code == 301 || $code == 302) { 
         preg_match('/Location:(.*?)\n/', $header, $matches); 
         $newurl = trim(array_pop($matches)); 
        } else { 
         $code = 0; 
        } 
       } 
      } while ($code && --$mr); 
      curl_close($rch); 
      if (!$mr) { 
       if ($maxredirect === null) { 
        trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING); 
       } else { 
        $maxredirect = 0; 
       } 
       return false; 
      } 
      curl_setopt($ch, CURLOPT_URL, $newurl); 
     } 
    } 
    return curl_exec($ch); 
} 
+0

Я не покупаю это как разумное решение. – chovy

+4

Я просто попробовал, и он отлично работает. Спасибо, что опубликовали его. –

+0

Я взял часть preg_match и аналогичную установку, которую я уже имел в своем коде для решения URL-адресов и работает как шарм :) – Michael

Смежные вопросы