|
|
 |
XII. Funzioni CURL, Client URL LibraryIntroduzione
PHP supporta libcurl, una libreria creata da Daniel Stenberg, che
permette di collegarsi e comunicare con parecchi tipi di
server e con parecchi tipi di protocolli. Libcurl al momento
supporta i protocolli http, https, ftp, gopher, telnet, dict, file, e
ldap. libcurl supporta anche i certificati HTTPS, HTTP
POST, HTTP PUT, l'upload via FTP (questo può essere ottenuto anche con l'estensione
ftp di PHP), upload attraverso una form HTTP, proxy, cookie e
autenticazione con utente e password.
Queste funzioni sono state aggiunte in PHP 4.0.2.
Requisiti
Per utilizzare le funzioni CURL occorre installare il pacchetto CURL. PHP richiede che si usi
CURL 7.0.2-beta o successivi. PHP non funzionerà con alcuna versione di
CURL antecedente alla 7.0.2-beta. Dalla versione 4.2.3 di PHP è necessario usare
CURL versione 7.9.0 o successiva. Con PHP 4.3.0 occorre avere CURL 7.9.8 o successive.
PHP 5.0.0 molto probabilmente richiederà CURL 7.10.5 o successiva.
Installazione
Al fine di utilizzare il supporto CURL occorre anche compilare PHP con --with-curl[=DIR] dove DIR è il
percorso della directory che contiene le directory lib e
include. Nella directory "include" ci dovrebbe essere una cartella
chiamata "curl" che dovrebbe contenere i file easy.h e
curl.h. Ci dovrebbe essere un file chiamato
libcurl.a nella directory "lib". A cominciare da
PHP 4.3.0 si può configurare PHP all'uso di CURL per gli url stream
--with-curlwrappers.
Nota agli utenti Win32:
Per abilitare questo modulo in ambiente Windows, occorre copiare
libeay32.dll e ssleay32.dll
dalla cartella delle DLL del pacchetto PHP/Win32 nella cartella
SYSTEM32 della propria macchina Windows. (Es: C:\WINNT\SYSTEM32
o C:\WINDOWS\SYSTEM)
Costanti predefinite
Queste costanti sono definite da questa estensione e
sono disponibili solo se l'estensione è stata compilata
nel PHP o se è stata caricata dinamicamente a runtime.
Esempi
Una volta compilato PHP con supporto CURL, si possono usare
le funzioni CURL. L'idea di fondo che sta dietro le funzioni CURL è:
si inizializza una sessione CURL usando
curl_init(), si impostano le
opzioni per il trasferimento tramite curl_setopt(),
si esegue la sessione usando
curl_exec() e quindi si termina la sessione con
curl_close().
Qui di seguito si trova un esempio che fa uso delle funzioni CURL per
scaricare la homepage del sito example.com e metterla in un file:
Esempio 1. Usare il modulo CURL di PHP per scaricare la homepage di example.com |
<?php
$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
|
|
add a note
User Contributed Notes
Funzioni CURL, Client URL Library
setec at freemail dot it
23-Apr-2004 06:23
Hi, I spent half a day to get it out, it isn't well documented.
If you want to use the same cURL session to make a POST request and then a GET request you need to use the CURLOPT_HTTPGET option, otherwise cURL will continue to execute a POST request. Sample code follows.
<?php
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
?>
a_zazello at yahoo dot com
15-Apr-2004 01:23
If I want to use CURLOPT_COOKIEFILE and CURLOPT_POSTFIELDS in the same request.
The post fields are not inserted in the HTTP header as I expected!
$url = "http://www.url.com";
$data = "key1=val1&key2=val2";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cook");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch); // run the whole process
curl_close($ch);
echo $result;
PHP 4.3.3 libcurl/7.10.5
simon [at] vhostdirect [dot] co [dot] uk
03-Mar-2004 10:53
It took me quite some to to figure out how to get Curl (with SSL), OpenSSL and PHP to play nicely together.
After reinstalling MS-VC7 and compiling OpenSSL to finally realise this was'nt nesscary.
If your like me and like *Nix systems more than Windows then you'll most probly have similar problems.
I came across this, on a simple google with the right keywords.
http://www.tonyspencer.com/journal/00000037.htm
I read thru that and found my mistake.
Its just a small list of notes, I found them to be the best I've found on the subject and the most simplist.
Dont forget to add a simple line like this into your scripts to get them working on Win32.
<?php
if($WINDIR) curl_setopt($curl, CURLOPT_CAINFO, "c:\\windows\\ca-bundle.crt");
?>
Last note: ca-bundle.crt file is located in the Curl download. I stored mine in the windows directory and apache/php can access it fine.
All the best and I hope this helps.
Simon Lightfoot
vHost Direct Limited
hraefn at hraefn dot net
03-Feb-2004 07:15
You can request (and have deflated for you) compressed http (from mod_gzip or ob_gzhandler, for instance) by using the following:
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
This seems to work fine with the latest php (4.3.4) curl (7.11.0) and zlib (1.1.4) under linux. This is much more elegant than forcing the Accept-Encode header and using gzdeflate on an edited result.
mmm at turkmenweb dot com
15-Dec-2003 10:49
I know that many people suffer from cURL when trying to send XML data. I solved this problem and want to share it with you:
I was trying to send SMS messages with a SMS service provider. They gave me the following ASP code, where you send data as XML and receive a response in XML as well:
url = "http://...someaddress/somefile.asp";
xmldata ="<XMLtag1>many other tags, data here</XMLtag1>";
Set ob = Server.CreateObject("Msxml2.XMLHTTP")
ob.Open "POST",url,false
ob.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
ob.Send xmldata
...then recieve code was here...
This is done in PHP using cURL library in this way:
<?php
$XPost = "<XMLcontent>sameas above</XMLcontent>"
$url = "..same URL as above..";
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT, 4); curl_setopt($ch, CURLOPT_POSTFIELDS, $XPost); $result = curl_exec($ch); echo $result; ?>
Some say that you should use CURLOPT_CUSTOMREQUEST, CURLOPT_HTTPHEADER and etc. to perform this task , as you can see you don't need those at all.
Hope it will help those who tries to simulate Msxml2.XMLHTTP or simply try sending XML data over PHP.
Regards,
Muhammed Mamedov
rodneywa at yahoo dot com
24-Oct-2003 07:47
Here's how I was able to post arrays using Curl:
$array_of_vars[]="var1";
$array_of_vars[]="var2";
$array_of_vars[]="var3";
$array_of_vars[]="var4";
$submit_url = "http://www.example.com/reads_post.php";
$formvars["feild1"] = "feild1";
for ($i=0;$i<sizeof($array_of_vars);$i++)
$formvars["array_of_vars[$i]"] = $dna[$i];
// init curl handle
$ch = curl_init($submit_url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $formvars);
// perform post
$rr=curl_exec($ch);
echo $rr;
curl_close($ch);
da at canaan dot co dot il
08-Oct-2003 01:42
i had problems with receiving all of the data that was replied to me about a transaction, atlast after way too much time spent i found out that all i missed was:
curl_setopt($ch, CURLOPT_HEADER, 1);
hope it helped anyone
alwong at 123infosys dot com
21-Sep-2003 01:35
The following scripts show how to post form to a web server via https. I modified rodrigo posting because it did not work for me on IIS5.
<?php
$url = 'https://www.yourserver.com/yourrequest;
$params = "name=your_name&email=youremail@mail.com";
$user_agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // this line makes it work under https
$result=curl_exec ($ch);
curl_close ($ch);
echo("Results: <br>".$result);
?>
rodrigo dot nakahodo at dhweb dot com dot br
18-Sep-2003 06:57
The script shows how to get a simple response of a SSL Server. Enjoy it!
<?php
$defined_vars = get_defined_vars();
$_url = 'https://www.example.com.br';
$_VAR001 = 'nono';
$_VAR002 = 'nonono';
$params = "VAR001=$_VAR001&VAR002=$_VAR002&";
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
curl_setopt($ch, CURLOPT_URL,$_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);
echo("Output: ".$result);
?>
helvecio_oliveira at yahoo dot com dot br
21-Aug-2003 03:12
CURL install steps in Mandrake 9.1:
==========================================================
cp -r /usr/src/php-devel/extensions/curl /tmp/curl
cd /tmp/curl
phpize
./configure
make install
echo "extension = curl.so" > /etc/php/90_curl.ini
Restart apache web server.
==========================================================
curl.so is in:
/usr/lib/php/extensions/
look in phpinfo, the string:
/etc/php/90_curl.ini
Needs these tools:
autoconf
automake
libtool
m4
php430-devel-430-11mdk.rpm
Some docs:
/usr/share/doc/php430-devel-430/SELF-CONTAINED-EXTENSIONS
eric at imap dot ch
07-Jul-2003 03:38
I managed to use curl to retrieve information from severs on ports other than 80 or 443 (for https) on some installations but not on all.
If you get an "CURLE_COULDNT_CONNECT /* 7 */" error, try adding the port : (for example)
curl_setopt($ch, CURLOPT_PORT, $_SERVER['SERVER_PORT']);
php at mechintosh dot com
03-Jul-2003 02:51
IMHO the example code is somewhat confusing; the fopen() and fclose() are not needed at all, AFAICT.
By default the resulting data/page of the external server is just printed out. To assign the result of the curl session to a variable, one can use
- output buffering (see ob_start(), ob_get_contents())
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
With the latter, the result of curl_exec is the actual data instead of a boolean.
sorin
09-Apr-2003 07:44
function curl_string ($url,$user_agent,$proxy){
$ch = curl_init();
curl_setopt ($ch, CURLOPT_PROXY, $proxy);
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt ($ch, CURLOPT_COOKIEJAR, "c:\cookie.txt");
curl_setopt ($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_TIMEOUT, 120);
$result = curl_exec ($ch);
curl_close($ch);
return $result;
}
$url_page = "http://www.google.com/";
$user_agent = "Mozilla/4.0";
$proxy = "http://208.25.243.167:8080";
$string = curl_string($url_page,$user_agent,$proxy);
echo $string;
this could hep someone
Sorin
thomas at NOSPAM dot gutschke dot com
07-Apr-2003 11:00
Here's a little code snippet if you need the last-modified-time for a remote file as filemtime() does not work on those. :)
$modified = "";
function read_header($ch, $header)
{
global $modified;
$length = strlen($header);
if(strstr($header, "Last-Modified:"))
{
$modified = substr($header, 15);
}
return $length;
}
function last_mod($remote_file)
{
global $modified;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $remote_file);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
$headers = curl_exec ($ch);
curl_close ($ch);
return $modified;
}
use something like
echo strtotime(last_mod("http://www.php.net/"));
to get the time as an Unix timestamp or
echo last_mod("http://www.php.net/");
to get the gmdate()-like time.
dweingart at pobox dot com
02-Apr-2003 10:08
If you want to Curl to follow redirects and you would also like Curl to echo back any cookies that are set in the process, use this:
curl_setopt($ch, CURLOPT_COOKIEJAR, '-');
'-' means stdout
-dw
diana dot castillo at nvtechnologies dot com
25-Mar-2003 04:30
bharris at spro dot net
25-Feb-2003 10:58
For Win2000: To get the 4.3.1 curl dll to work with https you now need to download the latest win32 curl library from http://curl.haxx.se and snag the ca-bundle.crt file from the lib directory. Place this somewhere handy on your webserver.
Then in your PHP script, add the following setopt line to the rest of your curl_setopt commands:
curl_setopt($ch, CURLOPT_CAFILE, 'C:\pathto\ca-bundle.crt')
This worked for me and allowed me to discontinue using the CURLOPT_SSL_VERIFYPEER set to zero hack.
retro at nospam dot enx dot org
11-Jan-2003 11:42
When using cURL to do posts, make sure you actually specify the CURLOPT_POSTFIELDS option. Not doing so seems to make PHP core (and apache as well if you're running it through there).
asi at neo dot ee
13-Dec-2002 01:28
If anybody has problems with getting new curl working with older version of php then ...
I got stuck with installing curl-7.10.2+php 4.0.6 or better said configuring PHP with mentioned version of curl.
After some hopeless attempts to configure curl support into PHP I saw an error message:
"checking for cURL greater than or equal to 7.8... ./configure: line 11725: test: 070a02: integer expression expected"
after which configure said: "configure: error: cURL version 7.8 or later is required to compile php with cURL support"
On the mentioned line "test" is used to compare verion from curl-sonfig with preset value 70800 but ... test expects both values to be integer. From verson 7.8 curl outputs its version in hex...
I did'nt had the time to think about fixing this - I just deleted lines responsible and got curl working :)
jerome at blaster dot dyndns dot org
10-Oct-2002 01:23
I wanted to import an https Web pages thanks to fopen("https://xxx", "r") or fsockopen but as far as I read, it was only possible with cURL extension (to get these functions worked with https, we have to wait the PHP 4.3 release, TBC) , so I installed it and it worked. It is quite easy, but I spend to much time on it:
First of all, here is the most important: WE DON'T NEED to compile anything to get curl worked. All the extensions that we need are already in the PHP 4.2.3 zip. So here are the instructions and links to get Apache + PHP + CURL work properly:
Downloads:
=> Apache Web server with Openssl included:
http://www.modssl.org/contrib/ftp/contrib/ Apache_1.3.26-Mod_SSL_2.8.9-OpenSSL_0.9.6d-WIN32.zip
=> PHP 4.2.3 for Windows:
http://www.php.net/get_download.php?df=php-4.2.3-Win32.zip
=> Optional: Openssl zip to get libeay32.dll and ssleay32.dll (I didn't need them because I used those stored in PHP zip)
http://www.modssl.org/contrib/ftp/contrib/ OpenSSL-0.9.6d-win32_RAR3_Archive_.rar
Installs:
=> Unzip Apache in Program Files folder(there should be no problem with the blank in the path):
=> Follow those instructions: http://tud.at/programm/apache-ssl-win32-howto.php3 . I didn't exactly do what they wrote but it helped a lot. I created the test certificat thanks to this link in order to test my Apache server with SSL.
=> Configure httpd (easy to find on the Web) and test Apache before going on, it avoids problems.
I just changed the Port from 80 (http) to 443 (https) in httpd, I only wanted to perform https.
I didn't try to get the both working together.
=> Unzip PHP in C:\Php path (don't install it in Program Files folder, you would have troubles because of the blank this time...)
=> Configure PHP : http://www.php.net/manual/en/install.windows.php #install.windows.manual
WARNING: php.ini MUST be stored into the c:\winnt folder and the dlls must be stored into the c:\winnt\system32 folder.
=> Test it with Apache and phpinfo() function.
cURL:
To add cURL extension, YOU DON'T NEED to compile anything.
All the extensions that you need are in the C:\php\extensions folder. To add cURL or any other extensions:
=> Have the libeay32.dll and ssleay32.dll in the system32 folder (already done if you installed PHP)
=> Copy all dlls from php/dll/ folder to winnt/system32/ (libeay32.dll and ssleay32.dll are already there if you followed
the previous steps)
=> Remove the ";" in front of extension=php_curl.dll in php.ini.
Those instructions come from: http://www.php.net/manual/en/install.windows.php #install.windows.extensions
And it should work, just test it with curl functions into your php script.
hamannDOTw at tDOTonline dot de
02-Jul-2002 03:18
Using the customrequest for a complete post is wrong. Libcurl will add a partial url, the http version and the standard headers after the post data - while this works with a non-persistent connection and an apache web server, it may fail under different conditions
smclean at scoreinfo dot tv
22-Jun-2002 12:46
marco dot mcc at inwind dot it
27-May-2001 05:50
If you want to write your entire HTTP request without use any other CURL functions like CURLOPT_POST specify it within a curl_setopt ($ch,CURLOPT_CUSTOMREQUEST , $req) line;
Where $req looks like (let me imagine a POST request...):
POST /destination/script HTTP/1.1
Content-length: xxx
Content-type: text/xml
host: yourhost
accept: */*
accept-encoding: gzip, deflate
accept-language: en-us
connection: close; Keep-Alive
...
your POST data
...
CURLOPT_CUSTOMREQUEST is not documented?!? but it's useful and amazing!
marcomcc (Roma)
dan dot polansky at seznam dot cz
17-Jan-2001 08:31
I used to download www pages to my script and one of the pages was different in MS explorer and different, when I downloaded it. Namely, information, I was really interested in was missing. That was because the server on the other bank of the river was looking at who is downloading the page. Everything got fixed when I pretended I was MSIE. It is done with curl. Here is a function, that you may use in similar situation
function download_pretending($url,$user_agent) {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($ch);
curl_close ($ch);
return $result;
}
| |