Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

curl_setopt

(PHP 4 >= 4.0.2, PHP 5)

curl_setopt -- Устанавливает параметр для сеанса CURL

Описание

bool curl_setopt ( resource ch, string option, mixed value )

Функция curl_setopt() Устанавливает параметр для сеанса CURL, заданного аргументом ch. Аргумент option задает устанавливаемый параметр, а value - его значение.

Для перечисленных ниже параметров, value должен быть целым числом:

  • CURLOPT_INFILESIZE: при закачке файла на удаленный сервер, следует использовать этот параметр для указания ожидаемого размера файла.

  • CURLOPT_VERBOSE: При установке этого параметра в ненулевое значение cURL будет выводить подробные сообщения о всех производимых действиях.

  • CURLOPT_HEADER: При установке этого параметра в ненулевое значение результат будет включать полученные заголовки.

  • CURLOPT_NOPROGRESS: При установке этого параметра в ненулевое значение не будет выводиться индикатор прогресса операции.

    Замечание: В PHP этот параметр устанавливается в ненулевое значение по умолчнию. Изменять его значение рекомендуется только при отладке.

  • CURLOPT_NOBODY: При установке этого параметра в ненулевое значение результат не будет включать документ (например, вам нужно получить только заголовки).

  • CURLOPT_FAILONERROR: При установке этого параметра в ненулевое значение, получение HTTP кода более 300 считается ошибкой.

  • CURLOPT_UPLOAD: Установка этого параметра в ненулевое значение означает, что будет производиться закачка файла на удаленный сервер.

  • CURLOPT_POST: При установке этого параметра в ненулевое значение будет отправлен HTTP запрос методом POST типа application/x-www-form-urlencoded, используемый браузерами при отправке форм.

  • CURLOPT_FTPLISTONLY: При установке этого параметра в ненулевое значение будет получен список файлов в директории FTP сервера.

  • CURLOPT_FTPAPPEND: При установке этого параметра в ненулевое значение данные будут добавляться к файлу на FTP сервере, в противном случае файл будет перезаписан.

  • CURLOPT_NETRC: При установке этого параметра в ненулевое значение будет сделана попытка найти имя пользователя и пароль к удаленному серверу в файле ~./netrc.

  • CURLOPT_FOLLOWLOCATION: При установке этого параметра в ненулевое значение, при получении HTTP заголовка "Location: " будет происходить перенаправление на указанный этим заголовком URL (это действие выполняется рекурсивно, для каждого полученного заголовка "Location:").

  • CURLOPT_PUT: При установке этого параметра в ненулевое значение, будет производиться закачка файла методом HTTP PUT. Файл задается параметрами CURLOPT_INFILE и CURLOPT_INFILESIZE.

  • CURLOPT_MUTE: При установке этого параметра в ненулевое значение, все сообщения cURL будут подавляться.

  • CURLOPT_TIMEOUT: Задает масимальное время выполнения операции в секундах.

  • CURLOPT_LOW_SPEED_LIMIT: Задает минимальную скорость передачи в байтах в секунду. Если в течении времени, заданного параметром CURLOPT_LOW_SPEED_TIME, скорость передачи будет меньше этого значения, операция будет прервана.

  • CURLOPT_LOW_SPEED_TIME: Задает время в секундах, в течение которого скорость передачи должна быть ниже, чем CURLOPT_LOW_SPEED_LIMIT, чтобы операция была признана слишком медленной и прервана.

  • CURLOPT_RESUME_FROM: Задает позицию в файле в байтах, с которой начнется передача данных.

  • CURLOPT_CAINFO: Имя файла, содержащего один или более сертификатов, которые будут использованы при проверке подлинности удаленного сервера. Имеет значение только совместно с параметром CURLOPT_SSL_VERIFYPEER.

  • CURLOPT_SSL_VERIFYPEER: Установите этот параметр в ноль, чтобы запретить проверку сертификата удаленного сервера (начиная с curl 7.10, по умолчанию этот параметр имеет значение TRUE). Дополнительные сертификаты можно задать с помощью параметра CURLOPT_CAINFO (добавленного в in curl 7.9.8). Можно также указать путь к файлам сертификатов в параметре CURLOPT_CAPATH. Если CURLOPT_SSL_VERIFYPEER установлен в 0, возможно, также потребуется установить CURLOPT_SSL_VERIFYHOST в 1 или 0 (по умолчанию 2).

  • CURLOPT_SSLVERSION: Целое число, указывающее, какую версию SSL использовать (2 или 3). По умолчанию версия SSL определяется автоматически, но в некоторых случаях требуется явное указание.

  • CURLOPT_SSL_VERIFYHOST: Задает проверку имени, указанного в сертификате удаленного сервера, при установлении SSL соединения. Значение 1 означает проверку существования имени, значение 2 - кроме того, и проверку соответствия имени хоста.

  • CURLOPT_TIMECONDITION: Задает способ интерпретации значения параметра CURLOPT_TIMEVALUE. Возможные значения: TIMECOND_IFMODSINCE или TIMECOND_ISUNMODSINCE. Применяется только для протокола HTTP.

  • CURLOPT_TIMEVALUE: Задает время в секундах с 1 января 1970 г. Это значение будет использовано в соответствии со значением параметра CURLOPT_TIMECONDITION (по умолчанию TIMECOND_IFMODSINCE).

  • CURLOPT_RETURNTRANSFER: При установке этого параметра в ненулевое значение CURL будет возвращать результат, а не выводить его.

Для перечисленных ниже параметров, value должен быть строкой:

  • CURLOPT_URL: URL, с которым будет производиться операция. Значение этого параметра также может быть задано в вызове функции curl_init().

  • CURLOPT_USERPWD: Стока с именем пользователя и паролем в виде [username]:[password].

  • CURLOPT_PROXYUSERPWD: Стока с именем пользователя и паролем к HTTP прокси-серверу в виде [username]:[password].

  • CURLOPT_RANGE: Задает участок файла, который нужно загрузить, в формате "X-Y" , причем X или Y могут быть опущены. Протокол HTTP также поддерживает передачу нескольких фрагментов файла, это задается в виде "X-Y,N-M".

  • CURLOPT_POSTFIELDS: Строка, содержащая данные для HTTP POST запроса.

  • CURLOPT_REFERER: Задает значение HTTP заголовка "Referer: ".

  • CURLOPT_USERAGENT: Задает значение HTTP заголовка "User-Agent: ".

  • CURLOPT_FTPPORT: Задает значение, которое будет использоваться для определения IP адреса для команды "PORT" протокола ftp. Команда "PORT" сообщает серверу, с каким IP адресом он должен устанавливать соединение. Это может быть IP адрес, имя хоста, имя сетевого интерфейса (под Unix), или просто '-' для использования IP адреса по умолчанию.

  • CURLOPT_COOKIE: Содержимое заголовка "Cookie: ", который будет отправлен с HTTP запросом.

  • CURLOPT_SSLCERT: Имя файла с сертификатом в формате PEM.

  • CURLOPT_SSLCERTPASSWD: Пароль к файлу сертификата, заданному параметром CURLOPT_SSLCERT.

  • CURLOPT_COOKIEFILE: Имя файла, содержащего данные cookie. Данные могут быть либо в формате Netscape, либо просто HTTP-заголовки.

  • CURLOPT_CUSTOMREQUEST: Задает специальный метод, который будет использован в HTTP запросе вместоGET или HEAD. Это используется для отправке запросов DELETE или других, редко используемых. Допустимыми зачениями являются GET, POST, и т.д; не передавайте полный HTTP запрос в этом параметре. Например, 'GET /index.html HTTP/1.0\r\n\r\n' недопустимо.

    Замечание: Перед использованием этого параметра убедитесь, что сервер, к которому вы обращаетесь, поддерживает требуемый метод.

  • CURLOPT_PROXY: Имя HTTP прокси, через который будут направляться запросы.

  • CURLOPT_INTERFACE: Имя используемого сетевого интерфейса. Может быть именем интерфейса, IP адресом или именем хоста.

  • CURLOPT_KRB4LEVEL: Уровень безопасности KRB4 (Kerberos 4). Допустимы следующие значения (в порядке возрастания безопасности) : 'clear', 'safe', 'confidential', 'private'. Если переданное значение не входит в этот список, используется 'private'. Установка этого параметра в NULL, запрещает безопасность KRB4 . В настоящее время безопасность KRB4 поддерживается только для протокола FTP.

  • CURLOPT_HTTPHEADER: Массив с HTTP заголовками.

  • CURLOPT_QUOTE: Массив с FTP командами, которые будут выполнены перед выполнением основного запроса.

  • CURLOPT_POSTQUOTE: Массив с FTP командами, которые будут выполнены после выполнения основного запроса.

Для перечисленных ниже параметров, value должен быть дескриптором файла, возвращенным функцией fopen():

  • CURLOPT_FILE: Файл, в который будет выведен результат операции. По умолчанию STDOUT.

  • CURLOPT_INFILE: Файл, содержащий данные для передачи.

  • CURLOPT_WRITEHEADER: Файл, в который будут выведены полученные заголовки.

  • CURLOPT_STDERR: Файл, в который будут выводиться сообщения об ошибках. По умолчанию STDERR.

Пример 1. Инициализация сеанса CURL и загрузка web-страницы

<?php
// инициализация сеанса
$ch = curl_init();

// установка URL и других необходимых параметров
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// загрузка страницы и выдача её браузеру
curl_exec($ch);

// завершение сеанса и освобождение ресурсов
curl_close($ch);
?>



curl_version> <curl_setopt_array
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
curl_setopt
patrick fournier
24-Oct-2007 07:38
If you pass a string as the argument to CURLOPT_POSTFIELDS, your data will be interpreted as x-www-form-urlencoded; if you pass an array, it will be interpreted as multi-part form-data.

