PHP 8.1.9 Released!

Ejemplos

Tabla de contenidos

add a note

User Contributed Notes 3 notes

up
121
cmnajs at gmail dot com
13 years ago
Following code returns the curl output as a string.

<?php
       
// create curl resource
       
$ch = curl_init();

       
// set url
       
curl_setopt($ch, CURLOPT_URL, "example.com");

       
//return the transfer as a string
       
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

       
// $output contains the output string
       
$output = curl_exec($ch);

       
// close curl resource to free up system resources
       
curl_close($ch);     
?>
up
-35
jlee8df at gmail dot com
14 years ago
Basic cURL file or page download with basic error trapping.

<?php

function cURLcheckBasicFunctions()
{
  if( !
function_exists("curl_init") &&
      !
function_exists("curl_setopt") &&
      !
function_exists("curl_exec") &&
      !
function_exists("curl_close") ) return false;
  else return
true;
}

/*
* Returns string status information.
* Can be changed to int or bool return types.
*/
function cURLdownload($url, $file)
{
  if( !
cURLcheckBasicFunctions() ) return "UNAVAILABLE: cURL Basic Functions";
 
$ch = curl_init();
  if(
$ch)
  {
   
$fp = fopen($file, "w");
    if(
$fp)
    {
      if( !
curl_setopt($ch, CURLOPT_URL, $url) )
      {
       
fclose($fp); // to match fopen()
       
curl_close($ch); // to match curl_init()
       
return "FAIL: curl_setopt(CURLOPT_URL)";
      }
      if( !
curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
      if( !
curl_setopt($ch, CURLOPT_HEADER, 0) ) return "FAIL: curl_setopt(CURLOPT_HEADER)";
      if( !
curl_exec($ch) ) return "FAIL: curl_exec()";
     
curl_close($ch);
     
fclose($fp);
      return
"SUCCESS: $file [$url]";
    }
    else return
"FAIL: fopen()";
  }
  else return
"FAIL: curl_init()";
}

// Download from 'example.com' to 'example.txt'
echo cURLdownload("http://www.example.com", "example.txt");

?>

- JLèé
up
-54
randearievilo at gmail dot com
14 years ago
This simple code work fine using libcurl versions before 7.18.x.

<?php
        $ch
= curl_init("www.example.com/curl.php?option=test");
       
curl_setopt($ch, CURLOPT_HEADER, 0);
       
curl_setopt($ch, CURLOPT_POST, 1);
       
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       
$output = curl_exec($ch);      
       
curl_close($ch);
        echo
$output;
?>

If you have some trouble (Ex.: Failed to open/read local data from file/application) using a similar code with libcurl 7.18.x, try to add the option curl_setopt($ch, CURLOPT_POSTFIELDS, "").

I think there was a change in the option CURLOPT_POST. Now, to use this option, it seems to be necessary to set the option CURLOPT_POSTFIELDS.
To Top