文字

cURL 函数

Table of Contents

  • curl_close — 关闭一个cURL会话
  • curl_copy_handle — 复制一个cURL句柄和它的所有选项
  • curl_errno — 返回最后一次的错误号
  • curl_error — 返回一个保护当前会话最近一次错误的字符串
  • curl_escape — 使用 URL 编码给定的字符串
  • curl_exec — 执行一个cURL会话
  • curl_file_create — 创建一个 CURLFile 对象
  • curl_getinfo — 获取一个cURL连接资源句柄的信息
  • curl_init — 初始化一个cURL会话
  • curl_multi_add_handle — 向curl批处理会话中添加单独的curl句柄
  • curl_multi_close — 关闭一组cURL句柄
  • curl_multi_exec — 运行当前 cURL 句柄的子连接
  • curl_multi_getcontent — 如果设置了CURLOPT_RETURNTRANSFER,则返回获取的输出的文本流
  • curl_multi_info_read — 获取当前解析的cURL的相关传输信息
  • curl_multi_init — 返回一个新cURL批处理句柄
  • curl_multi_remove_handle — 移除curl批处理句柄资源中的某个句柄资源
  • curl_multi_select — 等待所有cURL批处理中的活动连接
  • curl_multi_setopt — 为 cURL 并行处理设置一个选项
  • curl_multi_strerror — Return string describing error code
  • curl_pause — Pause and unpause a connection
  • curl_reset — Reset all options of a libcurl session handle
  • curl_setopt_array — 为cURL传输会话批量设置选项
  • curl_setopt — 设置一个cURL传输选项
  • curl_share_close — Close a cURL share handle
  • curl_share_init — Initialize a cURL share handle
  • curl_share_setopt — Set an option for a cURL share handle.
  • curl_strerror — Return string describing the given error code
  • curl_unescape — 解码给定的 URL 编码的字符串
  • curl_version — 获取cURL版本信息

用户评论:

[#1] helmizz at yahoo dot com [2014-05-11 10:03:35]

This is sample script to use curl, Just input curl_setopt,
exp : 
curlsetop[0] ==> name : CURLOPT_URL ; value : http://amazon.com
curlsetop[1] ==> name : CURLOPT_RETURNTRANSFER ; value : true
curlsetop[2] ==> name : CURLOPT_FOLLOWLOCATION ; value : true

You can add form input.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="">
  <meta name="Author" content="Helmi Anwar">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>

 <body>

 <form method="post" action="">
<table>
<tr class="rowid_add">
<td>curl_setopt [0]</td>
<td>Name : <input type="text" size="50" name="setopt_name[]"></td>
<td>Value :<input type="text" size="50" name="setopt_value[]"></td>
</tr>
<tr class="rowid_add">
<td>curl_setopt [0]</td>
<td>Name : <input type="text" size="50" name="setopt_name[]"></td>
<td>Value :<input type="text" size="50" name="setopt_value[]"></td>
</tr>
<tr class="rowid_add">
<td>curl_setopt [0]</td>
<td>Name : <input type="text" size="50" name="setopt_name[]"></td>
<td>Value :<input type="text" size="50" name="setopt_value[]"></td>
</tr>
<tr>
<td><input type="submit" name="submit_yes" value="EXECUTE"></td>
</tr>
</table>
 </form>

 
  <?php

    
function curl_test($setopt_content)
    {
        
$ch curl_init();
        
curl_setopt_array($ch$setopt_content);
        
$result_data curl_exec($ch);
        
curl_close($ch);
        return 
$result_data;
    }

if(
$_REQUEST['submit_yes']=="EXECUTE")
{
    
    foreach (
$_REQUEST['setopt_name'] as $k => $index_content
    {    
        
$value_content=$_REQUEST['setopt_value'][$k];
        
$index_content =strtoupper($index_content);
        eval(
'$index_content = '.$index_content.';');
        
//echo ($index_content);
        
if($index_content!='')
        {
            if(
strtoupper($value_content)=='TRUE')
            {
$setopt_content[$index_content]=TRUE;}
            elseif(
strtoupper($value_content)=='FALSE')
            {
$setopt_content[$index_content]=FALSE;}
            else
            {
$setopt_content[$index_content]=$value_content;}
        }
    }

    
$info=curl_test($setopt_content);

}

 
?>

 <textarea name="result" rows="25" cols="100"> <?php echo htmlspecialchars($info);?> </textarea>
 </body>
</html>

[#2] Emprivo.com [2009-08-26 09:58:28]

Fixed bugs in the function posted earlier (better javascript redirect following and now supports HTTPS)

<?php


function get_url$url,  $javascript_loop 0$timeout )
{
    
$url str_replace"&amp;""&"urldecode(trim($url)) );

    
$cookie tempnam ("/tmp""CURLCOOKIE");
    
$ch curl_init();
    
curl_setopt$chCURLOPT_USERAGENT"Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
    
curl_setopt$chCURLOPT_URL$url );
    
curl_setopt$chCURLOPT_COOKIEJAR$cookie );
    
