|
 |
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();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>
|
|
curl_setopt
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(
);
$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 ,,,,etc..) this problem appears too.
The solution is to encode in a unique string all the post key=>values
Possibly this code doesnt work:
<?php
$post_data = array();
$post_data['var1'] = "Diseo web uruguay";
$post_data['var2'] = "Other string";
$url = "http://www.someurl.com/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, );
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($ch);
?>
But this works:
<?php
$post_data = array();
$post_data['var1'] = "Diseo web uruguay";
$post_data['var2'] = "Other string";
$url = "http://www.someurl.com/";
$o="";
foreach ($post_data as $k=>$v)
{
$o.= "$k=".utf8_encode($v)."&";
}
$post_data=substr($o,0,-1);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, );
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($ch);
?>
Rgds.
Alejandro Moreno.-
azcappy at azcappy dot com
23-Mar-2005 10:03
AZAds is a traffic exchange that we wrote. We wanted to come up with a way to check the UP or DOWN status of a submitted URL. Here is the solution we came up with. Can also be used for a site monitoring service.
<?
$uServer="$url";
@$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$uServer");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
@curl_exec($ch);
$errnum=curl_errno($ch);
@curl_close($ch);
if($errnum != "0") {
print "Remote Site Status: DOWN";
} else {
print "Remote Site Status: UP";
}
?>
Simply feed the URL to be tested into $url. The code will check the site and return the error code if there is one and display to appropriate message.
Hope this is useful.
Keith
www.azads.net
mcknight at chek dot com
21-Feb-2005 09:38
Another way to automate a login process and store multiple cookies for additional transfers.
(The easiest way is probably just to use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE and save them to a file. But if you need to change those cookie values or add/delete them then you can use the code below to set them.)
Continuing with Paul Ebermann's parsing function.
function parse_response($this_response)
{
// Split response into header and body sections
list($response_headers, $response_body) = explode("\r\n\r\n", $this_response, 2);
$response_header_lines = explode("\r\n", $response_headers);
// First line of headers is the HTTP response code
$http_response_line = array_shift($response_header_lines);
if(preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@',$http_response_line, $matches)) { $response_code = $matches[1]; }
// put the rest of the headers in an array
$response_header_array = array();
foreach($response_header_lines as $header_line)
{
list($header,$value) = explode(': ', $header_line, 2);
$response_header_array[$header] .= $value."\n";
}
return array("code" => $response_code, "header" => $response_header_array, "body" => $response_body);
}
// Do transfer, and make sure to include header in response
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "[login process]");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
// Parse the response message
$response = parse_response($response);
// Create the basic header
$this_header = array(
"MIME-Version: 1.0",
"Content-type: text/html; charset=iso-8859-1",
"Content-transfer-encoding: text"
);
// Add each cookie that has been returned in the response
// If cookies need to be added/deleted or value changed, then add code here
$cookies = explode("\n", $response["header"]["Set-Cookie"]);
foreach($cookies as $this_cookie) { array_push($this_header, "Cookie: ".$this_cookie); }
// Next set of transfers
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "[new transfer]");
curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
Aaron Stephanic
10-Nov-2004 09:51
The parse_response code below does not return multiple cookies as the value of 'Set-Cookie' if multiple cookies are set by the server. It appears to only return the last cookie set.
Yura Pylypenko (plyrvt at mail dot ru)
08-Oct-2004 02:10
Each example of CURLOPT_POSTFIELDS in these comments has missing urlencode() on variable values. This should be applied according to RFC1738
<?php
$vars=null;
foreach($data as $key=>$value)
if($key && $value)
$vars.=$key."=".urlencode($value)."&";
?>
Paul dot Ebermann at esperanto dot de
22-Aug-2004 08:51
I changed the parse_response() function given by "brett at brettbrewer dot com", so it now ignores 1xx-responses, which may come before the real response.
<?php
function parse_response($response){
do
{
list($response_headers,$response) = explode("\r\n\r\n",$response,2);
$response_header_lines = explode("\r\n",$response_headers);
$http_response_line = array_shift($response_header_lines);
if (preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@',$http_response_line,
$matches)) {
$response_code = $matches[1];
}
else
{
$response_code = "Error";
}
}
while (substr($response_code, 0,1) == "1");
$response_body = $response;
$response_header_array = array();
foreach ($response_header_lines as $header_line) {
list($header,$value) = explode(': ',$header_line,2);
$response_header_array[$header] = $value;
}
return array($response_code,$response_header_array,$response_body);
}
?>
raul at navenetworks dot com
21-Jul-2004 01:19
Hi!
I have found some information I am sure it could help lot of programmers when they want to connect with curl to any https website and they haven't a good or right CA Cert :)
I give you just one example It has resolved me 2 hours of my time looking for a solution.
It is simple, just if you get any error in the curl_exec (use curl_error(...) to see the error to trace it) add the next line and everything is solved:
(note: replace $ch with the right curl variable)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
<?php
$ch = curl_init();
$res= curl_setopt ($ch, CURLOPT_URL,"https://yoururl/cgi");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "Idc=si&");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$xyz = curl_exec ($ch);
curl_close ($ch);
echo $xyz;
if ($xyz == NULL) {
echo "Error:<br>";
echo curl_errno($ch) . " - " . curl_error($ch) . "<br>";
}
?>
I hope this helps.
Raul Mate Galan
Ceo Navenetworks Corp.
Note: Thanks to Ruben Lopez Gea for his help too.
ron at ttvavanti dot nl
07-May-2004 08:00
If you specify a CAINFO, note that the file must be in PEM format! (If not, it won't work).
Using Openssl you can use:
openssl x509 -in <cert> -inform d -outform PEM -out cert.pem
To create a pem formatted certificate from a binary certificate (the one you get if you download the ca somewhere).
brett at brettbrewer dot com
28-Apr-2004 07:48
I found it very annoying that cURL did not offer any easy way to extract the response headers. If you do
curl_setopt($ch, CURLOPT_HEADER, 1);
then you only get the headers output inline with the rest of your response. Here's a nice little function to parse the cURL response when you use CURLOPT_HEADER. I took it from an example on another site and turned it into a function. It assumes you're using CURLOPT_RETURNTRANSFER to return the response to some variable that is then passed to the function. You just pass it a curl_exec result and it returns the result parsed into an array with headers broken up into their correct parts.
<?php
function parse_response($response){
list($response_headers,$response_body) = explode("\r\n\r\n",$response,2);
$response_header_lines = explode("\r\n",$response_headers);
$http_response_line = array_shift($response_header_lines);
if (preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@',$http_response_line,
$matches)) {
$response_code = $matches[1];
}
$response_header_array = array();
foreach ($response_header_lines as $header_line) {
list($header,$value) = explode(': ',$header_line,2);
$response_header_array[$header] = $value;
}
return array($response_code,$response_header_array,$response_body);
}
?>
Jakub Horky <jakub dot php at horky dot net>
04-Apr-2004 01:20
A bit more documentation (without minimum version numbers):
- CURLOPT_WRITEFUNCTION
- CURLOPT_HEADERFUNCTION
Pass a function which will be called to write data or headers respectively. The callback function prototype:
long write_callback (resource ch, string data)
The ch argument is CURL session handle. The data argument is data received. Note that its size is variable. When writing data, as much data as possible will be returned in all invokes. When writing headers, exactly one complete header line is returned for better parsing.
The function must return number of bytes actually taken care of. If that amount differs from the amount passed to this function, an error will occur.
- CURLOPT_READFUNCTION
Pass a function which will be called to read data. The callback function prototype:
string read_callback (resource ch, resource fd, long length)
The ch argument is CURL session handle. The fd argument is file descriptor passed to CURL by CURLOPT_INFILE option. The length argument is maximum length which can be returned.
The function must return string containing the data which were read. If length of the data is more than maximum length, it will be truncated to maximum length. Returning anything else than a string means an EOF.
[Note: there is more callbacks implemented in current cURL library but they aren't unfortunately implemented in php curl interface yet.]
me
14-May-2003 09:36
Just a reminder: When setting your CURLOPT_POSTFIELDS remember to replace the spaces in your values with %20
joeldegan AT yahoo.com
24-Feb-2003 01:38
Often times people ask about how to get data from secure servers.
Here is an example of getting the balance page from Paypal
<?
function GetCurlPage ($pageSpec) {
$agent = "up.b";
$header[] = "Accept: text/vnd.wap.wml,*.*";
$ch = curl_init($pageSpec);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cook");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cook");
$tmp = curl_exec ($ch);
curl_close ($ch);
return $tmp;
}
function PostCurlPage ($pageSpec, $data) {
$agent = "up.b";
$header[] = "Accept: text/vnd.wap.wml,*.*";
$ch = curl_init($pageSpec);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cook");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cook");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$tmp = curl_exec ($ch);
curl_close ($ch);
return $tmp;
}
$first = GetCurlPage("https://www.paypal.com/cgi-bin/phscr?cmd=login");
$exp = explode("=", $first);
$id = explode("\"", $exp[16]);
$second = PostCurlPage("https://www.paypal.com/cgi-bin/phscr?rs=".$id[0], "email=EMAIL@HOST.COM&pass=YOUR_PP_PASS&cmd=login-submit-pass");
echo $second."\n\n";
?>
yann dot corno at free dot fr
13-Nov-2002 04:19
About the CURLOPT_HTTPHEADER option, it took me some time to figure out how to format the so-called 'Array'. It fact, it is a list of strings. If Curl was already defining a header item, yours will replace it. Here is an example to change the Content Type in a POST:
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
Yann
23-Oct-2002 12:04
beware that not all cURLlib constants are supported under php :
e.g. CURLOPT_PROGRESSFUNCTION or CURLOPT_WRITEDATA are not supported.
CURLOPT_WRITEFUNCTION, although undocumented is supported. It takes the name of a user_defined function.
the function should take two arguments (the curl handle, and the inputdata) and return the length of the written data
e.g.
function myPoorProgressFunc($ch,$str){
global $fd;
$len = fwrite($fd,$str);
print("#");
return $len;
}
curl_setopt($ch,CURLOPT_WRITEFUNCTION,"myPoorProgressFunc");
Also be aware that CURLOPT_WRITEFUNCTION does NOT take the CURLOPT_FILE as a parameter!
in curl lib it would take CURLOPT_WRITEDATA but this is not supported by php; that's why I use "global $fd;" in my exemple function.
CURLOPT_HEADERFUNCTION works the same, and is guaranteed to receive complete header lines as input!
Hope this helps
Ivan
m dot fische at gmx dot net
08-Oct-2002 03:42
note: if your option comes from a variable eg:
$option = "CURLOPT_RETURNTRANSFER";
$value = "1";
this will fail:
curl_setopt($ch,$option,$value);
because the curl option is a constant.
use the function constant() to get the value:
curl_setopt($ch,constant($option),$value);
mrcheezy at hotmail dot com
13-Sep-2002 02:34
If you set return transfer to 1 and are sending a post form and find that this crashes php try setting follow location to 1 also. I'm not exactly sure why this crashed, but after i used follow it stopped.
curl_setopt ($sess, CURLOPT_FOLLOWLOCATION, '1');
curl_setopt ($sess, CURLOPT_RETURNTRANSFER, '1');
paul at zgtec dot com
26-Aug-2002 02:31
To make a POST in multipart/form-data mode
this worked for me, the " \n" at the end of the variables was very important on my OS X server.
<?php
$file = "file_to_upload.txt";
$submit_url = "http://www.url_to_upload_to.com/upload_page.php";
$formvars = array("cc"=>"us \n");
$formvars[variable_1] = "bla bla \n";
$formvars[variable_2] = "bla bla \n";
$formvars[variable_3] = "bla bla \n";
$formvars[variable_4] = "bla bla \n";
$formvars[upfile] = "@$file"; $ch = curl_init($submit_url);
curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt"); curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt"); curl_setopt($ch, CURLOPT_REFERER, "http://www.last_url_for_referer_logs.com"); curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $formvars);
echo $pnp_result_page = curl_exec($ch);
curl_close ($ch);
?>
jckim at iquick4u dot com
15-Apr-2002 08:05
#!/usr/local/bin/php -q
<?php
$id = "xxxx";
$pw = "xxxx";
$LOGINURL = "http://login.daum.net/Mail-bin/login.cgi";
$GETURL = "http://www.daum.net/Mail-bin/mail_list";
$POSTFIELDS = "id=$id&pw=$pw";
function AUTH_SITE_COOKIE_STORE($LOGINURL,$POSTFIELDS)
{
$parseURL = parse_url($LOGINURL);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "$parseURL[host].cookie");
curl_setopt($ch, CURLOPT_URL,"$LOGINURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "$POSTFIELDS");
ob_start();
curl_exec ($ch);
ob_end_clean();
curl_close ($ch);
return "$parseURL[host].cookie";
}
function AUTH_SITE_GET($GETURL,$cookieFile)
{
$parseURL = parse_url($GETURL);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "$cookieFile");
curl_setopt($ch, CURLOPT_URL,"$GETURL");
$result = curl_exec ($ch);
curl_close ($ch);
$fp = fopen ("$parseURL[host].html", "w");
fwrite($fp,$result);
fclose ($fp);
return $result;
}
$cookieFile = AUTH_SITE_COOKIE_STORE($LOGINURL,$POSTFIELDS);
echo $result = AUTH_SITE_GET($GETURL,$cookieFile);
?>
tychay at alumni dot caltech dot edu
03-Apr-2002 01:14
CURLOPT_HTTPHEADER is NOT like the -H command line switch. The command line switch adds or replaces headers (much like the header() line in PHP, but for HTTP clients instead of servers), but the curl extension will eliminate the headers cURL sends by default.
For instance, your Authorization, Host, Referer, Pragma, and Accept headers which are normally written by default or by other CURLOPT_*'s.
Also, it might seem intuitive that this should accept an array hash of header->values, but this is not the case. It accepts an array of strings of the format "Header: Value", much like the -H command-line switch.
Hope this helps,
terry
asmith at crawlspace dot com
28-Feb-2002 07:18
It's possible to take advantage of multiple URLs on the same host in one curl_exec transaction ... just use multiple instances of CURLOPT_URL.
Example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://foo.com/a.html");
curl_setopt($ch, CURLOPT_URL, "http://foo.com/b.html");
curl_setopt($ch, CURLOPT_URL, "http://foo.com/c.html");
curl_exec($ch);
curl_close($ch);
... the URLs appear to be hit in the same order they are entered. This takes advantage of cURL's Persistant Connection capability if all the URLs are on the same host!
bvwj at swbell dot net
18-Dec-2001 01:35
To collect cookies recieved with a request, set CURLOPT_COOKIEJAR "cookieFileName". Then use CURLOPT_COOKIEFILE "cookieFileName" to recall them in subsequent transactions.
22-Sep-2001 09:52
To make a POST in multipart/form-data mode
(to upload a file for example) you can use
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);
where $post is an array :
$post['key1'] = 'data1'
// like a text field in a POST
$post['file1'] = '@filename1'
// upload filename1
For more informations see the
curl_formparse man page.
sr2899.at.hotmail.com
14-May-2001 02:00
CURLOPT_RETURNTRANSFER has the interesting behaviour of tacking a null char onto the end of the string. This null char is actually on the end of the php string, and can cause some odd results if you're not expecting it to be there.
fil at rezox dot com
21-Feb-2001 05:50
If you want to connect to a secure server for posting info/reading info, you need to make cURL with the openSSL options. Then the sequence is nearly identical to the previous example (except http_S_://, and possibly add the useragent):
curl_setopt($ch, CURLOPT_URL,"https://secure.website.com");
//some sites only accept your request if your browser looks legit, so send a useragent profile...
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
bvr at xs4all dot nl
07-Feb-2001 07:09
If you'd like to include extra headers in your POST request, you can accomplish this by setting the following option:
CURLOPT_HTTPHEADER
This is similar to the CURL -H command line switch.
Thanks to Daniel Stenberg for pointing out this usefull feature!
Note: this option was first supported in PHP version 4.03 .
awestholm at imail dot usi dot net
25-Jan-2001 11:33
Just because the docs are rather sparse on this, to set multiple values in a cookie, you separate them with a semicolon, as usual. An example, yo set j to j and k to k:
curl_setopt($ch,CURLOPT_COOKIE,"j=j;k=k");
-- Alex
| |