This may not be a surprise for many, but I know I bled my eyes out trying to implement this in php. And when I knew it was this simple, I really felt extremely stupid. So I put this just so google will save somebody some time in the future.
PHP NTLM AUTH
Make sure you have the 'curl' extension loaded
now just do...
curl_setopt($ch,CURLAUTH_NTLM);
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password");
and just continue to use curl in the ordinary fashion.
curl_setopt
(PHP 4 >= 4.0.2, PHP 5)
curl_setopt — Define uma opção para a transferencia cURL
Descrição
Define uma opção para o manipulador de sessão cURL indicado.
Parâmetros
- ch
-
Um manipulador cURL retornado por curl_init().
- option
-
A CURLOPT_XXX opção a definir.
- value
-
O valor a ser definido em option .
value deve ser um booleano para os seguintes valores do parâmetro option :
Opção Definir value para Notas CURLOPT_AUTOREFERER TRUE para definir automaticamente um campo Referer: nas requisições aonde ele segue um redirecionamento Location:. Disponível desde PHP 5.1.0. CURLOPT_BINARYTRANSFER TRUE para retornar a saída crua quando CURLOPT_RETURNTRANSFER é usado. CURLOPT_COOKIESESSION TRUE para marcar este como um novo cookie de sessão. Ela irá forçar a libcurl a ignorar todos os cookies que esteja a ponto de carregar que sejam "cookies de sessão" da sessão anterior. Por padrão, libcurl sempre salva e carrega todos os cookies, independente se sejam cookies de sessão ou não. Cookies de sessão são cookies sem data de expiração o que significa que devem estar vivos e existir apenas para essa sesão apenas. Disponível desde PHP 5.1.0. CURLOPT_CRLF TRUE para converter finais de linha Unix para finais de linha CRLF nas transferencias. CURLOPT_DNS_USE_GLOBAL_CACHE TRUE para usar um cache de DNS global. Esta opção não é thread-safe e esta ativada por padrão. CURLOPT_FAILONERROR TRUE para falhar silenciosamente se o codigo HTTP retornado for maior ou igual a 400. O funcionamento padrão é retornar a pagina normalmente, ignorando o codigo. CURLOPT_FILETIME TRUE para tentar obter a data de modificação do documento remoto. Este valor pode ser obtido usando a opção CURLINFO_FILETIME com curl_getinfo(). CURLOPT_FOLLOWLOCATION TRUE para seguir qualquer cabeçalho "Location: " que o servidor envie como parte do cabeçalho HTTP (note que isto é recursivo, PHP irá seguir tantos cabeçalhos "Location: " quantos sejam enviados, a menos que CURLOPT_MAXREDIRS seja definido). CURLOPT_FORBID_REUSE TRUE para forçar a conexão ser fechada explicitamente quando o processamento seja terminado, e não ser guardada para reuso. CURLOPT_FRESH_CONNECT TRUE para forçar o uso de uma nova conexão ao invés de uma guardada em cache. CURLOPT_FTP_USE_EPRT TRUE para usar EPRT (e LPRT) ao fazer downloads FTP ativos. Use FALSE para desabilitar EPRT e LPRT e usar apenas PORT. Adicionado no PHP 5.0.0. CURLOPT_FTP_USE_EPSV TRUE para tentar primeiro um comando EPSV pára transferencias FTP antes de reverter de volta para PASV. Defina como FALSE para desabilitar EPSV. CURLOPT_FTPAPPEND TRUE para adicionar ao arquivo remoto ao invés de sobrescreve-lo. CURLOPT_FTPASCII um apelido para CURLOPT_TRANSFERTEXT. Use aquela ao invés. CURLOPT_FTPLISTONLY TRUE para listar apenas os nomes de um diretório FTP. CURLOPT_HEADER TRUE para incluir o cabeçalho na saída. CURLOPT_HTTPGET TRUE para redefinir o metodo de solicitação HTTP para GET. já que GET é o padrão, isto apenas é necessário se o metodo de solicitação foi modificado. CURLOPT_HTTPPROXYTUNNEL TRUE para fazer tunel através de um servidor HTTP proxy indicado. CURLOPT_MUTE TRUE para ser compeltamente silencioso no que diz respeito as funções cURL. CURLOPT_NETRC TRUE to scan the ~/.netrc file to find a username and password for the remote site that a connection is being established with. CURLOPT_NOBODY TRUE to exclude the body from the output. CURLOPT_NOPROGRESS TRUE para desabilitar o medidor de progresso para as transferencias cURL.
Nota: PHP automaticamente define essa opção como TRUE, isto deve ser modificado apenas para fins de debug.
CURLOPT_NOSIGNAL TRUE para ignorar qualquer função cURL que faça com que um sinal seja enviado para o processo PHP. Isto é ativado por padrão em servidores multi-tarefa assim opções de limite de tempo ainda podem ser usadas. Adicionado no cURL 7.10 e PHP 5.0.0. CURLOPT_POST TRUE para fazer um HTTP POST normal. Este POST é do tipo normal application/x-www-form-urlencoded, mais comunmente usado pelos formulários HTML. CURLOPT_PUT TRUE para enviar um arquivo usando HTTP PUT. O arquivo a enviar deve estar definido com CURLOPT_INFILE e CURLOPT_INFILESIZE. CURLOPT_RETURNTRANSFER TRUE para retornar a transferencia como uma string de valor de retorno de curl_exec() ao invés de enviar diretamente para a saída. CURLOPT_SSL_VERIFYPEER FALSE para fazer o cURL parar de verificar o certificado do cliente. Certificados alternativos para verificar podem ser definidos com a opção CURLOPT_CAINFO ou um diretório de certificados pode ser definido com a opção CURLOPT_CAPATH. CURLOPT_SSL_VERIFYHOST também precisa ser definido como TRUE ou FALSE se CURLOPT_SSL_VERIFYPEER esta desabilitado (o padrão é 2). TRUE por padrão a partir do cURL 7.10. Instalado por padrão a partir do cURL 7.10. CURLOPT_TRANSFERTEXT TRUE para usar o modo ASCII para transferencias FTP. Para LDAP, ele obtem os datos em texto simples ao invés de HTML. Em Sistemas Windows, ele não irá definir STDOUT para o modo binário. CURLOPT_UNRESTRICTED_AUTH TRUE para continuar enviando o nome de usuário e senha ao seguir localizações (usando CURLOPT_FOLLOWLOCATION), mesmo que o nome do servidor tenha mudado. Adicionado no PHP 5.0.0. CURLOPT_UPLOAD TRUE para preparar para o envio de um arquivo. CURLOPT_VERBOSE TRUE para enviar muita informação para a saída. Escreve a saída para STDERR, ou para o arquivo especificado usando CURLOPT_STDERR. value deve ser um inteiro para os seguintes valores do parâmetro option :
Opção Definir value como Notas CURLOPT_BUFFERSIZE O tamanho do buffer a usar em cada lida. Não há garantia de que este pedido será cumprido, entretando. Adicionado no cURL 7.10 e PHP 5.0.0. CURLOPT_CLOSEPOLICY Ou CURLCLOSEPOLICY_LEAST_RECENTLY_USED ou CURLCLOSEPOLICY_OLDEST . Existem ainda três outras constantes CURLCLOSEPOLICY_, mas cURL ainda não as suporta. CURLOPT_CONNECTTIMEOUT O número de segundos para esperar ao tentar se conectar. Use 0 para esperar infinitamente. CURLOPT_DNS_CACHE_TIMEOUT O número de segundos para manter entradas DNS na memória. Esta opção é definida para 120 (2 minutos) por padrão. CURLOPT_FTPSSLAUTH O método de autenticação FTP (quando é ativado): CURLFTPAUTH_SSL (tentar SSL primeiro), CURLFTPAUTH_TLS (tentar TLS primeiro), ou CURLFTPAUTH_DEFAULT (deixar cURL decidir). Adicionado no cURL 7.12.2 e PHP 5.1.0. CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE (padrão, deixa o CURL decidir qual versão usar), CURL_HTTP_VERSION_1_0 (força HTTP/1.0), ou CURL_HTTP_VERSION_1_1 (força HTTP/1.1). CURLOPT_HTTPAUTH O metodo de autenticação HTTP a usar. As opções são: CURLAUTH_BASIC , CURLAUTH_DIGEST , CURLAUTH_GSSNEGOTIATE , CURLAUTH_NTLM , CURLAUTH_ANY , e CURLAUTH_ANYSAFE .
O operador de bits | (ou) pode ser usado para combinar mais de um metodo. Se isso for feito, o cURL irá conversar com o servidor e ver quais métodos ele suporta e escolher o melhor.
CURLAUTH_ANY é um apelido para CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.
CURLAUTH_ANYSAFE é um apelido para CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.
Adicionado no PHP 5.0.0. CURLOPT_INFILESIZE O tamanho experado, em bytes, do arquivo ao enviar um arquivo para um local remoto. CURLOPT_LOW_SPEED_LIMIT A velocidade de transferencia, em bytes por segundos, a qual a transferência deve estar abaixo durante de CURLOPT_LOW_SPEED_TIME segundos para o PHP considerar a transferência muito lenta e abortar. CURLOPT_LOW_SPEED_TIME O número de segundos que a transferência deve estar abaixo de CURLOPT_LOW_SPEED_LIMIT para o PHP considerar a transferência lenta de mais e abortar. CURLOPT_MAXCONNECTS O número máximo de conexões persistentes que são permitidas. Quando o limite é atingido, CURLOPT_CLOSEPOLICY é usado para determinar qual conexão deve ser fechada. CURLOPT_MAXREDIRS O número máximo de redirecionamentos HTTP a seguir. Use esta opção em conjunto com CURLOPT_FOLLOWLOCATION. CURLOPT_PORT Um número alternativo de porta para conectar. CURLOPT_PROXYAUTH Os métodos HTTP de autenticação usados para conectar ao servidor proxy. Use as mesmas mascaras de bits descritas em CURLOPT_HTTPAUTH. Para autenticação com o proxy, apenas CURLAUTH_BASIC e CURLAUTH_NTLM são suportados atualmente. Adicionado em cURL 7.10.7 e PHP 5.1.0. CURLOPT_PROXYPORT O número de porta para conectar ao proxy. Este número de porta também pode ser definido em CURLOPT_PROXY. Adicionado no PHP 5.0.0. CURLOPT_PROXYTYPE Ou CURLPROXY_HTTP (padrão) ou CURLPROXY_SOCKS5 . Adicionado no cURL 7.10 e PHP 5.0.0. CURLOPT_RESUME_FROM O índice, em bytes, a partir do qual continuar a transferencia. CURLOPT_SSL_VERIFYHOST 1 para conferir a existencia do nome comum no certificado SSL do cliente. 2 para conferir a existencia de um nome comum e também conferir se combina com o nome de servidor dado. CURLOPT_SSLVERSION A versão SSL (2 ou 3) a ser usada. por padrão o PHP tentará determinar isso por sí mesmo, entretando em alguns casos deve ser definido manualmente. CURLOPT_TIMECONDITION Como CURLOPT_TIMEVALUE é tratado. Use CURL_TIMECOND_IFMODSINCE para retornar apagina apenas se foi modificada desde o tempo especificado em CURLOPT_TIMEVALUE. Se não foi modificada um cabeçalho "304 Not Modified" assumindo que CURLOPT_HEADER seja TRUE. Use CURL_TIMECOND_ISUNMODSINCE para o efeito reverso. CURL_TIMECOND_IFMODSINCE é o padrão. Adicionado no PHP 5.1.0. CURLOPT_TIMEOUT O número máximo de segundos que uma função cURL pode executar. CURLOPT_TIMEVALUE O tempo em segundos desde 1º de Janeiro de 1970. O tempo será usado por CURLOPT_TIMECONDITION. Por padrão, CURL_TIMECOND_IFMODSINCE é usado. value deve ser uma string para os seguintes valores do parâmetro option :
Opção Definir o value para Notas CURLOPT_CAINFO O nome do arquivo contendo um ou mais certidicados para verificar o peer. Esta opção apenas tem sentido em conjunto com CURLOPT_SSL_VERIFYPEER. CURLOPT_CAPATH Um diretório que contem vários certificados CA. Use este opção em conjunto com CURLOPT_SSL_VERIFYPEER. CURLOPT_COOKIE O conteúdo do cabeçalho "Set-Cookie: " a ser utilizado na requisição HTTP. CURLOPT_COOKIEFILE O nome do arquivo contendo os dados de cookie. O arquivo de cookie pode estar no formato Netscape, ou apenas no estilo de cabeçalhos HTTP salvos em um arquivo. CURLOPT_COOKIEJAR O nome do arquivo para salvar todos os cookies internos quando a conexão fechar. CURLOPT_CUSTOMREQUEST Um método de solicitação personalizado para usar ao invés de "GET" ou "HEAD" ao fazer uma solicitação HTTP. Isto é útil para fazer "DELETE" ou outras solicitações HTTP mais obscuras. Valores válidos são coisas como "GET", "POST", "CONNECT" e assim por diante; i.e. Do not enter a whole HTTP request line here. For instance, entrar "GET /index.html HTTP/1.0\r\n\r\n" estaria errado.
Nota: Não faça isto sem ter certesa que o servidor suporte a requisição personaçlizada primeiro.
CURLOPT_EGDSOCKET Como CURLOPT_RANDOM_FILE, exceto um nome de arquivo para um Entropy Gathering Daemon socket. CURLOPT_ENCODING O conteúdo do cabeçalho "Accept-Encoding: ". Isto ativa a decodificação da resposta. codificações suportadas são "identity", "deflate", e "gzip". Se for definida uma string vazia, "", um cabeçalho contendo todos os tipos de codificações suportados é enviado. Adicionado no cURL 7.10. CURLOPT_FTPPORT O valor o qual vai ser usado para ter o endereço IP para usar com a instrução FTP "POST". A instrução "POST" diz ao servidor remoto conectar com o seu endereço IP especificado. A string deve ser um endereço IP simples, um nome de servidor, um nome de interface de rede (sob o Unix), ou apenas um simples "-" para usar o endereço IP padrão do sistema. CURLOPT_INTERFACE O nome da interface de rede de saída a usar. Isto pode ser um nome de interface, um endereço IP ou um nome de servidor. CURLOPT_KRB4LEVEL O nível de segurança KRB4 (Kerberos 4). Qualquer un dos seguintes valores (em ordem do menos ao mais poderoso) são válidos: "clear", "safe", "confidential", "private".. Se a string não combinar com um destes, "private" é usado. Definir esta opção como NULL irá desabilitar a segurança KRB4. Atualmente a segurança KRB4 funciona apenas com transações FTP. CURLOPT_POSTFIELDS Todos os dados para enviar em uma operação HTTP "POST". Para enviar um arquivo, adicione antes do nome do arquivo um @ e use o caminho completo. CURLOPT_PROXY O servidor HTTP proxy pelo qual passar as requisições. CURLOPT_PROXYUSERPWD Um nome de usuário e senha formatados como "[username]:[password]" para usar na conexão com o proxy. CURLOPT_RANDOM_FILE Um nome de arquivo para ser usado como semente para o gerador de números aleatórios para SSL. CURLOPT_RANGE Intervalo(s) de data para obter no formato "X-Y" aonde X ou Y é opcional. Transferencias HTTP também suportam vários intervalos, separados por vírgulas no formato "X-Y,N-M". CURLOPT_REFERER O conteúdo do cabeçalho "Referer: " a ser usado em uma solicitação HTTP. CURLOPT_SSL_CIPHER_LIST Uma lista de ciphers para usar com SSL. Por exemplo, RC4-SHA e TLSv1 são listas cipher validas. CURLOPT_SSLCERT O nome de um arquivo contendo um certificado formatado PEM. CURLOPT_SSLCERTPASSWD A senha necessária para usar o certificado CURLOPT_SSLCERT. CURLOPT_SSLCERTTYPE O formato do certificado. Formatos suportados são "PEM" (default), "DER", e "ENG". Adicionado no cURL 7.9.3 e PHP 5.0.0. CURLOPT_SSLENGINE O identificador para o motor de criptografia da chave SSL privada especificada em CURLOPT_SSLKEY. CURLOPT_SSLENGINE_DEFAULT O identificador para o motor de criptografia usado para para operações assimétricas. CURLOPT_SSLKEY O nome de um arquivo contendo uma chave SSL privada. CURLOPT_SSLKEYPASSWD A senha secreta necessária para usar a chave privada SSL especificada em CURLOPT_SSLKEY.
Nota: Já que esta opção contem uma senha sensível, lembre-se de manter o script PHP que a contem em segurança.
CURLOPT_SSLKEYTYPE O tipo de chave para a chave SSL privada especificada em CURLOPT_SSLKEY. Tipos de chaves suportados são "PEM" (default), "DER", and "ENG". CURLOPT_URL A URL para obter. isto também pode ser definido ao inicializar a sessão com curl_init(). CURLOPT_USERAGENT O conteúdo do cabeçalho "User-Agent: " a ser usado na solicitação HTTP. CURLOPT_USERPWD Um nome de usuário e senha formatado como "[username]:[password]" para usar para a conexão. value deve ser uma matriz para os seguintes valores do parâmetro option :
Opção Definir value como Notas CURLOPT_HTTP200ALIASES Um array de respostas HTTP 200 que serão tratadas como respostas válidas e não como erros. Adicionado no cURL 7.10.3 e PHP 5.0.0. CURLOPT_HTTPHEADER Um array de cabeçalhos HTTP a definir. CURLOPT_POSTQUOTE Um array de comandos FTP a executar no servidor depois de a requisição FTP ter sido realizada. CURLOPT_QUOTE Um array de comandos FTP a serem executados no servidor antes da requesição. value deve ser um recurso stream (usando fopen(), por exemplo) para os seguintes valores do parâmetro option :
Opção Define value como Notas CURLOPT_FILE O arquivo na qual a transferencia deve ser escrita. O padrão é STDOUT (a janela do browser). CURLOPT_INFILE O arquivo que deve ser lido ao se fazer um upload. CURLOPT_STDERR Um local alternativo para se escrever os erros ao invés de STDERR. CURLOPT_WRITEHEADER O arquivo em que a parte do cabeçalho da transferencia é escrita. value dese ser uma string que seja o nome de uma função de callback válida para os seguintes valores do parãmetro option :
Opção Define value como Notas CURLOPT_HEADERFUNCTION O nome da função de callback aonde a função de callback tem dois parâmetros. O primeiro é o recurso cURL, o segundo é uma string com os ados a serem escritos. Os dados do cabeçalho devem ser escritos usando esta função de callback. Retorna o número de bytes escritos. CURLOPT_PASSWDFUNCTION O nome da função de callback aonde a função de callback tem três parâmetros. O primeiro é o recurso cURL, o segundo é uma string contendo uma string para o pronpt da senha, e o terceiro é o limite de tamanho da senha. Retorna a string contendo a senha. CURLOPT_READFUNCTION O nome da função de callback aonde a função de callback tem dois parâmetros. O primeiro é o recurso cURL, e so segundo é uma string com os dados a serem lidos. Os dados devem ser lidos atráves dessa função de callback. Retorna o número de bytes lidos. Retorne 0 para indicar EOF (final do arquivo). CURLOPT_WRITEFUNCTION O nome da função de callback aonde a função de callback tem dois parâmetros. O primeiro é o recurso resource, e o segundo é a string com os dados a serem escritos. Os dados devem ser escritos usando essa função de callback. Deve retornar o número exato de bytes escritos ou isto irá falhar.
Valor Retornado
Retorna TRUE em caso de sucesso ou FALSE em falhas.
Exemplos
Exemplo #1 inicializando uma nova sessão cURL e obtendo uma pagina da internet
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>
Exemplo #2 Enviando um arquivo
<?php
/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
?>
O exemplo acima irá imprimir:
Array ( [name] => Foo ) Array ( [file] => Array ( [name] => test.png [type] => image/png [tmp_name] => /tmp/phpcpjNeQ [error] => 0 [size] => 279 ) )
curl_setopt
10-Oct-2008 02:20
26-Sep-2008 06:10
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.
26-Sep-2008 12: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 01: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 02: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 :)
22-Aug-2008 05: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 10: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.
05-Aug-2008 04: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 04: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 01: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 10: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 09: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 02: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 09: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 04: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 12: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!
06-May-2008 06: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 02: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).
09-Apr-2008 05: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 09: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);
}
15-Feb-2008 10: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.
28-Dec-2007 09: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 12: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 02: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 09: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.
05-Jul-2007 03: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 11: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 02: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 01: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.
11-May-2007 09: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 09: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.
13-Mar-2007 05: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 06: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 06: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 11: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)
21-Nov-2006 08: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 11: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 04: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 10: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.
13-Jul-2006 03: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(
//... your curl opts here
);
$data = $test->exec($opts);
print_r($test->headers);
?>
...something like that
(This works in php v. 5.1.4)
30-May-2006 11:31
Clarification on the callback methods:
- CURLOPT_HEADERFUNCTION is for handling header lines received *in the response*,
- CURLOPT_WRITEFUNCTION is for handling data received *from the response*,
- CURLOPT_READFUNCTION is for handling data passed along *in the request*.
The callback "string" can be any callable function, that includes the array(&$obj, 'someMethodName') format.
-Philippe
14-Apr-2006 07:22
Sometimes you can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE becoz of the server php-settings(They say u may grab any files from server using these options). Here is the solution
1)Don't use CURLOPT_FOLLOWLOCATION
2)Use curl_setopt($ch, CURLOPT_HEADER, 1)
3)Grab from the header cookies like this:
preg_match_all('|Set-Cookie: (.*);|U', $content, $results);
$cookies = implode(';', $results[1]);
4)Set them using curl_setopt($ch, CURLOPT_COOKIE, $cookies);
Good Luck, Yevgen
27-Mar-2006 02:59
- CURLOPT-HTTPAUTH is defined in php 4.4.2 9and maybe lower), even tough the manual says php 5.0 only...
- it is not clear from the manual what kind of http auth is carried out by default if user specifies username/pwd: it is BASIC auth
ps: note to manual writers: the version info on this page always looks a bit inaccurate, especially regarding the php version where a given option first appeared...
27-Dec-2005 02:24
To further expand upon use of CURLOPT_CAPATH and CURLOPT_CAINFO...
In my case I wanted to prevent curl from talking to any HTTPS server except my ow