So if you want to upload a file:
- pass an array to CURLOPT_POSTFIELDS
- do not urlencode your data
- put a @ in front of your file name.
andrabr at gmail dot com
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...
chuck
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.
michael sky
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;
sleepwalker at rahulsjohari dot com
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);
mcbreen at gmail dot com
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);
vincent at ludden dot nl
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.
Jon Freilich
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.
rob at infoglobe dot net
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.
alfredoaguirre dot v at gmail dot com
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
paczor
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')
Killerwhile
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.
Jamolkhon
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)
eion at bigfoot dot com
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;
        }
    }
?>
jochem AT hotmail dot com
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.
zarko at svetlozar dot net
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)
php at miggy dot org
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.
bendavis78 at gmail dot com
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)
Philippe dot Jausions at 11abacus dot com
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
mr at coder dot tv
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
giunta dot gaetano at sea-aeroportimilano dot it
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...
Dustin Hawkins
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 own using a self signed certificate. To do this, you'll need openssl installed and access to the HTTPS Server Certificate (server.crt by default on apache)

You can then use a command simiar to this to translate your apache certificate into one that curl likes.

$ openssl x509 -in server.crt -out outcert.pem -text

Then set CURLOPT_CAINFO equal to the the full path to outcert.pem and turn on CURLOPT_SSL_VERIFYPEER.

If you want to use the CURLOPT_CAPATH option, you should create a directory for all the valid certificates you have created, then use the c_rehash script that is included with openssl to "prepare" the directory.

If you dont use the c_rehash utility, curl will ignore any file in the directory you set.
skyogre __at__ yandex __dot__ ru
22-Dec-2005 02:13
There is really a problem of transmitting $_POST data with curl in php 4+ at least.
I improved the encoding function by Alejandro Moreno to work properly with mulltidimensional arrays.

<?php
function data_encode($data, $keyprefix = "", $keypostfix = "") {
 
assert( is_array($data) );
 
$vars=null;
  foreach(
$data as $key=>$value) {
    if(
is_array($value)) $vars .= data_encode($value, $keyprefix.$key.$keypostfix.urlencode("["), urlencode("]"));
    else
$vars .= $keyprefix.$key.$keypostfix."=".urlencode($value)."&";
  }
  return
$vars;
}

curl_setopt($ch, CURLOPT_POSTFIELDS, substr(data_encode($_POST), 0, -1) );

?>
phpnet at wafflehouse dot de
23-Oct-2005 06:34
Resetting CURLOPT_FILE to STDOUT won't work by calling curl_setopt() with the STDOUT constant or a php://output stream handle (at least I get error messages when trying the code from phpnet at andywaite dot com). Instead, one can simply reset it as a side effect of CURLOPT_RETURNTRANSFER. Just say

        curl_setopt($this->curl,CURLOPT_RETURNTRANSFER,0);

and following calls to curl_exec() will output to STDOUT again.
webmaster () stauceni.com
20-Oct-2005 01:42
A little mistake, that took a half-day to fix it:
When specifing CURLOPT_COOKIEFILE or CURLOPT_COOKIEJAR options, don't forget to "chmod 777" that directory where cookie-file must be created.
mcknight at chek dot com
22-Aug-2005 08:10
when specifing the file for either CURLOPT_COOKIEFILE or CURLOPT_COOKIEJAR you may need to use the full file path instead of just the relative path.
phpnet at andywaite dot com
07-Jun-2005 02:08
After setting CURLOPT_FILE, you may want want to revert back to the normal behaviour of displaying the results. This can be achieved using:

$fp = fopen ("php://output", "w") or die("Unable to open stdout for writing.\n");
curl_setopt($ch, CURLOPT_FILE, $fp);
ikendra at yken dot nospam dot org
09-May-2005 09:26
Using cURL, I needed to call a third-party script which was returning binary data as attachment to pass on retrieved data again as attachment.

Problem was that the third-party script occassionally returned HTTP errors and I wanted to avoid passing on zero-length attachment in such case.

Combination of using CURLOPT_FAILONERROR and CURLOPT_HEADERFUNCTION callback helped to process the third-party script HTTP errors neatly:

<?
function curlHeaderCallback($resURL, $strHeader) {
    if (preg_match('/^HTTP/i', $strHeader)) {
        header($strHeader);
        header('Content-Disposition: attachment; filename="file-name.zip"');
    }
    return strlen($strHeader);
}

$strURL = 'http://www.somesite.com/script-whichs-dumps-binary-attachment.php';

$resURL = curl_init();
curl_setopt($resURL, CURLOPT_URL, $strURL);
curl_setopt($resURL, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($resURL, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback');
curl_setopt($resURL, CURLOPT_FAILONERROR, 1);

curl_exec ($resURL);

$intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE);
curl_close ($resURL);

if ($intReturnCode != 200) {
    print 'was error: ' . $intReturnCode;
}
?>
ale at desarrolloweburuguay dot com
05-May-2005 05:00
I don't know if in PHP 5+ this problem is solved, but, when I send via POST using CURLOPT_POSTFIELDS some times it doesnt work an associative array as parameter... and, if I need to send non-ascii characters (like
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571