curl_setopt$chCURLOPT_FOLLOWLOCATIONtrue );
    
curl_setopt$chCURLOPT_ENCODING"" );
    
curl_setopt$chCURLOPT_RETURNTRANSFERtrue );
    
curl_setopt$chCURLOPT_AUTOREFERERtrue );
    
curl_setopt$chCURLOPT_SSL_VERIFYPEERfalse );    # required for https urls
    
curl_setopt$chCURLOPT_CONNECTTIMEOUT$timeout );
    
curl_setopt$chCURLOPT_TIMEOUT$timeout );
    
curl_setopt$chCURLOPT_MAXREDIRS10 );
    
$content curl_exec$ch );
    
$response curl_getinfo$ch );
    
curl_close $ch );

    if (
$response['http_code'] == 301 || $response['http_code'] == 302)
    {
        
ini_set("user_agent""Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");

        if ( 
$headers get_headers($response['url']) )
        {
            foreach( 
$headers as $value )
            {
                if ( 
substrstrtolower($value), 0) == "location:" )
                    return 
get_urltrimsubstr$value9strlen($value) ) ) );
            }
        }
    }

    if (    ( 
preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i"$content$value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i"$content$value) ) &&
            
$javascript_loop 5
    
)
    {
        return 
get_url$value[1], $javascript_loop+);
    }
    else
    {
        return array( 
$content$response );
    }
}

?>

[#3] Peter X. [2008-05-02 19:44:23]

Although it has been noted that cURL outperforms both file_get_contents and fopen when it comes to getting a file over a HTTP link, the disadvantage of cURL is that it has no way of only reading a part of a page at a time.

For example, the following code is likely to generate a memory limit error:

<?php
$ch 
curl_init("http://www.example.com/reallybigfile.tar.gz");
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_BINARYTRANSFERtrue);
$output curl_exec($ch);

$fh fopen("out.tar.gz"'w');
fwrite($fh$output);
fclose($fh);
?>


While this, on the other hand, wouldn't

<?php
$hostfile 
fopen("http://www.example.com/reallybigfile.tar.gz"'r');
$fh fopen("out.tar.gz"'w');

while (!
feof($hostfile)) {
    
$output fread($hostfile8192);
    
fwrite($fh$output);
}
    
fclose($hostfile);
fclose($fh);
?>

