Ver Mensaje Individual
  #7 (permalink)  
Antiguo 04/08/2009, 12:16
Avatar de abimaelrc
abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 10 meses
Puntos: 1517
Respuesta: [APORTE] file_get_contents(), cURL, HTTP_Request

Para ver el estatus de algún sitio, con file_get_contents hay una variable que sostiene la información de la cabecera $http_response_header
Código PHP:
Ver original
  1. <?php
  2. file_get_contents("http://forosdelweb.com/");
  3. var_dump($http_response_header);
El problema de esta forma es que file_get_contents, tiene que cargar toda la página y una vez cargada la variable te dará la información. Puedes indicar límites a la descarga indicando el cuarto y quinto parametro que no pase información de la página o lea por ejemplo un solo caracter.
Código PHP:
Ver original
  1. <?php
  2. //ningún caracter pasa
  3. file_get_contents("http://forosdelweb.com/",null,null,0,0);
  4. var_dump($http_response_header);
  5.  
  6. //pasa solamente el primer caracter
  7. file_get_contents("http://forosdelweb.com/",null,null,0,1);
  8. var_dump($http_response_header);
Pero hay una forma más sencilla de lograr ver la cabecera y es usando get_headers.
Código PHP:
Ver original
  1. <?php
  2. var_dump(get_headers('http://forosdelweb.com/',1));
  3.  
  4. //Este sería la forma de verificar si una página está funcionando o no
  5. $getHeader = get_headers('http://forosdelweb.com/',1);
  6. echo $getHeader[0];

También cURL puede ver los estatus de los sitios web. Para este código verificaremos el estatus de los enlaces. Es una buena forma para ver si los enlaces que hemos posteado en la pagina estan rotos o han sido movidos. Solo escribe el nombre en el navegador
http://localhost/nombre_de_este_arch...s_de_links.com No tiene que ser otra direccion puede ser hasta tus propios archivos.

Una vez que una página se haya cargado, el programa utiliza el XPath para obtener una lista de enlaces en la página. Entonces, después de un preprocesamiento busca cada uno de los vínculos, los enlace son recuperados. Debido a que sólo necesita las cabeceras de estas respuestas, no necesitamos usar el método de GET, esto lo hacemos con la opción CURLOPT_NOBODY. Al activar CURLOPT_HEADER le indica a curl_exec() que incluya en la respuesta la cabecera en la cadena que envia. Basado en la respuesta, el estatus del link es impreso a la misma vez con la nueva localidad si ha sido movido.

Código PHP:
Ver original
  1. <?php
  2. $url = $_GET['url'];
  3.  
  4. // Load the page
  5. list($page,$pageInfo) = load_with_curl($url);
  6.  
  7. if(!strlen($page)) die("No page retrieved from $url");
  8.  
  9. // Convert to XML for easy parsing
  10. $opts = array('output-xhtml' => true, 'numeric-entities' => true);
  11. $tidy = new tidy;
  12. $xml = $tidy->repairString($page,$opts);
  13.  
  14. $doc = new DOMDocument();
  15. $doc->loadXML($xml);
  16. $xpath = new DOMXPath($doc);
  17. $xpath->registerNamespace('xhtml','http://www.w3.org/1999/xhtml');
  18.  
  19. // Compute the Base URL for relative links
  20. $baseURL = '';
  21. // Check if there is a <base href=""/> in the page
  22. $nodeList = $xpath->query('//xhtml:base/@href');
  23. if ($nodeList->length == 1) {
  24.     $baseURL = $nodeList->item(0)->nodeValue;
  25. }
  26. // No <base href=""/>, so build the Base URL from $url
  27. else {
  28.     $URLParts = parse_url($pageInfo['url']);
  29.     if (! (isset($URLParts['path']) && strlen($URLParts['path']))) {
  30.         $basePath = '';
  31.     } else {
  32.         $basePath = preg_replace('#/[^/]*$#','',$URLParts['path']);
  33.     }
  34.     if (isset($URLParts['username']) || isset($URLParts['password'])) {
  35.         $auth = isset($URLParts['username']) ? $URLParts['username'] : '';
  36.         $auth .= ':';
  37.         $auth .= isset($URLParts['password']) ? $URLParts['password'] : '';
  38.         $auth .= '@';
  39.     } else {
  40.         $auth = '';
  41.     }
  42.     $baseURL = $URLParts['scheme'] . '://' .
  43.                $auth . $URLParts['host'] .
  44.                $basePath;
  45. }
  46.  
  47. // Keep track of the links we visit so we don't visit each more than once
  48. $seenLinks = array();
  49.  
  50. // Grab all links
  51. $links = $xpath->query('//xhtml:a/@href');
  52.  
  53. foreach ($links as $node) {
  54.     $link = $node->nodeValue;
  55.     // resolve relative links
  56.     if (! preg_match('#^(http|https|mailto):#', $link)) {
  57.         if (((strlen($link) == 0)) || ($link[0] != '/')) {
  58.             $link = '/' . $link;
  59.         }
  60.         $link = $baseURL . $link;
  61.     }
  62.     // Skip this link if we've seen it already
  63.     if (isset($seenLinks[$link])) {
  64.         continue;
  65.     }
  66.     // Mark this link as seen
  67.     $seenLinks[$link] = true;
  68.     // Print the link we're visiting
  69.     echo $link.': ';
  70.     flush();
  71.  
  72.     list($linkHeaders, $linkInfo) = load_with_curl($link, 'HEAD');
  73.     // Decide what to do based on the response code
  74.     // 2xx response codes mean the page is OK
  75.     if (($linkInfo['http_code'] >= 200) && ($linkInfo['http_code'] < 300)) {
  76.         $status = 'OK';
  77.     }
  78.     // 3xx response codes mean redirection
  79.     else if (($linkInfo['http_code'] >= 300) && ($linkInfo['http_code'] < 400)) {
  80.         $status = 'MOVED';
  81.         if (preg_match('/^Location: (.*)$/m',$linkHeaders,$match)) {
  82.                 $status .= ': ' . trim($match[1]);
  83.         }
  84.     }
  85.     // Other response codes mean errors
  86.     else {
  87.         $status = "ERROR: {$linkInfo['http_code']}";
  88.     }
  89.     // Print what we know about the link
  90.     echo "$status\n";
  91. }
  92.  
  93. function load_with_curl($url, $method = 'GET') {
  94.     $c = curl_init($url);
  95.     curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
  96.     if ($method == 'GET') {
  97.         curl_setopt($c,CURLOPT_FOLLOWLOCATION, true);
  98.     }
  99.     else if ($method == 'HEAD') {
  100.         curl_setopt($c, CURLOPT_NOBODY, true);
  101.         curl_setopt($c, CURLOPT_HEADER, true);
  102.     }
  103.     $response = curl_exec($c);
  104.     return array($response, curl_getinfo($c));
  105. }

Para hacer la petición usando un proxy puedes hacerlo con cURL de esta forma:
Código PHP:
Ver original
  1. <?php
  2. $url = 'http://www.google.com/';
  3. $ch = curl_init($url);
  4. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  5. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  6. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true);
  7. curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  8. curl_setopt($ch, CURLOPT_PROXY, 'ip:port');
  9. $page = curl_exec($ch);
  10.  
  11. $a = curl_getinfo($ch);
  12. print_r ($a);
  13.  
  14.  
  15. echo $page;
Este código fue tomado de este tema http://www.forosdelweb.com/f18/curl-...8/#post3784335

Para hacer la petición usando un proxy puedes hacerlo con fopen de esta forma:
Código PHP:
Ver original
  1. <?php
  2. $opts = array('http' => array('proxy' => 'tcp://127.0.0.1:8080', 'request_fulluri' => true));
  3. $context = stream_context_create($opts);
  4. $fp = fopen('http://www.example.com', 'r', false, $context);
Este código fue tomado de este tema http://www.forosdelweb.com/4147617-post93.html


IPN (Instant Payment Notification) Paypal y cURL
Para enviar a Paypal y verificar si es verdadero la transacción que haya hecho el usuario, usando el IPN (Instant Payment Notification)
Código PHP:
Ver original
  1. <?php
  2. // Choose url
  3. if(array_key_exists('test_ipn', $_POST) && 1 === (int) $_POST['test_ipn'])
  4.     $url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
  5. else
  6.     $url = 'https://www.paypal.com/cgi-bin/webscr';
  7.  
  8. // Set up request to PayPal
  9. $request = curl_init();
  10. (
  11.     CURLOPT_URL => $url,
  12.     CURLOPT_POST => TRUE,
  13.     CURLOPT_POSTFIELDS => http_build_query(array('cmd' => '_notify-validate') + $_POST),
  14.     CURLOPT_RETURNTRANSFER => TRUE,
  15.     CURLOPT_HEADER => FALSE,
  16.     CURLOPT_SSL_VERIFYPEER => TRUE,
  17.     CURLOPT_CAINFO => 'cacert.pem',
  18. ));
  19.  
  20. // Execute request and get response and status code
  21. $response = curl_exec($request);
  22. $status   = curl_getinfo($request, CURLINFO_HTTP_CODE);
  23.  
  24. // Close connection
  25. curl_close($request);
  26.  
  27.  
  28. if($status == 200 && $response == 'VERIFIED')
  29. {
  30.     $str = '';
  31.     foreach($_POST as $k => $v){
  32.         $str .= $k . ' => ' . $v . PHP_EOL;
  33.     }
  34.     file_put_contents('ipn.txt', $str);
  35. }
  36. else
  37. {
  38.     file_put_contents('ipn_error.txt', $response . PHP_EOL . $status);
  39. }
Para obtener el archivo cacert.pem deben ir a http://curl.haxx.se/docs/caextract.html y bajarlo o copiar y pegar el contenido a ese archivo con ese nombre y extensión. Lo deben colocar al lado del archivo que van a usar este código o a la ruta que hayan indicado.

Esta información la tomé de la siguiente página http://www.geekality.net/2011/05/28/...ification-ipn/
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos

Última edición por abimaelrc; 18/04/2012 a las 08:45