In this article you will see how to transfer data using various protocols with cURL, using the PHP library, libcurl. I will show you, in this article, only some of the most important protocols, like: FTP, FTPS, FILE, HTTP, HTTPS, SMTP, SMTPS.
As I wrote in my PHP multithreading with cURL article, the libcurl is a free and easy-to-use client-side URL transfer library, supporting DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, TELNET and TFTP. PHP supports the libcurl library which 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. These library functions have been added to PHP 4.0.2. To use this library in PHP, remove the ";" from extension=php_curl.dll in php.ini, put ssleay32.dll and libeay32.dll in Windows/System32, and copy the php_curl.dll into Windows/System32.

PHP Data Transfer via FTP with Libcurl

File Transfer Protocol (FTP) is a standard network protocol used to transfer files from one host to another over a TCP-based network, such as the Internet. FTP is built on a client-server architecture and utilizes separate control and data connections between the client and server. FTP users may authenticate themselves using a clear-text sign-in protocol but can connect anonymously if the server is configured to allow it.
In this section, to show how to transfer data using the FTP protocol with cURL, I created an online public FTP account. After creating this account, I got the following login information:
FTP address  - ftp9.Jabry.com
Username - florinsteaua
Password - florinsteaua
Note that I gave you the password to test yourself on this account, if you want, and to use whatever you file you want, from your computer.
And then, to see the result of my cURL-FTP client, I installed the FileZilla client. In the File-> Site Manager menu option, I set the corresponding options for my public FTP account from above, as you can see in the below picture:



Click here for larger image

Figure 1. Setting the FileZilla Site Manager by providing the corresponding information

Then, press Connect button. You should get something like this:
Status:	Resolving address of ftp9.Jabry.com
Status:	Connecting to 67.208.91.118:21...
Status:	Connection established, waiting for welcome message...
Response:	220 users9 V2 WS_FTP Server 5.0.4 (0)
Command:	USER florinsteaua
Response:	331 Password required
Command:	PASS ************
Response:	230 user logged in
Command:	SYST
Response:	215 UNIX
Command:	FEAT
Response:	500 illegal command
Status:	Connected
Status:	Retrieving directory listing...
Command:	PWD
Response:	257 "/florinsteaua" is current directory
Command:	TYPE I
Response:	200 Type set to IMAGE.
Command:	PASV
Response:	227 Entering Passive Mode (67,208,91,118,14,129).
Command:	LIST
Response:	150 Opening ASCII data connection for directory listing
Response:	226 transfer complete
Status:	Directory listing successful
The above text represents all the commands and responses of the server connection, as you can see in the section below the Quickconnect information bar . In the Remote site section, from the below picture, you can see the structure of my florinsteaua site:



Click here for larger image

Figure 2. Using the FileZilla client to see the main folder of the site

So, let's get back to work! Now, using the cURL, libcurl PHP library, we will create a client that will upload a picture into the main folder of our site. To do that, we will use a small HTML form:
The ftp.html listing:
<html>
<body>
<form action="ftp.php" method="post" enctype="multipart/form-data">
<div>
<label for="upload">Select file</label>
<input name="upload" type="file" />
<input type="submit" name="Submit" value="Upload" />
</div>
</form>
</body>
</html>
The form seen in browser looks like this:



Click here for larger image

Figure 3. The HTML form used to browse the file that will be uploading

The ftp.php listing:
<?php   
           
if (isset($_POST['Submit'])) {
 if (!empty($_FILES['upload']['name'])) {
            //Initialize a cURL session
 	$ch = curl_init();
 	$localpicture = $_FILES['upload']['tmp_name'];
 	$fp = fopen($localpicture, 'r');
       
           //Set the URL for cURL to work with
	curl_setopt($ch, CURLOPT_URL, 'ftp://florinsteaua:florinsteaua@ftp9.Jabry.com/'.$_FILES['upload']['name']);
           // Sets the TRUE option to prepare for an upload
 	curl_setopt($ch, CURLOPT_UPLOAD, TRUE);
           //Sets the input file for the transfer
 	curl_setopt($ch, CURLOPT_INFILE, $fp);
          //Sets the size of the file to be sent, in bytes
 	curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localpicture));
           //Executing the upload
 	curl_exec ($ch);
 	$error_no = curl_errno($ch);    
 	curl_close ($ch);
    if ($error_no == 0) {
        $error = 'File uploaded succesfully.';
        } else {
        	$error = 'File upload error.';
        }
 } else {
    	$error = 'Please select a file.';
 }
echo $error;
} 
?> 
In the browser, if the $error_no=0 then everything worked fine ( you can find all the error corresponding to their number of the error here and you should get the message : 'File uploaded successfully.', like in the next figure:



Click here for larger image

Figure 4. The FTP OK message listed into the browser

And, now, let's check if our picture_to_upload.jpg was uploaded. Note that you should first try to relogin, otherwise, you will think that didn't work, even the message was the expected one.



Click here for larger image

Figure5. The site structure and content after uploading the picture_to_upload.jpg picture

PHP Data Transfer via FTPS with Libcurl

FTPS (FTP Secure or FTP-SSL) is an extension to the commonly used File Transfer Protocol (FTP) that adds support for the Transport Layer Security (TLS) and the Secure Sockets Layer (SSL) cryptographic protocols. FTPS includes full support for the TLS and SSL cryptographic protocols, including the use of server-side public key authentication certificates and client-side authorization certificates. It also supports compatible ciphers, including AES, RC4, RC2, Triple DES and DES, and hash functions SHA, MD5, MD4 and MD2.
In this section we will improve the above ftp.php script, by adding some security to it, by setting some of the predefined constants : CURLOPT_SSL_VERIFYHOST, CURLOPT_FTP_SSL, CURLOPT_USERPWD, CURLOPT_SSLVERSION:
<?php                         
if (isset($_POST['Submit'])) {
 if (!empty($_FILES['upload']['name'])) {
 	$ch = curl_init();
 	$localfile = $_FILES['upload']['tmp_name'];
 	$fp = fopen($localfile, 'r');
 	curl_setopt($ch, CURLOPT_URL, 'ftp://florinsteaua:florinsteaua@ftp9.Jabry.com/'.$_FILES['upload']['name']);
 	curl_setopt($ch, CURLOPT_UPLOAD, 1);
 	curl_setopt($ch, CURLOPT_INFILE, $fp);
 
  //SSL settings
  //To stop cURL from verifying the peer's certificate use the value 0 or False.
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  //1 to check the existence of a common name in the SSL peer certificate. 
  //2 to check the existence of a common name and also verify that it matches the hostname provided. 2 is the default value.
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
  
  //The FTP authentication method : CURLFTPAUTH_SSL (try SSL first), CURLFTPAUTH_TLS (try TLS first), or CURLFTPAUTH_DEFAULT (let cURL decide).
  curl_setopt($ch, CURLOPT_FTP_SSL, CURLOPT_FTPSSLAUTH);
  //Try using SSL, proceed as normal otherwise.
   curl_setopt($ch, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);
  //Sets the username and password to use for the connection.
  curl_setopt($ch, CURLOPT_USERPWD, 'florinsteaua:florinsteaua');
  
   //Sets the SSL version
   curl_setopt($ch, CURLOPT_SSLVERSION, 3);
  //end SSL

  curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
  curl_exec ($ch);
  $error_no = curl_errno($ch);
  $error_msg = curl_error($ch);
  
  if ($error_no == 0) {
      $error = 'File uploaded succesfully.';
      } else {
	        $error = 'File upload error.';
	 }
}
echo $error;      
curl_close ($ch);
}
?> 
The output is the same as the for above application, in the Figure 5.

PHP Data Transfer via FILE with Libcurl

URL (Uniform Resource Locator) File Protocol is the browser-standard scheme used for accessing files on a local computer. The URL should start with "file://" followed either by the host name of the local computer, "localhost" or void. In the next application you will see a simple example of using the FILE protocol:
<?php
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'file:///D:/Apache2.2/htdocs/php/cURL_protocols/FILE.txt');
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Get the response and close the channel.
$response = curl_exec($ch);
echo $response;
curl_close($ch);
?>
The output is:



