curl_setopt--Sets an option for the curl call
Describe
BOOL curl_setopt (INT-ch, string option, mixed value)
The curl_setopt () function sets the option for a curl session. The option parameter is the setting you want, and value is the values given by this choice.
The values of the following options will be used as long reshaping (specified in the option argument):
Curlopt_infilesize: When you upload a file to a remote site, this option tells PHP the size of the file you uploaded.
Curlopt_verbose: If you want to curl report every unexpected thing, set this option to a value other than 0.
Curlopt_header: If you want to include a header in the output, set this option to a value other than 0.
Curlopt_noprogress: If you don't have PHP to display a process bar for curl transmissions, set this option to a non 0 value.
Note: PHP automatically sets this option to a value other than 0, and you should only change this option for debugging purposes.
Curlopt_nobody: If you don't want to include the body part in the output, set this option to a value other than 0.
Curlopt_failonerror: If you want PHP to be in error (HTTP code returns greater than or equal to 300), do not display, set this option to a person not 0 value. The default behavior is to return a normal page, ignoring the code.
Curlopt_upload: If you want PHP to be ready for upload, set this option to a value other than 0.
Curlopt_post: If you want PHP to do a regular HTTP POST, set this option to a non 0 value. This post is an ordinary application/x-www-from-urlencoded type, most of which is used by HTML forms.
Curlopt_ftplistonly: Set this option to a value other than 0, PHP will list the list of directory names for FTP.
Curlopt_ftpappend: Set this option to a value other than 0, PHP will apply the remote file instead of overwriting it.
CURLOPT_NETRC: Set this option to a value other than 0, PHP will find the username and password of the remote site you want to connect to in your ~./netrc file.
Curlopt_followlocation: Set this option to a non-0 value (like ' Location: '), the server will send it as a part of the HTTP header (note that this is recursive, PHP will send the shape like ' Location: ' head).
Curlopt_put: Set this option for a non 0 value to upload a file with HTTP. To upload this file, you must set the Curlopt_infile and Curlopt_infilesize options.
Curlopt_mute: Set this option to a value other than 0, PHP will be completely silent for the curl function.
Curlopt_timeout: Sets a long shaping number, as the maximum continuation of how many seconds.
Curlopt_low_speed_limit: Sets a long shaping number to control how many bytes are transferred.
Curlopt_low_speed_time: Set a long shaping number, control how many seconds to transfer curlopt_low_speed_limit The specified number of bytes.
Curlopt_resume_from: Passes a long shaping parameter that contains the byte offset address (the start form you want to transfer to).
Curlopt_sslversion: Passes a long parameter containing the SSL version. The default PHP will be determined by its own efforts, and in more security you must set it manually.
Curlopt_timecondition: Passes a long parameter specifying how to handle the Curlopt_timevalue parameter. You can set this parameter to Timecond_ifmodsince or timecond_isunmodsince. This is for HTTP only.
Curlopt_timevalue: Passes a number of seconds from 1970-1-1 to the present. This time is used by the Curlopt_timevalue option as the specified value or by default timecond_ifmodsince.
The values of the following options will be used as strings:
Curlopt_url: This is the URL you want to retrieve with PHP. You can also set this option when initializing with the Curl_init () function.
Curlopt_userpwd: Pass a string in a form like [Username]:[password] style, the function of PHP to connect.
Curlopt_proxyuserpwd: Passes a string in a form like [Username]:[password] to connect to the HTTP proxy.
Curlopt_range: Pass a range that you want to specify. It should be an ' x-y ' format, X or Y is excepted. HTTP transmissions also support several intervals, separated by a x-y,n-m.
Curlopt_postfields: Passes a string of all data that is an HTTP "POST" operation.
Curlopt_referer: Contains a string of ' REFERER ' headers in the HTTP request.
Curlopt_useragent: Contains a string of ' user-agent ' headers in the HTTP request.
Curlopt_ftpport: Passes an IP address that contains the ftp ' POST ' instruction. This post instruction tells the remote server to connect to the IP address we specified. This string can be an IP address, a host name, a network interface name (under Unix), or '-' (using the system default IP address).
Curlopt_cookie: Passes a header connection that contains an HTTP COOKIE.
Curlopt_sslcert: Passes a string containing the PEM format certificate.
CURLOPT_SSLCERTPASSWD: Passes a password that is required to use the Curlopt_sslcert certificate.
Curlopt_cookiefile: A string that passes the name of a file that contains cookie data. This cookie file can be in Netscape format, or in the HTTP style header that is stockpiled in the file.
Curlopt_customrequest: When making an HTTP request, passing a character is used by get or head. It is useful for delete or other operations, more pass a string of used instead of a and head when doing a HTTP request. This is useful to doing or another, more obscure, HTTP request.
Note: Do not do this before confirming your server support command.
The following options require a file description (obtained by using the fopen () function):
Curlopt_file: This file will be the output file where you put the transfer, and the default is stdout.
Curlopt_infile: This file is the input file you sent over.
Curlopt_writeheader: This file is written with the head part of your output.
Curlopt_stderr: This file is written with errors, not STDERR.
Instance
<?php Tutorial
@header ("Expires:mon, June June 1997 05:00:00 GMT"); Date in the past
@header ("last-modified:"). Gmdate ("D, D M Y h:i:s"). "GMT");
Always modified
@header ("Cache-control:no-store, No-cache, must-revalidate"); http/1.1
@header ("Cache-control:post-check=0, pre-check=0", false);
@header ("Pragma:no-cache");
@header ("content-type:text/html; Charset=utf-8 ");
$url = ' http://s.111cn.net ';
$querystring = $_server["Query_string"];
$CURRENTURL = $_server[' server_name '];
if ($querystring!= ') $querystring = $querystring. "&";
$querystring = $querystring. "Siteurl=". $CURRENTURL;
if ($querystring!= ')
{
$url = $url. "?" . $querystring;
}
$ch = Curl_init ();
$timeout = 60; Set to zero for no timeout
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_connecttimeout, $timeout);
$handles = curl_exec ($ch);
Here is the replacement, which can be combined with server pseudo static settings
$handles = Preg_replace ("/?page=" ([0-9]+) &categoryid= ([0-9]+)/I, "/fenlei/category-$1-$2.html", $handles);
$handles = Preg_replace ("/?categoryid=" ([0-9]+)/I, "/fenlei/category--$1.html", $handles);
$handles = Preg_replace ("/?page=" ([0-9]+)/I, "/fenlei/category-$1.html", $handles);
$handles = preg_replace ("/infodetail.asp tutorial x?id= ([0-9]+)/I", "/fenlei/$1.html", $handles);
$handles = Str_replace ("infolist.aspx", "/fenlei/index.html", $handles);
$handles = Str_replace ("unionlist.aspx", "unionlist.html", $handles);
Echo $handles;
?>
Why do you use CURL?
Yes, we can get the content of the webpage by other means. Most of the time, because I want to be lazy, I use simple PHP functions directly:
$content = file_get_contents ("http://www.111cn.net");
Or
$lines = File ("Http://www.111cn.net");
Or
ReadFile (http://www.111cn.net);
However, this approach lacks flexibility and effective error handling. Also, you can't use it to do some difficult tasks-such as processing coockies, validation, form submission, file uploads, and so on.
Reference:
CURL is a powerful library that supports many different protocols, options, and provides various details about URL requests.
Basic structure
Before you learn more complex features, take a look at the basic steps in creating a Curl request in PHP:
Class
Setting variables
Execute and get results
Release Curl handle
1. Class
$ch = Curl_init ();
2. Setting options, including URLs
curl_setopt ($ch, Curlopt_url, "http://www.111cn.net");
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_header, 0);
3. Execute and get the contents of the HTML document
$output = curl_exec ($ch);
4. Release Curl handle
Curl_close ($ch);
The second step (i.e. curl_setopt ()) is the most important, and all mysticism is here. There is a long string of curl parameters that can be set to specify the details of the URL request. It may be difficult to read it all at once and understand it, so today we'll just try the more common and useful options.
Check for errors
You can add an error-checking statement (although this is not required):
// ...
$output = curl_exec ($ch);
if ($output = = FALSE) {
echo "CURL Error:". Curl_error ($ch);
}
// ...
Note that when comparing, we use "= = False" instead of "= = False". Because we have to distinguish between null output and Boolean value false, the latter is the real error.
Get information
// ...
Curl_exec ($ch);
$info = Curl_getinfo ($ch);
Echo ' Get '. $info [' url ']. ' Time consuming '. $info [' Total_time ']. ' Seconds ';
// ...
The following information is included in the returned array:
"url"//Resource Network Address
"Content_Type"//Content encoding
"Http_code"//http status code
Size of the "header_size"//header
Size of "request_size"//Request
"FILETIME"//File creation time
"Ssl_verify_result"//ssl validation results
"Redirect_count"//Jump Technology
"Total_time"/Total time consuming
"Namelookup_time"//dns query time consuming
"Connect_time"/Waiting for connection time consuming
"Pretransfer_time"//Pre-transport preparation time consuming
Size of "size_upload"//Uploading data
Size of "size_download"//Download Data
"Speed_download"//download speed
"Speed_upload"//upload speed
Length of "download_content_length"//download content
"Upload_content_length"//Length of uploaded content
"Starttransfer_time"//Time to start transmission
"Redirect_time"//redirect time consuming
Browser-based redirection
In the first example, we will provide a piece of code to detect if the server has browser-based redirection. For example, some sites redirect Web pages based on whether they are mobile browsers or even where users come from.
We use the Curlopt_httpheader option to set the HTTP request header information (HTTP headers) that we send out, including the user agent information and the default language. Then we'll see if these specific sites will redirect us to different URLs.
The URL for the test
$urls = Array (
"Http://www.cnn.com",
"Http://www.mozilla.com",
"Http://www.facebook.com"
);
Browser Information for testing
$browsers = Array (
"Standard" => Array (
"User_agent" => "mozilla/5.0" (Windows; U Windows NT 6.1; En-us; rv:1.9.1.6) gecko/20091201 firefox/3.5.6 (. NET CLR 3.5.30729) ",
"Language" => "en-us,en;q=0.5"
),
"iphone" => Array (
"User_agent" => "mozilla/5.0" (IPhone; U CPU like Mac OS X; EN) applewebkit/420+ (khtml, like Gecko) version/3.0 mobile/1a537a safari/419.3 ",
"Language" => "en"
),
"French" => Array (
"User_agent" => "mozilla/4.0" (compatible; MSIE 7.0; Windows NT 5.1; GTB6. NET CLR 2.0.50727) ",
"Language" => "fr,fr-fr;q=0.5"
)
);
foreach ($urls as $url) {
echo "URL: $urln";
foreach ($browsers as $test _name => $browser) {
$ch = Curl_init ();
Set URL
curl_setopt ($ch, Curlopt_url, $url);
Set a specific header for a browser
curl_setopt ($ch, Curlopt_httpheader, Array (
' User-agent: {$browser [' user_agent ']} ',
' Accept-language: {$browser [' Language ']} '
));
Page content We don't need
curl_setopt ($ch, curlopt_nobody, 1);
Just return the HTTP header
curl_setopt ($ch, Curlopt_header, 1);
Return the result rather than output it
curl_setopt ($ch, Curlopt_returntransfer, 1);
$output = curl_exec ($ch);
Curl_close ($ch);
Do you have redirected HTTP header information?
if (Preg_match) ("! Location: (. *)! ", $output, $matches)) {
echo "$test _name:redirects to $matches [1]n];
} else {
echo "$test _name:no redirectionn";
}
}
echo "NN";
}
First, we create a set of URLs that need to be tested, and then specify a set of browser information that needs to be tested. Finally, a loop tests the possible scenarios for various URLs and browser matches.
Because we specify the Curl option, the returned output includes only HTTP header information (stored in $output). Using a simple regular, we check whether the header information contains the word "Location:".
Running this code should return the following results:
Send data by post method
When a GET request is initiated, the data can be passed to a URL through a query string. For example, when searching in Google, the search key is part of the query string for the URL:
Http://www.google.com/search?q=nettuts
In this case you may not need curl to simulate. Throw this URL to "file_get_contents ()" To get the same result.
However, there are some HTML forms that are submitted using the Post method. When this form is submitted, the data is sent through the HTTP request body, not the query string. For example, when using the CodeIgniter forum form, no matter what keyword you enter, it is always post to the following page:
http://codeigniter.com/forums/do_search/
You can use PHP scripts to simulate this URL request. First, create a new file that will accept and display the post data, and we'll name it post_output.php:
Print_r ($_post);
Next, write a PHP script to execute the Curl request:
$url = "http://localhost/post_output.php";
$post _data = Array (
"foo" => "Bar",
"Query" => "Nettuts",
"Action" => "Submit"
);
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, Curlopt_returntransfer, 1);
We are in post data Oh!
curl_setopt ($ch, Curlopt_post, 1);
Add a post variable to the
curl_setopt ($ch, Curlopt_postfields, $post _data);
$output = curl_exec ($ch);
Curl_close ($ch);
Echo $output;
After the code is executed, you should get the following results:
This script sends a POST request to post_output.php, the page $_post the variable and returns, and we use curl to capture the output.
File Upload
The upload file is very similar to the previous post. Because all file upload forms are submitted through the Post method.
First, create a new page that receives the file named upload_output.php:
Print_r ($_files);
Here's the script that actually performs the file upload task:
$url = "http://localhost/upload_output.php";
$post _data = Array (
"foo" => "Bar",
The local file address to upload
"Upload" => "@c:/wamp/www/test.zip"
);
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_post, 1);
curl_setopt ($ch, Curlopt_postfields, $post _data);
$output = curl_exec ($ch);
Curl_close ($ch);
Echo $output;
If you need to upload a file, just pass the file path like a post variable, but remember to precede it with the @ symbol. Executing this script should have the following output:
CURL Batch processing (multi CURL)
Curl also has an advanced feature-batch handle (handle). This feature allows you to open multiple URL connections simultaneously or asynchronously.
Here is the sample code from Php.net:
Create two Curl Resources
$ch 1 = curl_init ();
$ch 2 = Curl_init ();
Specify the URL and appropriate parameters
curl_setopt ($ch 1, Curlopt_url, "http://lxr.php.net/");
curl_setopt ($ch 1, curlopt_header, 0);
curl_setopt ($ch 2, Curlopt_url, "http://www.php.net/");
curl_setopt ($ch 2, Curlopt_header, 0);
Create a Curl batch handle
$MH = Curl_multi_init ();
Plus the front two resource handles
Curl_multi_add_handle ($MH, $ch 1);
Curl_multi_add_handle ($MH, $ch 2);
Predefined one State variable
$active = null;
Perform batch processing
do {
$MRC = Curl_multi_exec ($MH, $active);
while ($MRC = = Curlm_call_multi_perform);
while ($active && $MRC = = CURLM_OK) {
if (Curl_multi_select ($MH)!=-1) {
do {
$MRC = Curl_multi_exec ($MH, $active);
while ($MRC = = Curlm_call_multi_perform);
}
}
Close individual handles
Curl_multi_remove_handle ($MH, $ch 1);
Curl_multi_remove_handle ($MH, $ch 2);
Curl_multi_close ($MH);
The thing to do here is to open multiple curl handles and assign them to a batch handle. Then you just have to wait for it to execute in a while loop.
There are two major loops in this example. The first do-while loop repeats the call to Curl_multi_exec (). This function is free of partition (non-blocking), but executes as little as possible. It returns a state value, as long as the value equals constant curlm_call_multi_perform, which means there is still work to be done (for example, to send HTTP headers to the corresponding URL). That is, we need to keep calling the function until the return value changes.
The next while loop, only continues when the $active variable is true. This variable was passed to Curl_multi_exec () as the second argument, representing whether there are active connections in the batch handle as well. Next, we call Curl_multi_select (), which is "masked" before the active connection (for example, receiving a server response) appears. Once this function is executed successfully, we go into another do-while loop and continue to the next URL.
Let's take a look at how to put this function into practice:
WordPress Connection Checker
Imagine you have a blog with a large number of articles that contain a lot of links to external websites. After a while, for that reason, a significant number of these links are invalidated. Either be harmonious, or the whole site has been Kung Fu network ...
Let's create a script that analyzes all of these links, finds sites/pages that are not open or 404, and generates a report.
Please note that the following is not a really available WordPress plugin, just a standalone function of the script, only for demonstration, thank you.
All right, let's go. First, read all of these links from the database tutorial:
CONFIG
$db _host = ' localhost ';
$db _user = ' root ';
$db _pass = ';
$db _name = ' WordPress ';
$excluded _domains = Array (
' localhost ', ' www.mydomain.com ');
$max _connections = 10;
Initialize some of the variables
$url _list = Array ();
$working _urls = Array ();
$dead _urls = Array ();
$not _found_urls = Array ();
$active = null;
Connect to MySQL
if (!mysql tutorial _connect ($db _host, $db _user, $db _pass)) {
Die (' Could not connect: '. Mysql_error ());
}
if (!mysql_select_db ($db _name)) {
Die (' could not select DB: '. mysql_error ());
}
Find all articles that contain links
$q = "Select Post_content from Wp_posts
WHERE post_content like '%href=% '
and post_status = ' publish '
and Post_type = ' post ';
$r = mysql_query ($q) or Die (Mysql_error ());
while ($d = Mysql_fetch_assoc ($r)) {
Use a regular matching link
if (Preg_match_all (. *?) "!href=", $d [' post_content '], $matches)) {
foreach ($matches [1] as $url) {
Exclude some domains
$tmp = Parse_url ($url);
if (In_array ($tmp [' Host '], $excluded _domains)) {
Continue
}
Store the URL
$url _list []= $url;
}
}
}
Remove duplicate links
$url _list = array_values (Array_unique ($url _list));
if (! $url _list) {
Die (' No URL to check ');
}
We first configure the database, a series of domain names to exclude ($excluded _domains), and the maximum number of concurrent connections ($max _connections). Then, connect the database, get the articles and the included links, and collect them into an array ($url _list).
The following code is a little more complicated, so I'll explain it in small steps:
1. Batch Processor
$MH = Curl_multi_init ();
2. Add a URL that needs to be processed in batches
for ($i = 0; $i < $max _connections; $i + +) {
Add_url_to_multi_handle ($MH, $url _list);
}
3. Initial processing
do {
$MRC = Curl_multi_exec ($MH, $active);
while ($MRC = = Curlm_call_multi_perform);
4. Main loop
while ($active && $MRC = = CURLM_OK) {
5. There are active connections
if (Curl_multi_select ($MH)!=-1) {
6. Work
do {
$MRC = Curl_multi_exec ($MH, $active);
while ($MRC = = Curlm_call_multi_perform);
7. Do you have any information?
if ($mhinfo = Curl_multi_info_read ($MH)) {
means that the connection ends normally.
8. Getting information from a curl handle
$chinfo = Curl_getinfo ($mhinfo [' handle ']);
9. Dead chain?
if (! $chinfo [' Http_code ']) {
$dead _urls []= $chinfo [' url '];
10. 404, huh?
else if ($chinfo [' http_code '] = = 404) {
$not _found_urls []= $chinfo [' url '];
11. can still use
} else {
$working _urls []= $chinfo [' url '];
}
12. Remove handle
Curl_multi_remove_handle ($MH, $mhinfo [' handle ']);
Curl_close ($mhinfo [' handle ']);
13. Add a new URL and work
if (Add_url_to_multi_handle ($MH, $url _list)) {
do {
$MRC = Curl_multi_exec ($MH, $active);
while ($MRC = = Curlm_call_multi_perform);
}
}
}
}
14. Finished
Curl_multi_close ($MH);
echo "==dead urls==n";
echo Implode ("n", $dead _urls). "NN";
echo "==404 urls==n";
echo Implode ("n", $not _found_urls). "NN";
echo "==working urls==n";
echo Implode ("n", $working _urls);
15. To add a URL to a batch processor
function Add_url_to_multi_handle ($MH, $url _list) {
static $index = 0;
If there's a URL left to use,
if ($url _list[$index]) {
New Curl Handle
$ch = Curl_init ();
Configure URL
curl_setopt ($ch, Curlopt_url, $url _list[$index]);
Do not want to output the returned content
curl_setopt ($ch, Curlopt_returntransfer, 1);
Redirect to where we're going.
curl_setopt ($ch, curlopt_followlocation, 1);
Does not require content body, can save bandwidth and time
curl_setopt ($ch, curlopt_nobody, 1);
Add to Batch Processor
Curl_multi_add_handle ($MH, $ch);
Dial the counter, and the next time you call the function, you can add the next URL.
$index + +;
return true;
} else {
No new URLs to deal with
return false;
}
}
Let's explain the above code. The ordinal number of the list corresponds to the sequential numbers in the code comment.
Create a new batch processor. Created a multi handle.
Later we will create a function add_url_to_multi_handle () that adds the URL to the batch processor. Whenever this function is invoked, a new URL is added to the batch processor. Initially, we added 10 URLs to the batch processor (this number is determined by the $max _connections).
It is necessary to run curl_multi_exec () to initialize the work, as long as it returns to Curlm_call_multi_perform there is still something to do. This is done primarily to create a connection that does not wait for the full URL response.
As long as there are active connections in the batch the main loop will continue.
Curl_multi_select () waits until a URL query produces an active connection.
Curl's work is coming again, mainly to get response data.
Check all kinds of information. When a URL request completes, an array is returned.
There is a CURL handle in the returned array. We use it to get the appropriate information for a single curl request.
If this is a dead chain or the request times out, the HTTP status code will not be returned.
If this page is not found, it returns a 404 status code.
In other cases, we all think that this link is available (of course, you can also check the 500 error ...). )。
Remove this curl handle from the batch because it is no longer useful and shut it down!
Well, now you can add another URL to come in. Once again, the initialization work begins again ...
Well, it's all done. Turn off batch processors and generate reports.
Look back to the function of adding a new URL to the batch processor. Every time this function is invoked, the static variable $index incremented once, so that we know how many URLs remain to be processed.
I ran the script over my blog (test required, there are some error links are intentionally added), the results are as follows:
A total of about 40 URLs were checked, which cost less than two seconds. When you need to check a lot of URLs, the effect of the worry-saving is conceivable! If you open 10 connections at the same time, it can be 10 times times faster! In addition, you can use the Curl batch of the no partition feature to handle a large number of URL requests, without blocking your web script.
Some other useful curl options
HTTP Authentication
If a URL request requires an HTTP based authentication, you can use the following code:
Copy content to Clipboard code:
$url = "http://www.somesite.com/members/";
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, Curlopt_returntransfer, 1);
Send user name and password
curl_setopt ($ch, Curlopt_userpwd, "Myusername:mypassword");
You can allow it to redirect
curl_setopt ($ch, curlopt_followlocation, 1);
The following options let CURL after redirection
can also send user name and password
curl_setopt ($ch, Curlopt_unrestricted_auth, 1);
$output = curl_exec ($ch);
Curl_close ($ch);
FTP Upload
PHP comes with an FTP class library, but you can also use CURL:
Open a file pointer
$file = fopen ("/path/to/file", "R");
The URL contains most of the information you need.
$url = "Ftp://username:password@mydomain.com:21/path/to/new/file";
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, Curlopt_returntransfer, 1);
Upload related options
curl_setopt ($ch, curlopt_upload, 1);
curl_setopt ($ch, Curlopt_infile, $fp);
curl_setopt ($ch, Curlopt_infilesize, FileSize ("/path/to/file"));
Whether to turn on ASCII mode (useful when uploading text files)
curl_setopt ($ch, CURLOPT_FTPASCII, 1);
$output = curl_exec ($ch);
Curl_close ($ch);
WALL-turning technique
You can initiate a curl request with a proxy:
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, ' http://www.example.com ');
curl_setopt ($ch, Curlopt_returntransfer, 1);
Specify proxy Address
curl_setopt ($ch, Curlopt_proxy, ' 11.11.11.11:8080 ');
Provide user name and password if required
curl_setopt ($ch, curlopt_proxyuserpwd, ' user:pass ');
$output = curl_exec ($ch);
Curl_close ($ch);
callback function
You can have curl call a specified callback function during a URL request process. For example, start using the data immediately in the content or in response to the download, rather than waiting until the full download is complete.
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, ' http://net.tutsplus.com ');
curl_setopt ($ch, Curlopt_writefunction, "progress_function");
Curl_exec ($ch);
Curl_close ($ch);
function Progress_function ($ch, $str) {
Echo $str;
return strlen ($STR);
}
This callback function must return the length of the string, otherwise this feature will not work properly.
In the process of receiving a URL response, the function is invoked whenever a packet is received.
Summary
Today we learned about the power and flexibility of the Curl library. I hope you like it. The next time you want to launch a URL request, consider the Curl bar!
Curl Get 301-or 302-turn URL problem solutions
?
$ghurl = Isset ($_get[' id ')? $_get[' id ']: ' http://www.baidu.com/';
PHP Access
function getcontents ($url) {
$header = Array ("referer:http://www.111cn.net/");
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, Curlopt_timeout, 30);
curl_setopt ($ch, Curlopt_httpheader, $header);
curl_setopt ($ch, curlopt_followlocation,1); Whether to crawl the page after the jump
Ob_start ();
Curl_exec ($ch);
$contents = Ob_get_contents ();
Ob_end_clean ();
Curl_close ($ch);
return $contents;
}
$contents = getcontents ($ghurl);
Echo $contents;
?>
In general, under the Win2003+iis such as, the Php_curl.dll configuration is no problem.
But the author in Linux+apahe2.0+php5.2.12+directadmin, (General foreign host is using this configuration) if get the URL has 301/302 jumps, will be an error:
curl_setopt () [function.curl-setopt]: curlopt_followlocation cannot to activated when in Safe_mode or a open_basedir is s ET in * * *