Removing Output From a cURL Transfer in PHP

February 9th, 2011 - Posted by Steve Marks to PHP, Web Development.

Whether telnetting, performing FTP actions or getting a webpage’s content, cURL provides a very simple way to communicate with other servers over a wide array of protocols. PHP incorporates functionality to assist with using cURL making it easy to carry out tasks with just a few lines of code.

A problem I ran early into early on when writing my first script using cURL was that the output from the call was being output directly to the screen. Let’s take the following example:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "ftp://username:password@ipaddress:port");
curl_setopt($ch, CURLOPT_QUOTE, array("DELE /images/house.gif"));
curl_exec($ch);
curl_close($ch);

When ran the above snippet will connect to a server via FTP and delete the required file, in this case ‘house.gif’. The code itself works fine and does exactly as expected, however following execution I then get a load of output to the screen like so:

drwxr-x--- 2 root root 0 Feb 8 05:47 . drwxr-x--- 2 root root 0 Feb 8 05:47 .. drwxr-x--- 1 root root 698 Feb 6 19:10 images -rwxr-x--- 2 root root 0 Feb 6 19:02 index.html

The Solution

That output is all well and good and actually provides some useful information, however what if we don’t want it blurted out the screen? Well, it’s easy. Simply add the following line of code to your cURL session:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

In doing this the transfer from cURL will now be returned as a string rather than output directly. Our final code now looks like so:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "ftp://username:password@ipaddress:port");
curl_setopt($ch, CURLOPT_QUOTE, array("DELE /images/house.gif"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch); // assign the return string to $output
curl_close($ch);
Tags: ,
This entry was posted on Wednesday, February 9th, 2011 at 9:25 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first