Click here for larger image

Figure6. Using the FILE protocol

PHP Data Transfer via HTTP with Libcurl

The Hypertext Transfer Protocol (HTTP) represents the foundation of data communication for the World Wide Web and a networking protocol for distributed, collaborative, hypermedia information systems. An HTTP session represents a sequence of network request-response transactions, most used to access information on the Internet. The HTTP protocol is a text one and is the implicit protocol for the World Wide Web (WWW). An HTTP client initiates a request, it establishes a Transmission Control Protocol (TCP) connection to a particular port on a host (typically port 80; see List of TCP and UDP port numbers). An HTTP server listening on that port waits for a client's request message. Upon receiving the request, the server sends back a status line, such as "HTTP/1.1 200 OK", and a message of its own, the body of which is perhaps the requested resource, an error message, or some other information.
Next, is a simple application uses basic cURL option set to handle an HTTP session:
<?php
//Initializes a new session and return a cURL handle for use with the curl_setopt(), curl_exec() and curl_close() functions
$curl = curl_init();
//Sets an option on the given cURL session handle like url, timeout, return transfer
curl_setopt($curl, CURLOPT_URL, 'http://www.google.ro');
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute the given cURL session (get the content of the url and put it into the output variable)
$output = curl_exec($curl);
// Outputs the result
echo $output;
// Print the curl info like http response code, content type etc.
// print_r (curl_getinfo($curl));
// close the curl handle to free system resources
curl_close($curl);
?>
The output for the listing is:



Click here for larger image

Figure 7. Outputting a simple HTTP session using cURL

PHP Data Transfer via HTTPS with Libcurl

Hypertext Transfer Protocol Secure (HTTPS) represents a combination of the Hypertext Transfer Protocol (HTTP) with SSL/TLS protocol that provides encrypted communication and secure identification of a network web server.
The below PHP script try to initialize an HTTPS session using two methods. One that doesn't verify the peer's certificate, and obviously not a safe one, by setting the false value (curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);) and one that checks the peer certificate, verify the host and then checks the certificate used to verify the peer. This certificate can be obtain from the restricted page like this: in the Tools menu of the browser (Mozilla Firefox in this case), choose the option Page Info -> Security Tab -> Details Tab -> View Certificate and select the certificate at the top of the hierarchy and then Export it into your corresponding folder to your application. I choose to put it together with my https.php script, also listed next:



Click here for larger image

Figure 8. The folder containing the certificate and the https.php script

Listing https.php:
<?php
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://encrypted.google.com/');
curl_setopt($ch, CURLOPT_TIMEOUT, 80);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Stops cURL from verifying the peer's certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

//Sets the cURL to verify the peer's certificate
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
// 1 to check the existence of a common name in the SSL peer certificate. 
//2 to check the existence of a common name and also verify that it matches the hostname provided. 
//2 is the default value
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//The name of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with CURLOPT_SSL_VERIFYPEER.
//curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "GTECyberTrustGlobalRoot.crt");  
// Get the response and close the channel.
$response = curl_exec($ch);
echo $response; 
print_r (curl_getinfo($ch));
curl_close($ch);
?>
The output is:



Click here for larger image

Figure 9. Using the HTTPS protocol to and also display the page info using the curl_getinfo function

Conclusion

Over the article you have seen how to transfer data using various protocols, like FTP, FTPS, HTTP, HTTPS, FILE, and cURL.

About the Author

Octavia Andreea Anghel is a senior PHP developer currently working as a primary trainer for programming teams that participate at national and international software-development contests. She consults on developing educational projects at a national level. She is a coauthor of the book "XML Technologies: XML in Java" (Albastra, ISBN 978-973-650-210-1), for which she wrote the XML portions. In addition to PHP and XML, she's interested in software architecture, web services, UML, and high-performance unit tests. to e-mail her.