[#4] Mr.KTO [2007-07-07 06:59:18]

Don't foget to curl_close($ch); Even if curl_errno($ch) != 0

Because if you don't - on Windows this will produce windows-error-report (Program terminated unexpectedly)

[#5] killermonk at REMOVE dot killermonk dot com [2007-03-06 11:23:15]

For anyone trying to use cURL to submit to an ASP/ASPX page that uses an image as the submit button.

Make sure that you have 'button_name.x' and 'button_name.y' in the post fields. PHP names these fields 'button_name_x' and 'button_name_y', while ASP uses a dot.

Also, as noted above, be sure to include the '__VIEWSTATE' input field in your post request.

[#6] gordon_e_rouse at yahoo dot com dot au [2007-01-25 14:24:00]

Using curl to take snapshots of the current page for emailing the HTML is a clever little idea. (ie: Email this page to a friend)

<?php
//to be explained below!
session_write_close();

$pageurl "http://www.site.com/content.php?PHPSESSID=123XYZ
curl_setopt(
$ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt (
$ch, CURLOPT_URL, $pageurl ); 
$html = curl_exec ( $ch );
curl_close(
$ch);

//then you need to fix pathing to absolute
$search = "/(src|href|background)=\"[^:,^>,^\"]*\"/i";

preg_match_all $search$html$a_matches );

//you can figure out the rest ! but thought the reg expression is useful as well
?>


But here is the catch, you may want to make sure curl connects to the server under the same session as the browser. So naturally you pass the session cookie through the curl system either by the cookie jar system, or through the query string in the path.

This is where you will get stuck. PHP will need write access to the same session file simultaneously!! causing serious hanging issues!

This is why you should close off your session before you make curl take a page snapshot!

[#7] galvao at galvao.eti.br [2006-07-06 20:27:44]

Note that on Win32 this documentation can get a little confusing.

In order to get this to work you need to:

1) Be sure that the folder where libeay32.dll and ssleay32.dll - tipically C:\\PHP - is present on the PATH variable.

2) Uncomment - remove the semi-colon - the line that says "extension=php_curl.dll" from php.ini

3) Restart the webserver (you should already know this one, but...)

It took me some time to realize this, since this page doesn't mention the need to uncomment that php.ini's line.

[#8] richardkmiller AT gmail [2006-03-02 16:21:16]

Beware of any extra spaces in the URL.  A trailing space in the URL caused my script to fail with the message "empty reply from server".

[#9] stevehartken at hotmail dot com [2006-02-21 22:40:01]

I had the following experience when harvesting urls with a get variable from a page using cUrl. HTML pages will output ampersands as &amp when the page is read by the curl function. 

If you code a script to find all hyperlinks, it will use &amp instead of &, especially using a regular expression search.

It is hard to detect because when you output the url to the browser it renders the html. To fix, add a line to replace the &amp with &.

<?php
function processURL($url){
    
$url=str_replace('&amp;','&',$url);
    
$ch=curl_init();
    
curl_setopt($chCURLOPT_URL$url);
    
curl_setopt ($chCURLOPT_RETURNTRANSFER1);
    
$xml curl_exec ($ch);
    
curl_close ($ch);
    echo 
$xml;
}
?>

[#10] mikeb[at]xamo[dot]com [2004-10-14 13:11:07]

A note of warning for PHP 5 users: if you try to fetch the CURLINFO_CONTENT_TYPE using curl_getinfo when there is a connect error, you will core dump PHP. I have informed the Curl team about this, so it will hopefully be fixed soon. Just make sure you check for an error before you look for this data.

[#11] alidrus at langkah dot com [2004-09-14 02:31:13]

In recent versions of php, CURLOPT_MUTE has (probably) been deprecated. Any attempt of using curl_setopt() to set CURLOPT_MUTE will give you a warning like this:

PHP Notice:  Use of undefined constant CURLOPT_MUTE - assumed 'CURLOPT_MUTE' in ....

If you wish tu silence the curl output, use the following instead:

<?php
    curl_setopt
($chCURLOPT_RETURNTRANSFERtrue);
?>


And then,

<?php
    $curl_output
=curl_exec($ch);
?>


The output of the curl operation will be stored as a string in $curl_output while the operation remains totally silent.

[#12] rich @ richud dot com [2004-06-11 07:12:46]

If you have upgraded to using thread safe PHP (with apache 2 MPM=worker) note that
CURLOPT_COOKIEJAR / CURLOPT_COOKIEFILE both need an absolute path set for the cookie file location and no longer take a relative path. 
(As before, also remember to have set correct permissions to allow a writeable cookie file/dir by apache)
[php 4.3.7/apache v2.0.49]

[#13] simon [at] vhostdirect [dot] co [dot] uk [2004-03-03 16:53:41]

It took me quite some to to figure out how to get Curl (with SSL), OpenSSL and PHP to play nicely together.

After reinstalling MS-VC7 and compiling OpenSSL to finally realise this was'nt nesscary.

If your like me and like *Nix systems more than Windows then you'll most probly have similar problems.

I came across this, on a simple google with the right keywords.

http://www.tonyspencer.com/journal/00000037.htm

I read thru that and found my mistake.

Its just a small list of notes, I found them to be the best I've found on the subject and the most simplist.

Dont forget to add a simple line like this into your scripts to get them working on Win32.

<?php
if($WINDIRcurl_setopt($curlCURLOPT_CAINFO"c:\\windows\\ca-bundle.crt");
?>


Last note: ca-bundle.crt file is located in the Curl download. I stored mine in the windows directory and apache/php can access it fine.

All the best and I hope this helps.

Simon Lightfoot
vHost Direct Limited

上一篇: 下一篇: