PHP - reading FTP file without downloading it/saving it locally - php

I would like to get FTP files content without saving it locally.
This is what I have so far:
$ftp_server = "my_server";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to the server");
if (#ftp_login($ftp_conn, "username", "password")) {
$local_file = 'C:\Users\user\Desktop\testing.txt';
$fp = fopen($local_file, "w");
$d = ftp_nb_fget($ftp_conn, $fp, "commands.yml", FTP_BINARY);
while ($d == FTP_MOREDATA) {
$d = ftp_nb_continue($ftp_conn);
}
if ($d != FTP_FINISHED) {
echo "Error downloading $server_file";
exit(1);
}
ftp_close($ftp_conn);
fclose($fp);
$filename = 'C:\Users\user\Desktop\testing.txt';
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
echo $contents;
} else {
echo "Couldn't establish a connection.";
}
The code above saves the file and read the file content. Is it possible to read the file without saving it locally?

From the answer on the official PHP site from bob at notallhere dot com:
Don't want to use an intermediate file? Use 'php://output' as the
filename and then capture the output using output buffering.
ob_start();
$result = ftp_get($ftp, "php://output", $file, FTP_BINARY);
$data = ob_get_contents();
ob_end_clean();

Related

SFTP file is not downloaded completelly with ssh2.sftp and fread

I am working on a log file download for a separate system that requires SFTP for viewing logs. I am able to view the available log files on the server and download them. My issue is that it seems that the download stops at 2K which, in most cases, is only the first 10 lines of the log file. The files should contain thousands of lines as they are daily logs of changes made to the system.
I have done this in two separate files, one loads all of the files onto a page where the user can select the available log files and click a link to view the contents in the browser:
$ftp_server = "IP of Server";
$ftp_user_name = "USERNAME";
$ftp_user_pass = "PASSWORD";
$connection = ssh2_connect($ftp_server, 22);
ssh2_auth_password($connection,$ftp_user_name, $ftp_user_pass);
$sftp = ssh2_sftp($connection);
$dh = opendir("ssh2.sftp://$sftp//EMSftp/audit_files/");
while (($file = readdir($dh)) !== false) {
if ($file != '.' && $file != '..'){
if (strpos($file,"2017-04")){
echo '/EMSftp/audit_files/'.$file.' | curl
| view<br>';
}
}
}
closedir($dh);
I have tried to download the files two different ways using sftp and ssh2:
$file = $_GET['file'];
$local_file = "/var/www/uploads/logs/$file";
if (!file_exists($local_file)){
$connection = ssh2_connect($ftp_server, 22);
ssh2_auth_password($connection,$ftp_user_name, $ftp_user_pass);
$sftp = ssh2_sftp($connection);
$stream = #fopen("ssh2.sftp://$sftp//EMSftp/audit_files/$file", 'r');
if (! $stream)
throw new Exception("Could not open file: $remote_file");
$contents = fread($stream, filesize("ssh2.sftp://$sftp//EMSftp/audit_files/$file"));
file_put_contents ($local_file, $contents);
#fclose($stream);
}
echo '<pre>';
echo file_get_contents($local_file);
echo '</pre>';
and also tried to accomplish this using curl. This only creates a blank file. Not sure what is missing here. Unable to add the file contents to the file.
$file = $_GET['file'];
$local_file = "/var/www/uploads/logs/$file";
fopen($local_file, 'w+');
chmod($local_file, 0777);
$remote = "sftp://$ftp_user_name:$ftp_user_pass#$ftp_server//EMSftp/audit_files/$file";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $remote);
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
curl_setopt($curl, CURLOPT_USERPWD, "$ftp_user_name:$ftp_user_pass");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$somecontent = curl_exec($curl);
if (is_writable($local_file)) {
if (!$handle = fopen($local_file, 'a')) {
echo "Cannot open file ($local_file)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($local_file)";
exit;
}
echo "Success, wrote ($somecontent) to file ($local_file)";
fclose($handle);
} else {
echo "The file $local_file is not writable";
}
curl_close($curl);
Not sure where I am missing something. Wondering if there is a time out related to this procedure that I am overlooking. Any help?
This is wrong:
$contents = fread($stream, filesize("ssh2.sftp://$sftp//EMSftp/audit_files/$file"));
It does not guarantee you, that a whole file will be read.
As documented:
fread() reads up to length bytes
If the logs are of reasonable size, use simple file_get_contents:
$contents = file_get_contents("ssh2.sftp://$sftp//EMSftp/audit_files/$file");
If not, read the file in chunks in a loop:
$stream = #fopen("ssh2.sftp://$sftp//EMSftp/audit_files/$file", 'r');
while (!feof($stream))
{
$chunk = fread($stream, 8192);
// write/append chunk to a local file
}
#fclose($stream);

Writte text file with message to FTP

I want to create a folder and create a file with a given message inside that folder on a FTP server.
Following is my attempt:
<?php
$dirname = "files/";
$dir = $_GET["name"];
$dirname .= $dir;
$filepath = $dirname."/message.txt";
$txt = $_GET["message"];
// set up basic connection
$conn_id = ftp_connect("example.com");
// login with username and password
$login_result = ftp_login($conn_id, "login", "password");
// try to create the directory and file
if (ftp_mkdir($conn_id, $dirname)) {
echo "successfully created $dirname\n";
$myfile = fopen('php://temp', 'r+') or die("Unable to open file!");
fwrite($myfile, $txt);
rewind($myfile);
ftp_fput($conn_id, $filepath, $myfile, FTP_ASCII);
} else {
echo "There was a problem while creating $dirname\n";
}
// close the connection
ftp_close($conn_id);
?>
This creates the folder with the given name and also puts a message.txt file inside that folder but the file is always empty. How can I add my message to the file?
I would be most comfortable with using shell_exec to write to a local file. My solution would look like this.
<?php
$dirname = "files/";
$dir = $_GET["name"];
$dirname .= $dir;
$filepath = $dirname."/message.txt";
$txt = $_GET["message"];
// set up basic connection
$conn_id = ftp_connect("example.com");
// login with username and password
$login_result = ftp_login($conn_id, "login", "password");
// try to create the directory and file
if (ftp_mkdir($conn_id, $dirname)) {
echo "successfully created $dirname\n";
$myfile = fopen('php://temp', 'r+') or die("Unable to open file!");
// Here is the good stuff with shell_exec.
$myfilelocation = '~/myfile.txt';
shell_exec( "cat $txt >> $myfilelocation" );
ftp_fput($conn_id, $filepath, $myfile, FTP_ASCII);
} else {
echo "There was a problem while creating $dirname\n";
}
// close the connection
ftp_close($conn_id);
?>
You seem to be opening the file in read mode ('php://temp', 'r+')
try fopen ('php://temp', 'w +')

error in upload file to ftp with ftp_nb_fput

I wrote this code for upload file via ftp.
<?php
$file = 'index.php';
$fp = fopen($file, 'r');
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// Initate the upload
$ret = ftp_nb_fput($conn_id, $file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {
// Do whatever you want
echo ".";
// Continue upload...
$ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
echo "There was an error uploading the file...";
exit(1);
}
fclose($fp);
?>
and I get this error:
Warning: ftp_nb_fput(): Could not open data connection to port 2804: Connection refused
I disable my firewall but not work!
Try running in pasv mode, ftp_pasv($conn_id, true); Also please use ftp_close($conn_id) when you're done.
Thanks Ohgodwhy!

PHP ftp upload times out(File is 12 byte)

I have a problem creating a local file, then uploading it to ftp server.
Here is my code:
$file = 'test';
$string = $phone.','.$y.','.$z;
$fp = fopen($file, 'w+');
fwrite($fp, $string);
fclose($fp);
$fp = fopen($file, 'r');
$conn_id = ftp_connect('domain');
ftp_login($conn_id, 'user', 'pass');
if (ftp_fput($conn_id, $file, $fp, FTP_BINARY)) {
} else {
}
ftp_close($conn_id);
fclose($fp);
unlink($file);
I dont get any error, I just exceed memory. I dont have any other problems with the ftp server, anywhere else but when I am uploading. As I said the file is only 12 bytes.

PHP upload text to file

I am after some help with some code for a HTML feature.
I am wanting to get information from two textboxes on a web site (txtName,txtBody), and then save the contents of these textboxes to a file on an ftp server using PHP.
Can someone point me in the correct direction to do this?
thanks
File put contents can be used to accomplish this as dagon says, below is a simple example.
<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
//Assign txtName to variable.
$name = $_POST['txtName'];
// Append a new person to the file
$current .= $name;
// Write the contents back to the file
file_put_contents($file, $current);
?>
If you dealing with ftp then you have to use http://www.php.net/manual/en/function.ftp-fput.php
$file = $_POST['txtName'];
file_put_contents($file, $_POST['txtBody']);
$fp = fopen($file, 'r');
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if (ftp_fput($conn_id, $file, $fp, FTP_ASCII)) {
echo "Successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
ftp_close($conn_id);
fclose($fp);

Categories