Tuesday, January 27, 2009

FTP upload via cURL

FTP hosting is often much cheaper than regular web hosting. The upload with an ftp client is for sure the most common way, but could be a problem for people behind a firewall or without enough rights (capabilities) to install a FTP client. For those a upload via a web form is the best solution.
Using cURL for file transmissions
In this example we want to upload a file to some (password protected) remote FTP server via a web form.
The form is simple and has only one file field and the submit button. Don’t forget to protect this kind of pages. we need some PHP code to handle the upload and opens a stream to send the file via cURL to the remote FTP server.

start form action="" method="post" enctype="multipart/form-data"

input name="upload" type="file"
input type="submit" name="Submit" value="Upload"
end form

After the user has selected a file, the data is uploaded to the web server. We open the temp file with fopen and the cURL session is initialized. Together with the URL for the remote FTP server, we send the FTP login and password to the target location. The other cURL settings are required to send the file via the FTP protocol to the target server. If the returned error code is equal “0″, the upload was successful.
This small PHP snippet is responsible for the upload to some remote FTP server.


Monday, January 26, 2009

What options we set here?
First we set the connection timeout to 30 seconds, so we don’t have our script waiting indefinitely if the remote server fails to respond.
Then we set how cURL will identify itself to the remote server. Some servers will return different content for different browsers (or agents, such as spiders of the search engines), so we want our request to look like it is coming from a popular browser.

CURLOPT_RETURNTRANSFER set to true forces cURL not to display the output of the request, but return it as a string.

Then we set CURLOPT_SSL_VERIFYPEER option to false, so the request will not trigger an error in case of an invalid, expired or not signed SSL certificate.
Finally, we set CURLOPT_FOLLOWLOCATION to 1 to instruct cURL to follow “Location:” redirects found in the headers sent by the remote site.
Now we must prepare the data that we want to post. We can first store this in an array, with the key of an element being the same as the input name of a regular form, and the value being the value that we want to post for that field.

For example, if in a regular form we would have:

we add this to our array like this:
$post_data['firstName'] = ‘Name’;
$post_data['action'] = ‘Register’;
Do the same for every form field.
Data will be posted in the following format:

In order to format the data like this, we are going to create strings for each key-value pair (for example key1=value1), put them in another array ($post_items) then combine them in one string using PHP function implode() .
foreach ( $post_data as $key => $value) {
$post_items[] = $key . ‘=’ . $value;
$post_string = implode (’&’, $post_items);
Next, we need to tell cURL which string we want to post. For this, we use the CURLOPT_POSTFIELDS option.

curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
Finally, we execute the post, then close the connection.
$result = curl_exec($curl_connection);
By now, the data should have been posted to the remote URL. Go check this, and if it did not work properly, use curl_getinfo() function to see any errors that might have occurred.
This line displays an array of information regarding the transfer. This must be used before closing the connection with curl_close();
You can also see number and description of the error by outputting curl_errno($curl_connection) and curl_error($curl_connection).
So let’s put everything together. Here is our code:

//create array of data to be posted
$post_data['firstName'] = ‘Name’;
$post_data['action'] = ‘Register’;
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . ‘=’ . $value;
//create the final string to be posted using implode()
$post_string = implode (’&’, $post_items);
//create cURL connection
$curl_connection = curl_init(’http://www.domainname.com/target_url.php’);
//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT, “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)”);
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
//set data to be posted
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
//perform our request
$result = curl_exec($curl_connection);
//show information regarding the request
echo curl_errno($curl_connection) . ‘-’ . curl_error($curl_connection);
//close the connection

Friday, January 23, 2009

1) Getting the contents of files on remote servers with CURL : CURL is a powerful way to interact with remote servers with PHP. With CURL, it is possible to download files from remote servers
We’re coding a simple CURL function that can be used over and over. This function is simply for getting the contents of files on remote servers

2) File Handling With CURL : Using PHP's CURL module to fetch the example.com homepage and write the content in example_homepage.txt.

CURLOPT_FILE is an option for a CURL session identified by the ch parameter. $fp is a value set to the file that the transfer should be written to. The default is STDOUT (the browser window).
CURLOPT_HEADER is an option for a CURL session . It has Boolean value. Set TRUE to include the header in the output. Set False is not include the header in the output.

3) Submit A Form With CURL :
Here we’re going to learn how to submit a form using PHP and CURL.
So how do I use cURL to post data?
Begin by creating a new connection.
$curl_connection = curl_init('http://www.domainname.com/target_url.php');
A new connection is created using curl_init() function, which takes as parameter the target URL where we want to post our data. The target URL is the same as the “action” parameters of a normal form, which would look like this:

form start ("form action="http://www.domainname.com/target_url.php" method="post")
Now let’s set some options for our connection.
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

end of form

Thursday, January 22, 2009

What are cURL and libcurl?

cURL stands for "Client URLs" is a function library, and was developed by Daniel Stenberg in 1998 as a command line tool. PHP supports it through libcurl. libcurl is a portable library that provides an easy interface to the cURL functionality. It is thread safe, IPv6 compatible, and supports persistent connections. The libcurl PHP binding was added by Sterling Hughes.

PHP supports libcurl, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
In order to use PHP's CURL functions you need to install the libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

The following are the basic steps when we process with libcurl from within PHP
Initialize the cURL session : - we initialize a CURL session using the curl_init().
Set the cURL options (The order of the options is not important) : - Then we can set all our options for the transfer via the curl_setopt(),
Execute the options in the cURL session : - we execute the session with the curl_exec()
Close the curl session : - we finish session using the curl_close().

There are more number of functions associated with this libcurl library. Which are
curl_close -- Close a CURL session
curl_copy_handle -- Copy a cURL handle along with all of its preferences
curl_errno -- Return the last error number
curl_error -- Return a string containing the last error for the current session
curl_exec -- Perform a CURL session
curl_getinfo -- Get information regarding a specific transfer
curl_init -- Initialize a CURL session
curl_multi_add_handle -- Add a normal cURL handle to a cURL multi handle
curl_multi_close -- Close a set of cURL handles
curl_multi_exec -- Run the sub-connections of the current cURL handle
curl_multi_getcontent -- Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
curl_multi_info_read -- Get information about the current transfers
curl_multi_init -- Returns a new cURL multi handle
curl_multi_remove_handle -- Remove a multi handle from a set of cURL handles
curl_multi_select -- Get all the sockets associated with the cURL extension, which can then be "selected"
curl_version -- Return the current CURL version
curl_setopt -- Set an option for a CURL transfer