In response to rkirilow's post, where he said to set the option CURLOPT_FILE, that should really be CURLOPT_COOKIEFILE. I was bitten by this issue myself with code that previously worked for logging into a website and posting a form. However, at some point the code just stopped working, and I eventually found that I needed to set this option to /dev/null for it to work.
curl_setopt
(PHP 4 >= 4.0.2, PHP 5)
curl_setopt — Imposta una opzione per un trasferimento CURL
Descrizione
Imposta le opzioni per una sessione CURL identificata dal parametro ch . opzione specifica quale opzione impostare e valore specifica il valore per l'opzione data.
valore dovrebbe essere di tipo booleano per i seguenti valori del parametro opzione ):
| Option | Set value to | Notes |
|---|---|---|
| CURLOPT_BINARYTRANSFER | TRUE restituisce la riga di output quando CURLOPT_RETURNTRANSFER è usata. | |
| CURLOPT_CRLF | TRUE per convertire la Unix newlines in CRLF newlines per i trasferimenti. | |
| CURLOPT_DNS_USE_GLOBAL_CACHE | TRUE per usare una cache gobale DNS. Questa opzione non è thread-safe ed è abilitata per default. | |
| CURLOPT_FAILONERROR | TRUE per terminare in maniera silenziosa se il codice HTTP restituito è maggiore di 300. Il comportamento di default è di restituire la pagina normalmente, ignorando il codice. | |
| CURLOPT_FILETIME | TRUE per cercare di recuperare la data di modifica del documento remoto. Si può cercare di ripristinare questo valore usando l'opzione CURLINFO_FILETIME con curl_getinfo(). | |
| CURLOPT_FOLLOWLOCATION | TRUE per seguire una qualunque "Location: " intestazione inviata dal server come parte dell' header HTTP (notare che è ricorsiva, PHP seguirà come molte "Location: " intestazioni inviate, a meno che CURLOPT_MAXREDIRS sia impostata). | |
| CURLOPT_FORBID_REUSE | TRUE forza la chiusura esplicita della connessione quando ha finito il processo e non può essere riutilizzata. | |
| CURLOPT_FRESH_CONNECT | TRUE forza l'uso di una nuova connessione invece di usarne una in cache. | |
| CURLOPT_FTP_USE_EPRT | TRUE per usare EPRT (e LPRT) quando si opera un download FTP. Usa FALSE per disaibilitare EPRT e LPRT e usare PORT solamente. | |
| CURLOPT_FTP_USE_EPSV | TRUE prima cerca un comando EPSV per trasferimento FTP prima di ritornare alla modalità PASV. Imposta a FALSE per disabilitare EPSV. | |
| CURLOPT_FTPAPPEND | TRUE per accodare aò file remoto invece di sovrascriverlo. | |
| CURLOPT_FTPASCII | Un alias di CURLOPT_TRANSFERTEXT. Usarlo al suo posto. | |
| CURLOPT_FTPLISTONLY | TRUE per elencare solamente i nomi di una directory FTP. | |
| CURLOPT_HEADER | TRUE per includere l'intestazione in output. | |
| CURLOPT_HTTPGET | TRUE per resettare la richiesta HTTP col metodo GET. Dopo che GET è il default, diventa necessario solo se il metodo di richiesta è cambiato. | |
| CURLOPT_HTTPPROXYTUNNEL | TRUE per passare attraverso un proxy HTTP fornito. | |
| CURLOPT_MUTE | TRUE per essere totalemtne silenzioso nei riguardi di una funzione CURL. | |
| CURLOPT_NETRC | TRUE per condurre il file ~/.netrc a trovare username e password per il sito remoto col quale si stabilisce una connessione. | |
| CURLOPT_NOBODY | TRUE esclude il corpo dall'output. | |
| CURLOPT_NOPROGRESS |
TRUE per disabilitare il progress meter per trasferimetni CURL.
|
|
| CURLOPT_NOSIGNAL | TRUE per ignorare qualunque funzione CURL che causa l'invio di un segnale a un processo PHP. Ciò è settato come default con le multi-threaded SAPI in modo che le opzioni di timeout possano essere ancora usate. | Aggiunto in CURL 7.10. |
| CURLOPT_POST | TRUE per compiere un regolare HTTP POST. Questo POST è il tipo normale di application/x-www-form-urlencoded, più comunemente usata dai form HTML. | |
| CURLOPT_PUT | TRUE per HTTP PUT un file. Il file da PUT deve essere impostato con CURLOPT_INFILE e CURLOPT_INFILESIZE. | |
| CURLOPT_RETURNTRANSFER | TRUE per restituire il trasferimento come una stringa del valore restituito di curl_exec() al posto di metterlo in output direttamente. | |
| CURLOPT_SSL_VERIFYPEER | FALSE per fermare CURL dal verificare i certificati dei peer. Un certificato alternativo di verificare può essere specificato con l'opzione CURLOPT_CAINFO o una directory certificata può essere specificata con l'opzione CURLOPT_CAPATH . CURLOPT_SSL_VERIFYHOST può anche dover essere messa TRUE o FALSE se CURLOPT_SSL_VERIFYPEER è disabilitata (il default è 2). | TRUE per default nel CURL 7.10. Default bundle installed as of CURL 7.10. |
| CURLOPT_TRANSFERTEXT | TRUE per usare la modalità ASCII per trasferimenti FTP. Per LDAP, riporta i dati in testo iano invece che in HTML. Sui sistemi Windows, non imposterà STDOUT alla modalità binaria. | |
| CURLOPT_UNRESTRICTED_AUTH | TRUE invia username e password quando le seguenti locazioni (che usano CURLOPT_FOLLOWLOCATION), anche quando l'hostname è cambiato. | |
| CURLOPT_UPLOAD | TRUE per preparare un upload. | |
| CURLOPT_VERBOSE | TRUE per inviare un'informazione di tipo verbose. Scrive l'output su STDERR, o sul file specificato usando CURLOPT_STDERR. |
value dovrebbe essere un intero per i seguenti valori del parametro option :
| Option | Set value to | Notes |
|---|---|---|
| CURLOPT_BUFFERSIZE | La dimensione del buffer da utilizzare per ogni lettura. Non è garantito che questa richiesta venga soddisfatta, comunque. | Aggiunto in CURL 7.10. |
| CURLOPT_CLOSEPOLICY | Anche CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST . Ci sono altri tre CURLCLOSEPOLICY_ costanti, ma CURL non li supporta ancora. | |
| CURLOPT_CONNECTTIMEOUT | Il numero di secondi da aspettare mentre si cerca di connettersi. Usare 0 per aspettare indefinitamente. | |
| CURLOPT_DNS_CACHE_TIMEOUT | Il numero di secondi con cui mantenere le istanze DNS in memoria. Questa opzio è posta a 120 (2 minuti) per default. | |
| CURLOPT_FTPSSLAUTH | Il metodo di autenticazione FTP (quando attivato): CURLFTPAUTH_SSL (cerca per primo SSL), CURLFTPAUTH_TLS (cerca per primo SSL), o CURLFTPAUTH_DEFAULT (lascia decidere a CURL). | Aggiunto in CURL 7.12.2 e disponibile da PHP 5.1.0 |
| CURLOPT_HTTP_VERSION | CURL_HTTP_VERSION_NONE (default, lascia decidere CURL quale versione usare), CURL_HTTP_VERSION_1_0 (forza HTTP/1.0), o CURL_HTTP_VERSION_1_1 (forza HTTP/1.1). | |
| CURLOPT_HTTPAUTH |
Il metodo(i) di autenticazione HTTP da usare. Le opzioni sono: CURLAUTH_BASIC , CURLAUTH_DIGEST , CURLAUTH_GSSNEGOTIATE , CURLAUTH_NTLM , CURLAUTH_ANY , e CURLAUTH_ANYSAFE . Si può usre l'operatore binario | (or) per combinare più di un metodo. In questo caso, CURL testerà il server per vedere quali metodi esso supporta e sceglierà il migliore. CURLAUTH_ANY è un alias per CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM. CURLAUTH_ANYSAFE è un alias per CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM. |
|
| CURLOPT_INFILESIZE | La grandezza attesa, in bytes, del file quando si invia (upload) un file a un sito remoto. | |
| CURLOPT_LOW_SPEED_LIMIT | La velocità di trasferimento, in bytes al secondo, in cui la trasmissione dovrebbe stare al di sotto durante CURLOPT_LOW_SPEED_TIME secondi affinchè PHP to consideri la trasmissione troppo lenta e la abortisca. | |
| CURLOPT_LOW_SPEED_TIME | Il numero di secondi in cui il trasferimento dovrebbe stare al di sotto CURLOPT_LOW_SPEED_LIMIT in modo che PHP consideri la rasmisiosne troppo lenta e la abortisca. | |
| CURLOPT_MAXCONNECTS | L'ammontare massimo di connessioni persistenti consentite. Quando il limite è raggiunto, CURLOPT_CLOSEPOLICY viene usata per determinare quale connessione chiudere. | |
| CURLOPT_MAXREDIRS | L'ammontare massimo di redirezioni HTTP da seguire. Usare questa opzione insieme a CURLOPT_FOLLOWLOCATION. | |
| CURLOPT_PORT | Un numero di porta alternativo a cui connettersi. | |
| CURLOPT_PROXYAUTH | Il metodo di autenticazione HTTP da usare per la connessione al proxy. Usare la stessa bitmask come descritto in in CURLOPT_HTTPAUTH. Per l'autenticazione del proxy, solo CURLAUTH_BASIC e CURLAUTH_NTLM sono attualmente supportate. | Aggiunto in CURL 7.10.7 e PHP 5.1.0. |
| CURLOPT_PROXYPORT | Il numero di porta del proxy alla quale connettersi. Questo numero può essere anche impostato in CURLOPT_PROXY. | |
| CURLOPT_PROXYTYPE | Anche CURLPROXY_HTTP (default) o CURLPROXY_SOCKS5 . | Aggiunto in CURL 7.10. |
| CURLOPT_RESUME_FROM | L' offset, in byte, per ripristinare un trasferimento. | |
| CURLOPT_SSL_VERIFYHOST | 1 per verificare l'esistenza di un nome comune nel certificato SSL peer . 2 per verificare l'esistenza di un nome comune e verificare inoltre che soddisfi l'hostname fornito. | |
| CURLOPT_SSLVERSION | La versione SSL (2 or 3) da usare. Per default PHP cercherà di determinare ciò da se stesso, benchè in alcuni casi si possa impostarlo manualmente. | |
| CURLOPT_TIMECONDITION | Come CURLOPT_TIMEVALUE è trattato. Usare CURL_TIMECOND_IFMODSINCE per restituire la pagina solo se è stata mpdificata dalla data specificata in CURLOPT_TIMEVALUE. Se non è stata modificata, un "304 Not Modified" header sarà restituito assumendo che CURLOPT_HEADER è TRUE. Usare CURL_TIMECOND_ISUNMODSINCE per l'effetto opposto. CURL_TIMECOND_IFMODSINCE è il default. | Aggiunto in PHP 5.1.0. |
| CURLOPT_TIMEOUT | Il numero massimo di secondi per permettere alle funzioni CURL di essere eseguite. | |
| CURLOPT_TIMEVALUE | Il tempo in secondi dal 1 Gennaio 1970. Il tempo verrà usato da CURLOPT_TIMECONDITION. Per default, CURL_TIMECOND_IFMODSINCE è usato. |
value dovrebbe essere una stringa per i seguenti valori del parametro option :
| Option | Set value to | Notes |
|---|---|---|
| CURLOPT_CAINFO | Il nome di un file contenente uno o più certificati che verificano la parità. Ciò ha significato solo quando usato in combinazione con CURLOPT_SSL_VERIFYPEER. | |
| CURLOPT_CAPATH | Una directory che contiene certificati multipli CA. Usare questa opzione insieme a CURLOPT_SSL_VERIFYPEER. | |
| CURLOPT_COOKIE | The contents of the "Set-Cookie: " header to be used in the HTTP request. | |
| CURLOPT_COOKIEFILE | Il nome del file che contiene i dati del cookie. Il cookie può essere nel formato Netscape, o solo un semplice header HTTP-style allegato in un file. | |
| CURLOPT_COOKIEJAR | Il nome di un file in cui salvare tutti i cookie interni finchè la connessione termina. | |
| CURLOPT_CUSTOMREQUEST |
Un metodo custom di richiesta da usare al posto di
"GET" o "HEAD" quando avviene una
richiesta HTTP. Ciò è utile per un
"DELETE" o altro, in più nasconde le richieste HTTP.
Valori validi sono termini quali "GET",
"POST", "CONNECT" e così via;
i.e. Non inserire un'intera riga di richieste HTTP qui. Ad esempio,
scrivere "GET /index.html HTTP/1.0\r\n\r\n"
sarebbe errato.
|
|
| CURLOPT_EGBSOCKET | Come CURLOPT_RANDOM_FILE, ecetto un filename per un Entropy Gathering Daemon socket. | |
| CURLOPT_ENCODING | I contenuti di un' "Accept-Encoding: " header. Ciò abilita la decodifica della risposta. Termini supportati sono "identity", "deflate", e "gzip". Se viene impostata una stringa vuota, "", viene inviato un header contenente tutti i tipi di termini supportati. | |
| CURLOPT_FTPPORT | Il valore che verrà utilizzato per ottenere un indirizzo IP da usare per l'istruzione FTP "POST" . L'istruzione "POST" indica al server remoto il proprio indirizzo IP a cui connettersi. La stringa può essere un semplice indirizzo IP, un hostname, un nome di un'interfaccia di rete (sotto Unix), o un semplice '-' per usare l'indirizzo Ip del sistema di default. | |
| CURLOPT_INTERFACE | Il nome di un'interfaccia di rete di uscita da usare. Può essere il nome di un'interfaccia, un indirizzo IP o un host name. | |
| CURLOPT_KRB4LEVEL | Il livello di sicurezza KRB4 (Kerberos 4). Uno qualunque dei valori seguenti (in ordine dal meno al più significativo) sono validi: "clear", "safe", "confidential", "private".. Se la stringa non corrisponde a uno di questi, si usa "private". Impostando questa opzione a NULL disabilita la sicurezza KRB4. Attualmente la sicurezza KRB4 lavora solamente con transazioni FTP. | |
| CURLOPT_POSTFIELDS | I dati completi da mandare in post in un'operazione HTTP "POST" . | |
| CURLOPT_PROXY | Il proxy HTTP in cui veicolare le richieste. | |
| CURLOPT_PROXYUSERPWD | Username e password formattate come "[username]:[password]" da usare per la connessione al proxy. | |
| CURLOPT_RANDOM_FILE | IL nome del file da passare al generatore di numeri casuali per SSL. | |
| CURLOPT_RANGE | Intervallo(i) di dati da ricevere nel formato "X-Y" dove X o Y sono opzionali. I trasferimenti HTTP supportano inoltre svariati intervalli, separati da virgole nel formato "X-Y,N-M". | |
| CURLOPT_REFERER | Il contenuto dell'header "Referer: " da usare in una richiesta HTTP. | |
| CURLOPT_SSL_CIPHER_LIST | Elenco di cifre da usare con SSL. Per esempio, RC4-SHA e TLSv1 sono elenchi validi di cifre. | |
| CURLOPT_SSLCERT | Il nome di un file contenente un certificato PEM formattato. | |
| CURLOPT_SSLCERTPASSWD | La password richiesta per usare il CURLOPT_SSLCERT certificato. | |
| CURLOPT_SSLCERTTYPE | Il formato del certificato. Formati ammessi sono "PEM" (default), "DER", e "ENG". | Aggiunto in CURL 7.9.3. |
| CURLOPT_SSLENGINE | L' identificatore per il cripto-motore della chiave privata SSL specificata in CURLOPT_SSLKEY. | |
| CURLOPT_SSLENGINE_DEFAULT | L' identificatore per il motore crypto usato per cripto-operazioni asimmetriche. | |
| CURLOPT_SSLKEY | Il nome di un file contenente una chiave privata SSL. | |
| CURLOPT_SSLKEYPASSWD |
La password segreta necessaria per usare la chiave privata SSL specificata in
CURLOPT_SSLKEY.
|
|
| CURLOPT_SSLKEYTYPE | Il tipo di chiave della chiave privata SSL specificata in CURLOPT_SSLKEY. I tipi di chiavi supportate sono "PEM" (default), "DER", e "ENG". | |
| CURLOPT_URL | L' URL da raggiungere. E' possibnile impostarla quando si inizializza una sessione con curl_init(). | |
| CURLOPT_USERAGENT | I contenuti dell'header "User-Agent: " da usare in una richiesta HTTP. | |
| CURLOPT_USERPWD | Username e password formattate come "[username]:[password]" da usare per la connessione. |
value dovrebbe essere un array per i seguenti valori del parametro option :
| Option | Set value to | Notes |
|---|---|---|
| CURLOPT_HTTP200ALIASES | Un array di 200 risposte HTTP che saranno trattate come risposte valide e non come errori. | Aggiunto in CURL 7.10.3. |
| CURLOPT_HTTPHEADER | Un array di campi di header HTTP da impostare. | |
| CURLOPT_POSTQUOTE | Un array di comandi FTP da eseguire sul server dopo che la richiesta FTP è stata eseguita. | |
| CURLOPT_QUOTE | Un array di comandi FTP commands da eseguire sul server prima della richiesta FTP. |
value dovrebbe essere una risorsa di streaming (usando fopen(), per esempio) per i seguenti valori del parametro option :
| Option | Set value to | Notes |
|---|---|---|
| CURLOPT_FILE | Il file che il trasferimento dovrebbe scrivere. Il default è STDOUT (la finestra del browser). | |
| CURLOPT_INFILE | Il file ce il trasferimento dovrebbe leggere quando si fa un upload. | |
| CURLOPT_STDERR | Una locazione alternativa per gli errori di output al posto di STDERR. | |
| CURLOPT_WRITEHEADER | Il file su cui viene scritto l' header parte del trasferimento. |
value dovrebbe essere una stringa col nome di una funzione di callback valida per i seguenti valori del parametro option :
| Option | Set value to | Notes |
|---|---|---|
| CURLOPT_HEADERFUNCTION | Il nome della funzione di callback la quale prende due parametri. il primo è la risorsa CURL, il secondo è una stringa con i dati dell'header da scrivere. Usando questa funzione di callback, diventa propria la responsabilità di scrivere i dati di header. Restituisce il numero di bytes scritti. | |
| CURLOPT_PASSWDFUNCTION | Il nome della funzione di callback che prende tre parametri. Il primo è la risorsa CURL, il secondo è una stringa contenente la richiesta di password e il terzo è la lunghezza massima della password. Restituisce la stringa che contiene la password. | |
| CURLOPT_READFUNCTION | Il nome della funzione di callback che prende due parametri. Il primo è la risorsa CURL, e il secondo è una stringa con i dati da leggere. Usindo questa funzione di callback, diventa propria la responsabilità di leggere i dati. Restituisce il numero di bytes letti. Restituisce 0 per un segnale di EOF. | |
| CURLOPT_WRITEFUNCTION | Il nome della funzione di callback che prende due parametri. Il primo è la risorsa CURL, e il secondo è una stringa con i dati da scrivere. Usindo questa funzione di callback, diventa propria la responsabilità di scrivere i dati. Deve restituire l'esatto numero di bytes scritti altrimenti fallisce. |
Example #1 Inizializza una sessione CURL nuova e carica una pagina web
<?php
// crea una nuova risorsa CURL
$ch = curl_init();
// imposta l'URL e altre opzioni spedifiche
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// carica l' URL e la passa al browser
curl_exec($ch);
// chiude la risorsa CURL e rilascia le risorse di sistema
curl_close($ch);
?>
curl_setopt
26-Sep-2008 03:10
26-Sep-2008 09:37
To fetch (or submit data to) multiple pages during one session,use this:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, 'http://site.com/page1.php');
$result1 = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://site.com/page2.php');
$result2 = curl_exec($ch);
curl_close($ch);
?>
16-Sep-2008 10:34
Some of you may noticed that curl is not transferring cookies between sequent calls to a host. This is because you must activate curl`s "cookie parser". That is achieved using an external file like this:
<?php
curl_setopt(CURLOPT_FILE, '/tmp/cookies_file');
?>
If you don`t need to read any cookies but you still want the "cookie parser" use the same code but with dummy file with no data like '/dev/null', that way curl is storing cookies internaly per curl_handle:
<?php
curl_setopt(CURLOPT_FILE, '/dev/null');
?>
06-Sep-2008 11:51
Like eion said before (http://br.php.net/manual/ro/function.curl-setopt.php#71313), the function CURLOPT_FOLLOWLOCATION don't will work when OPEN_BASEDIR is ON (or SAFE_MODE is ON).
he created a CURLOPT_FOLLOWLOCATION function alternative named: curl_redir_exec()
Well, this function have a little error on line that contains:
list($header, $data) = explode("\n\n", $data, 2);
do you have replace for:
list($header, $data) = explode("\r\n", $data, 2);
note the '\n\n' cause this error, so just replace for '\r\n'.
Thanks Eion for your curl_redir_exec() Function :)
23-Aug-2008 02:14
If you set CURLOPT_RESUME_FROM to resume the file, and then reuse the same Curl handle to download another file, you must reset the resume status by calling curl_setopt( $ch, CURLOPT_RESUME_FROM, 0 ). It will not reset, and will apply to all subsequent transfers even if the URL is the same.
12-Aug-2008 07:12
Just a small detail I too easily overlooked.
<?php
/* If you set: */
curl_setopt ($ch, CURLOPT_POST, 1);
/* then you must have the data: */
curl_setopt ($ch, CURLOPT_POSTFIELDS, $PostData);
?>
I found with only the CURLOPT_POST set (from copy, paste editing of course) cookies were not getting sent with CURLOPT_COOKIE. Just something subtle to watch out for.
06-Aug-2008 01:28
What encoding will a given HTTP POST request use?
The answer is easy -- passing an array to CURLOPT_POSTFIELDS results in multipart/form-data:
<?php
curl_setopt(CURLOPT_POSTFIELDS, array('field1' => 'value'));
?>
Passing a URL-encoded string will result in application/x-www-form-urlencoded:
<?php
curl_setopt(CURLOPT_POSTFIELDS, array('field1=value&field2=value2'));
?>
I ran across this when integrating with both a warehouse system and an email system; neither would accept multipart/form-data, but both happily accepted application/x-www-form-urlencoded.
05-Aug-2008 01:56
if you use
<?php
curl_setopt($ch, CURLOPT_INTERFACE, "XXX.XXX.XXX.XXX");
?>
to specify IP adress for request, sometimes you need to get list of all your IP's.
ifconfig command will output something like:
rl0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=8<VLAN_MTU>
inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
ether XX:XX:XX:XX:XX:XX
media: Ethernet autoselect (100baseTX <full-duplex>)
status: active
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
tun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
Opened by PID 564
tun1: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
Opened by PID 565
Opened by PID 565
My solution for FreeBSD 6 and PHP 5 was:
<?php
ob_start();
$ips=array();
$ifconfig=system("ifconfig");
echo $ifconfig;
$ifconfig=ob_get_contents();
ob_end_clean();
$ifconfig=explode(chr(10), $ifconfig);
for ($i=0; $i<count($ifconfig); $i++) {
$t=explode(" ", $ifconfig[$i]);
if ($t[0]=="\tinet") {
array_push($ips, $t[1]);
}
}
for ($i=0; $i<count($ips); $i++) {
echo $ips[$i]."\n";
}
?>
You will get list of IP adresses in $ips array, like:
82.146.XXX.XXX
78.24.XXX.XXX
82.146.XXX.XXX
82.146.XXX.XXX
82.146.XXX.XXX
78.24.XXX.XXX
78.24.XXX.XXX
01-Aug-2008 10:03
Be careful when following Salil Kothadia's suggestion of using http_build_query with CURLOPT_POSTFIELDS.
As pinkgothic at gmail dot com explains on the http_build_query page: "Be careful if you're assuming that arg_separator defaults to '&'." For example, XAMPP changes the default in PHP.ini to '& amp' which may cause hours of frustration when trying to resolve failed form submissions.
10-Jul-2008 07:08
If you want to connect to a server which requires that you identify yourself with a certificate, use following code. Your certificate and servers certificate are signed by an authority whose certificate is in ca.ctr.
<?php
curl_setopt($ch, CURLOPT_VERBOSE, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '1');
curl_setopt($ch, CURLOPT_CAINFO, getcwd().'/cert/ca.crt');
curl_setopt($ch, CURLOPT_SSLCERT, getcwd().'/cert/mycert.pem');
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, 'password');
?>
If your original certificate is in .pfx format, you have to convert it to .pem using following commands
# openssl pkcs12 -in mycert.pfx -out mycert.key
# openssl rsa -in mycert.key -out mycert.pem
# openssl x509 -in mycert.key >> mycert.pem
07-Jul-2008 06:18
Although CURLOPT_CLOSEPOLICY and the applicable choices are valid constants, setting this option with curl_setopt() always returns false. A quick google search suggests the option is deprecated and/or never worked.
19-Jun-2008 11:19
Someone posted this under tmpfile (http://us3.php.net/manual/en/function.tmpfile.php#69419), and I thought it was particularly useful:
By the way, this function is really useful for libcurl's CURLOPT_PUT feature if what you're trying to PUT is a string. For example:
/* Create a cURL handle. */
$ch = curl_init();
/* Prepare the data for HTTP PUT. */
$putString = "Hello, world!";
$putData = tmpfile();
fwrite($putData, $putString);
fseek($putData, 0);
/* Set cURL options. */
curl_setopt($ch, CURLOPT_URL, "http://www.example.com");
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $putData);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString));
/* ... (other curl options) ... */
/* Execute the PUT and clean up */
$result = curl_exec($ch);
fclose($putData);
curl_close($ch);
19-Jun-2008 06:02
In PHP5, for the "CURLOPT_POSTFIELDS" option, we can use:
<?php
$ch = curl_init($URI);
$Post = http_build_query($PostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $Post);
$Output = curl_exec($ch);
curl_close($ch);
?>
09-Jun-2008 01:07
Be careful setting options while reusing a curl handle. I do not believe curl_exec resets the previous options e.g. the referrer and headers you set two requests ago may remain for the latest request.
I have not fully tested this and am interested in your results.
13-May-2008 09:17
Please note that the below is not entirely correct. This format will work partially, but does not always produce correct headers. The correct form for the same code is:
<?php
$str = array(
"Accept-Language: en-us,en;q=0.5",
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
"Keep-Alive: 300",
"Connection: keep-alive"
);
curl_setopt($this->curl_handle, CURLOPT_HTTPHEADER, $str);
?>
The appropriate newlines/cr's *should* be handled by curl.
This realization has cost me many hours, because Host, User-Agent, Cache-Control, etc appear to be handled correctly with the string form, but Content-Length and Content-Type are duplicated and the second copy is not parsed correctly by the server!
07-May-2008 03:26
I just spent the last 45 minutes banging my head against my keyboard because when using libcurl for a lighttpd server I would get a 400 Bad Request Error.
It turns out, that despite what has been mentioned in other comments, when using the CURLOPT_HTTPHEADER option, you must use \r\n as newline separators for each header NOT \n. For some reason lighttpd will not accept them. Other webservers will however.
Example:
<?php
$str = "Accept-Language: en-us,en;q=0.5\r\n";
$str .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
$str .= "Keep-Alive: 300\r\n";
$str .= "Connection: keep-alive\r\n";
curl_setopt($this->curl_handle, CURLOPT_HTTPHEADER, array($str));
?>
30-Apr-2008 11:31
OMG! I've joust found kinda bug:
YES, you can set an IP for curl to use by using this statement: curl_setopt($curl, CURLOPT_INTERFACE, $ip);
NO, you CAN NOT set another IP for the same curl object. I mean if u do curl_setopt($curl, CURLOPT_INTERFACE, $ip2); - it wont work!
So to change an IP you need to re-create curl object (curl_close, then curl_init).
10-Apr-2008 02:55
If you are doing a POST, and the content length is 1,025 or greater, then curl exploits a feature of http 1.1: 100 (Continue) Status.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3
* it adds a header, "Expect: 100-continue".
* it then sends the request head, waits for a 100 response code, then sends the content
Not all web servers support this though. Various errors are returned depending on the server. If this happens to you, suppress the "Expect" header with this command:
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
?>
See http://www.gnegg.ch/2007/02/the-return-of-except-100-continue/
04-Apr-2008 06:22
Clarification for the CURLOPT_NOBODY option: by excluding the body from your request, you're effectively making a HEAD request. Use the CURLOPT_NOBODY option to return only the headers in the remote response.
Example:
function check_url($url) {
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_HEADER, 1); // get the header
curl_setopt($c, CURLOPT_NOBODY, 1); // and *only* get the header
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); // get the response as a string from curl_exec(), rather than echoing it
curl_setopt($c, CURLOPT_FRESH_CONNECT, 1); // don't use a cached version of the url
if (!curl_exec($c)) { return false; }
$httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);
return ($httpcode < 400);
}
16-Feb-2008 07:26
If you try to upload file to a server, you need do CURLOPT_POST first and then fill CURLOPT_POSTFIELDS.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
^^ This will post multipart/form-data
Next example don't work:
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch, CURLOPT_POST, 1);
Sets to content-lenght:0 if $postvars an array.
29-Dec-2007 06:13
Despite the documentation for CURLOPT_HTTPHEADER, all header fields MUST be in one string, with a eol indicator, inside a single element array, in my experience.
For example, this will fail.
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50"));
?>
This will work.
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50\n"));
?>
This will only set the first header
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50\n","Otherheader: stuff\n"));
?>
This however, will set both headers as we want.
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50\nOtherheader: stuff\n"));
?>
12-Dec-2007 09:34
hey hey hey!
the problem: curl_setopt($ch,FOLLOW_LOCATION,1);
the error: trouble with open_basedir and safe_mode
the solution: a function already developed by someone
the solution n 2: the same function, modifed, works great for me..
function curl_redir_exec($ch,$debug="")
{
static $curl_loops = 0;
static $curl_max_loops = 20;
if ($curl_loops++ >= $curl_max_loops)
{
$curl_loops = 0;
return FALSE;
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$debbbb = $data;
list($header, $data) = explode("\n\n", $data, 2);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302) {
$matches = array();
preg_match('/Location:(.*?)\n/', $header, $matches);
$url = @parse_url(trim(array_pop($matches)));
//print_r($url);
if (!$url)
{
//couldn't process the url to redirect to
$curl_loops = 0;
return $data;
}
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
/* if (!$url['scheme'])
$url['scheme'] = $last_url['scheme'];
if (!$url['host'])
$url['host'] = $last_url['host'];
if (!$url['path'])
$url['path'] = $last_url['path'];*/
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
curl_setopt($ch, CURLOPT_URL, $new_url);
// debug('Redirecting to', $new_url);
return curl_redir_exec($ch);
} else {
$curl_loops=0;
return $debbbb;
}
}
just use this function without de FOLLOW_LOCATION and should work. the problem was that when you get to the line where you return the data if http_code was different than 301 oe 302, $data has obsolete information or none. so $debbbb does the job.
hope this helps someone out there
thanks from argentina
20-Aug-2007 11:03
This is very clear in hindsight, but it still cost me several hours:
curl_setopt($session, CURLOPT_HTTPPROXYTUNNEL, 1);
means that you will tunnel THROUGH the proxy, as in "your communications will go as if the proxy is NOT THERE".
Why do you care? - Well, if you are trying to use, say, Paros, to debug HTTP between your cURL and the server, with CURLOPT_HTTPPROXYTUNNEL set to TRUE Paros will not see or log your traffic thus defeating the purpose and driving you nuts.
There are other cases, of course, where this option is extremely useful...
20-Jul-2007 06:07
The explanation of CURLOPT_NOBODY ("TRUE to exclude the body from the output.") seems unclear to me -- I originally read "output" to mean the return value, i.e. the response. In fact it means to exclude the body from your *request*. Not sure whether "output" means the same thing for CURLOPT_HEADER though.
06-Jul-2007 12:09
if you are trying to connect to 'https://...' and after that want to work with POST data - that's the way:
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($curl, CURLOPT_COOKIEJAR, "cookiefile"); # SAME cookiefile
curl_setopt($curl, CURLOPT_URL, "url1"); # this is where you first time connect - GET method authorization in my case, if you have POST - need to edit code a bit
$xxx = curl_exec($curl);
curl_setopt($curl, CURLOPT_URL, "url2"); # this is where you are requesting POST-method form results (working with secure connection using cookies after auth)
curl_setopt($curl, CURLOPT_POSTFIELDS, "var1=value&var2=value&var3=value&"); # form params that'll be used to get form results
$xxx = curl_exec($curl);
curl_close ($curl);
echo $xxx;
27-Jun-2007 08:18
Two things that I noted, one of which has been mentioned earlier, if you are connecting to an SSL site (https) and don't have the appropriate certificate, don't forget to set CURLOPT_SSL_VERIFYPEER as "false"... it's set to "true" by default. Scratched my head over 2 hours to figure this one out as I had a machine with an older version installed and everything worked fine without using this option on that one - but failed on other machines with newer versions.
Second very important thing, I've never had my scripts work (tried on various machines, multiple platforms) with a Relative path to a COOKIEJAR or COOKIEFILE. In my experience I HAVE to specify the absolute path and not the relative path.
Small script I wrote to connect to a page, gather all cookies into a jar, connect to another page to login, taking the cookiejar with you for authentication:
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/Library/WebServer/Documents/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"https://www.example.com/myaccount/start.asp");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start(); // Prevent output
curl_exec ($ch);
ob_end_clean(); // End preventing output
curl_close ($ch);
unset($ch);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "field1=".$f1."&field2=".$f2."&SomeFlag=True");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/Library/WebServer/Documents/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"https://www.example.com/myaccount/Login.asp");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec ($ch);
curl_close ($ch);
12-Jun-2007 11:35
If you are getting the following error:
SSL: certificate subject name 'domain-or-ip-1.com' does not match target host name 'domain-or-ip-2.com'
Then you can set the following option to get around it:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
12-Jun-2007 10:55
Please note that the CURLOPT_INTERFACE setting only accepts IP addresses and hostnames of the local machine. It is not meant to send a URL to a specific IP address.
12-May-2007 06:52
curl will sometimes return an "Empty reply from server" error if you don't send a User-Agent string. Use the CURLOPT_USERAGENT option.
24-Apr-2007 06:01
Options not included in the above, but that work (Taken from the libcurl.a C documentation)
CURLOPT_FTP_SSL
Pass a long using one of the values from below, to make libcurl use your desired level of SSL for the ftp transfer. (Added in 7.11.0)
CURLFTPSSL_NONE
Don't attempt to use SSL.
CURLFTPSSL_TRY
Try using SSL, proceed as normal otherwise.
CURLFTPSSL_CONTROL
Require SSL for the control connection or fail with CURLE_FTP_SSL_FAILED.
CURLFTPSSL_ALL
Require SSL for all communication or fail with CURLE_FTP_SSL_FAILED.
14-Mar-2007 01:26
Seems that CURLOPT_RETURNTRANSFER Option set to TRUE, returns a "1" when the transaction returns a blank page.
I think is for eliminate the FALSE to can be with a blank page as return
08-Mar-2007 03:50
How to get rid of response after POST: just add callback function for returned data (CURLOPT_WRITEFUNCTION) and make this function empty.
function curlHeaderCallback($ch, $strHeader) {
}
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curlHeaderCallback')
03-Mar-2007 03:36
In response to "brett at brettbrewer dot com" and Jamolkhon, the fact you don't take into account is when a redirection (Location: ...) occurs, all the headers are given so the \r\n\r\n can also separate twp consecutive headers.
An even better trick to get the header is to use CURLINFO_HEADER_SIZE :
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($output, 0, $header_size - 4);
$body = substr($output, $header_size);
Then $headers contains all the headers.
15-Dec-2006 08:11
in response to "brett at brettbrewer dot com":
another useful way of getting headers without using regular expression
<?php
class CCurl {
var $m_handle;
var $m_header;
var $m_body;
function CCurl($sUrl) {
$this->m_handle = curl_init();
curl_setopt($this->m_handle, CURLOPT_URL, $sUrl);
curl_setopt($this->m_handle, CURLOPT_HEADER, 1);
curl_setopt($this->m_handle, CURLOPT_RETURNTRANSFER, 1);
return;
}
function getHeader() {
return $this->m_header;
}
function execute() {
$sResponse = curl_exec($this->m_handle);
$this->m_body = substr($sResponse, strpos($sResponse, "\r\n\r\n") + 4);
$this->m_header = substr($sResponse, 0, -strlen($this->m_body));
return $this->m_body;
}
function close() {
curl_close($this->m_handle);
return;
}
}
?>
(you can add something or make some changes to suit your needs)
22-Nov-2006 05:40
If you are trying to use CURLOPT_FOLLOWLOCATION and you get this warning:
Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set...
then you will want to read http://www.php.net/ChangeLog-4.php which says "Disabled CURLOPT_FOLLOWLOCATION in curl when open_basedir or safe_mode are enabled." as of PHP 4.4.4/5.1.5. This is due to the fact that curl is not part of PHP and doesn't know the values of open_basedir or safe_mode, so you could comprimise your webserver operating in safe_mode by redirecting (using header('Location: ...')) to "file://" urls, which curl would have gladly retrieved.
Until the curl extension is changed in PHP or curl (if it ever will) to deal with "Location:" headers, here is a far from perfect remake of the curl_exec function that I am using.
Since there's no curl_getopt function equivalent, you'll have to tweak the function to make it work for your specific use. As it is here, it returns the body of the response and not the header. It also doesn't deal with redirection urls with username and passwords in them.
<?php
function curl_redir_exec($ch)
{
static $curl_loops = 0;
static $curl_max_loops = 20;
if ($curl_loops++ >= $curl_max_loops)
{
$curl_loops = 0;
return FALSE;
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
list($header, $data) = explode("\n\n", $data, 2);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302)
{
$matches = array();
preg_match('/Location:(.*?)\n/', $header, $matches);
$url = @parse_url(trim(array_pop($matches)));
if (!$url)
{
//couldn't process the url to redirect to
$curl_loops = 0;
return $data;
}
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
if (!$url['scheme'])
$url['scheme'] = $last_url['scheme'];
if (!$url['host'])
$url['host'] = $last_url['host'];
if (!$url['path'])
$url['path'] = $last_url['path'];
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
curl_setopt($ch, CURLOPT_URL, $new_url);
debug('Redirecting to', $new_url);
return curl_redir_exec($ch);
} else {
$curl_loops=0;
return $data;
}
}
?>
09-Nov-2006 08:27
I have seen two posts complaining the "CURLOPT_POSTFIELDS" option is not working well.
This was the solution given below:
$o="";
foreach ($post_data as $k=>$v)
{
$o.= "$k=".utf8_encode($v)."&";
}
$post_data=substr($o,0,-1);
The assumption that this is an error is not true, as stated on http://curl.rtin.bz/docs/httpscripting.html:
" The data you send to the server MUST already be properly encoded, curl will
not do that for you. For example, if you want the data to contain a space,
you need to replace that space with %20 etc. Failing to comply with this
will most likely cause your data to be received wrongly and messed up."
This means you do really have to encode the data yourself the right way.
01-Oct-2006 01:51
As Yevgen mentioned earlier sometimes we can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE. Below is a header callback function I wrote back in January that lets you maintain cookies between cURL requests. Cookies are added to $ch during all requests even during redirection, so you can use it together with CURLOPT_FOLLOWLOCATION.
Here is the code:
function read_header($ch, $string)
{
global $location; #keep track of location/redirects
global $cookiearr; #store cookies here
global $ch;
# ^overrides the function param $ch
# this is okay because we need to
# update the global $ch with
# new cookies
$length = strlen($string);
if(!strncmp($string, "Location:", 9))
{ #keep track of last redirect
$location = trim(substr($string, 9, -1));
}
if(!strncmp($string, "Set-Cookie:", 11))
{ #get the cookie
$cookiestr = trim(substr($string, 11, -1));
$cookie = explode(';', $cookiestr);
$cookie = explode('=', $cookie[0]);
$cookiename = trim(array_shift($cookie));
$cookiearr[$cookiename] = trim(implode('=', $cookie));
}
$cookie = "";
if(trim($string) == "")
{ #execute only at end of header
foreach ($cookiearr as $key=>$value)
{
$cookie .= "$key=$value; ";
}
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}
return $length;
}
Using the header function with curl (add this before curl_exec):
#don't forget globals, especially if you are using this in function
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
This code assumes that you will reuse $ch without initializing it every time (call curl_init only once, in the beginning). If you need to initialize $ch again at any point in your code you can access the currently stored cookies in $cookiearr and include them in the new $ch.
I wrote this function before I had enough experience with regular expressions so you won't find any preg_match calls here. I have used this code for quite a while and without any problems accessing gmail, yahoo, hotmail, aol etc. where I had to go through login and a few pages before getting to what I was looking for.
Svetlozar Petrov (http://svetlozar.net)
23-Aug-2006 07:35
Note that if you want to use a proxy and use it as a _cache_, you'll have to do:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Pragma: "));
else by default Curl puts a "Pragma: no-cache" header in and thus force cache misses for all requests.
14-Jul-2006 12:58
You can use CURLOPT_HEADERFUNCTION with a callback inside an object. This makes is it easy to capture the headers for later use. For example:
<?
class Test
{
public $headers;
//...
public function exec($opts)
{
$this->headers = array();
$opts[CURLOPT_HEADERFUNCTION] = array($this, '_setHeader');
$ch = curl_init();
curl_setopt_array($ch, $opts);
return curl_exec($ch);
}
private function _setHeader($ch, $header)
{
$this->headers[] = $header;
return strlen($header);
}
}
$test = new Test();
$opts = array(
