Upload file on ftp server with cURL and php

cURL is a computer software project providing a library and command-line tool for transferring data using various protocols.
With a cURL we can upload and download file on FTP server.

Code snippet given here:
For upload a file

		const REMOTE_FTP = 'ftp:/somename.com/';//give your ftp url here
    	const REMOTE_USER = 'user';//give your username here
		const REMOTE_PASSWORD = 'pass'; //give your password here 
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,REMOTE_FTP."/path/to/direcoty"); //give path if u want to access sub directory
		curl_setopt($ch, CURLOPT_USERPWD, REMOTE_USER.":".REMOTE_PASSWORD);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FTPLISTONLY,true);
		$result = curl_exec ($ch);
		print_r($result);//display file list from directory
		
		foreach($result as $file){
			curl_setopt($ch, CURLOPT_URL,REMOTE_FTP."/path/to/direcoty/".$file);//access file on ftp with full file path
			curl_setopt($ch, CURLOPT_USERPWD, REMOTE_USER.":".REMOTE_PASSWORD);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$result = curl_exec ($ch);
			print_r($result);//display file result
			//if you want to write in local
			$fp = fopen("filename.txt", "w");
			fwrite($fp, $result);	
			fclose($fp);
		}
				
		if(!curl_errno($ch)){
			$info = curl_getinfo($ch);		
			print_r($info);
		} else {
			echo 'Curl error: ' . curl_error($ch);	
		}
		
Posted in PHP. 1 Comment »

One Response to “Upload file on ftp server with cURL and php”

  1. Trisha Says:

    Is it for uploading or downloading ??


Speak Your Mind

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: