Monday 16 July 2018

Removing Output From a cURL Transfer in PHP

Removing Output From a cURL Transfer in PHP

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:

  1. $ch = curl_init();  
  2. curl_setopt($ch, CURLOPT_URL, "ftp://username:password@ipaddress:port");  
  3. curl_setopt($ch, CURLOPT_QUOTE, array("DELE /images/house.gif"));  
  4. curl_exec($ch);  
  5. 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:
  1. 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:
  1. 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:

  1. $ch = curl_init();  
  2. curl_setopt($ch, CURLOPT_URL, "ftp://username:password@ipaddress:port");  
  3. curl_setopt($ch, CURLOPT_QUOTE, array("DELE /images/house.gif"));  
  4. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
  5. $output = curl_exec($ch); // assign the return string to $output 

0 comments:

Post a Comment