failed to download the latest files using PHP, ssh2 via SFTP - php

#!/usr/bin/php
<?php
$username = "backup";
$password = "xxxxxxx";
$url = '192.168.1.100';
// Make our connection
$connection = ssh2_connect($url);
// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
{echo('Unable to connect.');}
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
{echo ('Unable to create SFTP connection.');}
$localDir = 'file:///home/hhh/Downloads/dbs';
$remoteDir = '/home/backup/Dropbox/dbs';
// download all the files
$dir = ('ssh2.sftp://' . $sftp . $remoteDir);
$numberOfFiles = 10;
$pattern = '/\.(aes|AES)$/'; // check only file with these ext.
$newstamp = 2;
$newname = "";
if ($handle = opendir($dir)) {
while (false !== ($fname = readdir($handle))) {
// Eliminate current directory, parent directory
if (preg_match('/^\.{1,2}$/',$fname)) continue;
// Eliminate other pages not in pattern
if (! preg_match($pattern,$fname)) continue;
$timedat = filemtime("$dir/$fname");
$fils[$fname] = $timedat;
if ($timedat > $newstamp) {
$newstamp = $timedat;
$newname = $fname;
}
}
}
closedir ($handle);
arsort ($fils, SORT_NUMERIC);
sfor($i = 0; $i < $numberOfFiles ; $i++)
$fils2 = array_keys($fils);
$i = 0;
foreach($fils2 as $s){
$i++;
echo "$i " . $s . "<br>\n";
if($i == $numberOfFiles )break;
}
// $newstamp is the time for the latest file
// $newname is the name of the latest file
// print last mod.file - format date as you like
$rttp = ssh2_scp_recv($connection, "$remoteDir/$newname", "$localDir/$newname")
?>
I have been trying to download the latest FILES from a directory using sftp. I have only managed to download ONE file instead to 10. I also was able to tweak it to download all the files but that is not i what I was after.
I would like to make it work so that I can be able to download a certain X number of files.

#!/usr/bin/php
<?php
$username = "user";
$password = "password";
$url = "host ip";
// Make our connection
$connection = ssh2_connect($url);
// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
{echo('Unable to connect.');}
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
{echo ('Unable to create SFTP connection.');}
//$dir
$localDir = "/path/to/localdir/".date('Y-m-d');
exec("mkdir -p '$localDir'");
echo $localDir;
$remoteDir = "/path/to/remotedir";
// download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
if (substr($file, 0, 11)== date('d-M-Y')) {
//date('d-M-Y', strtotime('yesterday') #for retriving the previous day
# code...
// echo $file;
ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
}
}
}
}
?>
This downloads the latest files from a remote directory and creates a new local directory by date where it downloads the new remote files

Related

Trying to get all content of directory from one server to another using ssh2_scp_recv in php

The below script is working successfully.
Getting file from one server to another
if(ssh2_scp_recv($conn, '/var/www/html/captures/store/2016/04/HK/15721022890870/test/vcredist.bmp',
'/var/www/html/captures/store/2016/04/HK/15721022890870/test/vcredist.bmp')){
echo "\n recevied \n";
}else{
echo "\n not recevied\n";
}
But instead for fetching just a static file, I want to fetch folder with all its content inside.
With above example, the directory I would like to fetch to local server is "15721022890870"
/var/www/html/captures/store/2016/04/HK/15721022890870/
I have tried below code but doesn't work,
The remote server has directory, but the local server doesn't have, so I want to make directory then copy all its content inside
if(ssh2_scp_recv($conn, '/var/www/html/captures/store/2016/04/HK/15721022890870/',
'/var/www/html/captures/store/2016/04/HK/')){
echo "\n recevied done \n";
}else{
echo "\n not done \n";
}
<?php
$username = "your_username";
$password = "your_pass";
$url = 'your_stp_server_url';
// Make our connection
$connection = ssh2_connect($url);
// Authenticate
if (!ssh2_auth_password($connection, $username, $password)) throw new Exception('Unable to connect.');
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) throw new Exception('Unable to create SFTP connection.');
$localDir = '/path/to/your/local/dir';
$remoteDir = '/path/to/your/remote/dir';
// download all the files
$files = scandir('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
}
}
}
?>
This is from server to computer but you can modify the $localDir

KCfinder upload image for many users

My website lets logged users to use CKeditor and CKFinder to create pages or blog and of course upload image from editor. I got problem for many users that will use the same images in a single folder. I have searching for the same problem on StackOverflow and I found this question:
KCFinder with CKEditor - setting up dynamic folders for upload files.
I think the solution was good, but rather than creating many folders, I am just thinking how to save every user images by using a prefix of their user ID. For example the user with ID 10 will save his images with prefix 10_xxxxx.jpg and so on.
How to do it. Any body could show me where part of the file script that could be modified? I am using KCFinder V.3.12. Sorry for my English.
$_SESSION['id'] = 10;
public function upload() {
$config = &$this->config;
$file = &$this->file;
$url = $message = "";
if ($config['disabled'] || !$config['access']['files']['upload']) {
if (isset($file['tmp_name'])) #unlink($file['tmp_name']);
$message = $this->label("You don't have permissions to upload files.");
} elseif (true === ($message = $this->checkUploadedFile())) {
$message = "";
$dir = "{$this->typeDir}/";
if (isset($_GET['dir']) &&
(false !== ($gdir = $this->checkInputDir($_GET['dir'])))
) {
$udir = path::normalize("$dir$gdir");
if (substr($udir, 0, strlen($dir)) !== $dir)
$message = $this->label("Unknown error.");
else {
$l = strlen($dir);
$dir = "$udir/";
$udir = substr($udir, $l);
}
}
if (!strlen($message)) {
if (!is_dir(path::normalize($dir)))
#mkdir(path::normalize($dir), $this->config['dirPerms'], true);
$filename = $this->normalizeFilename($file['name']);
$target = file::getInexistantFilename($dir . $filename);
if (!#move_uploaded_file($file['tmp_name'], $target) &&
!#rename($file['tmp_name'], $target) &&
!#copy($file['tmp_name'], $target)
)
$message = $this->label("Cannot move uploaded file to target folder.");
else {
if (function_exists('chmod'))
#chmod($target, $this->config['filePerms']);
$this->makeThumb($target);
$url = $this->typeURL;
if (isset($udir)) $url .= "/$udir";
$url .= "/" . basename($target);
if (preg_match('/^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)$/', $url, $patt)) {
list($unused, $protocol, $domain, $unused, $port, $path) = $patt;
$base = "$protocol://$domain" . (strlen($port) ? ":$port" : "") . "/";
$url = $base . path::urlPathEncode($path);
} else
$url = path::urlPathEncode($url);
}
}
}

Php check size of remote folder

I have a user folder on remote server (other than page files). I need check a size of whole "example" folder, not one file. I think i should do it with use a ftp, but I can't.
I have something like this but not working:
function dirFTPSize($ftpStream, $dir) {
$size = 0;
$files = ftp_nlist($ftpStream, $dir);
foreach ($files as $remoteFile) {
if(preg_match('/.*\/\.\.$/', $remoteFile) || preg_match('/.*\/\.$/', $remoteFile)){
continue;
}
$sizeTemp = ftp_size($ftpStream, $remoteFile);
if ($sizeTemp > 0) {
$size += $sizeTemp;
}elseif($sizeTemp == -1){//directorio
$size += dirFTPSize($ftpStream, $remoteFile);
}
}
return $size;
}
$hostname = '127.0.0.1';
$username = 'username';
$password = 'password';
$startdir = '/public_html'; // absolute path
$files = array();
$ftpStream = ftp_connect($hostname);
$login = ftp_login($ftpStream, $username, $password);
if (!$ftpStream) {
echo 'Wrong server!';
exit;
} else if (!$login) {
echo 'Wrong username/password!';
exit;
} else {
$size = dirFTPSize($ftpStream, $startdir);
}
echo number_format(($size / 1024 / 1024), 2, '.', '') . ' MB';
ftp_close($ftpStream);
Whole time script displays 0.00 MB, what can I do to fix it?
In your comments you indicated you have SSH access on the remote server. Great!
Here is a way to use SSH:
//connect to remote server (hostname, port)
$connection = ssh2_connect('www.example.com', 22);
//authenticate
ssh2_auth_password($connection, 'username', 'password');
//execute remote command (replace /path/to/directory with absolute path)
$stream = ssh2_exec($connection, 'du -s /path/to/directory');
stream_set_blocking($stream, true);
//get the output
$dirSize = stream_get_contents($stream);
//show the output and close the connection
echo $dirSize;
fclose($stream);
This will echo 123456 /path/to/directory where 123456 is the calculated size of the directory's contents. If you need human readable, you could use 'du -ch /path/to/directory | grep total' as the command, this will output formatted (k, M or G).
If you get an error "undefined function ssh2_connect()" you need to install/enable PHP ssh2 module on your local machine
Another way, without SSH could be to run the command on the remote machine.
Create a new file on the remote server, e.g. called 'dirsize.php' with the following code:
<?php
$path = '/path/to/directory';
$output = exec('du -s ' . $path);
echo trim(str_replace($path, '', $output));
(or any other PHP code that can determine the size of a local directory's contents)
And on your local machine include in your code:
$dirsize = file_get_contents('http://www.example.com/dirsize.php');

How do I copy a file thant contains random filename

How do I copy files in a directory with filename contains.. see sample below
file_123_XXXXXX.zip where XXXXXX is a random numbers..
I want to copy file_123_XXXXXX.zip from server to same file name to my local folder
the code is working operational if I set the filename exactly the same in the server but what if the file name randomly changes everyday.
thanks in advance..
here is my code:
include("./config.php");
$local_file1 = 'C:\Destination\file_123_XXXXXX.zip'; //how to copy the original filename XXXXX
if(file_exists($local_file1))
{
echo "
$('#getUpdts').attr('disabled','disabled')
.addClass('ui-state-disabled');
$('#proc').removeAttr('disabled')
.removeClass('ui-state-disabled');
";
echo "infoMsg('File is already downloaded..')";
}
else
{
$ftp_user = ftp_user;
$ftp_pw = ftp_pw;
$conn_id = ftp_connect('192.xxx.xxx.xxx') or die("Couldn't connect to 192.xxx.xxx.xxx");
$server_file1 = "/fromlocation/file_123_XXXXXX.zip"; //the filename with random that i want to get
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pw);
if(!file_exists($local_file1))
{
$contents = ftp_size($conn_id, $server_file1);
if ($contents >0) {
if (ftp_get($conn_id, $local_file1, $server_file1, FTP_BINARY)) {
echo "infoMsg('Successfully downloaded');";
} else {
echo "alertMsg('Unable to download');";
}
}else{
echo "alertMsg('Does not exist.');";
}
}
else
{
echo "alertMsg('does not exists');";
}
// close the connection
ftp_close($conn_id);
}
List the directory and match the filename using preg_match()
ftp_chdir($conn_id, "/fromlocation/");
foreach (ftp_nlist($conn_id, ".") as $server_file1) {
if (!preg_match('/^file_123_\d{6}\.zip/i', $server_file1)) continue;
if (is_file($server_file1)) continue;
// then the rest of your code...
$contents = ftp_size($conn_id, $server_file1);
if ($contents > 0) {
if (ftp_get($conn_id, $local_file1, $server_file1, FTP_BINARY)) {
echo "infoMsg('Successfully downloaded');";
} else {
echo "alertMsg('Unable to download');";
}
} else {
echo "alertMsg('Does not exist.');";
}
}
As I proposed in comment you could consider :
Connect to the server
Find the last modified file in your server file directory
Check IF (Local Side) the file already exists
Function's Code :
function get_last_modified_file($dir)
{
$path = $dir;
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read()))
{
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime)
{
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
return $latest_filename;
}
Using your code - It shoud looks like :
include("./config.php");
// Copy - Pasterino the function get_last_modified() here
// Fill variables $server_dir & $local_dir
$ftp_user = ftp_user;
$ftp_pw = ftp_pw;
$server_dir = "the path we will search into the last file/";
$local_dir = " the destination path/";
$conn_id = ftp_connect('192.xxx.xxx.xxx') or die("Couldn't connect to 192.xxx.xxx.xxx");
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pw);
// Get last modified file
$last_ctime_file = get_last_modified_file($server_dir);
if(file_exists($local_dir . $last_ctime_file"))
{
// We don't download it / echo Warning, etc..
echo "blalbllalba";
}
else
{
// We download it - Same code you used
$contents = ftp_size($conn_id, $server_dir . $last_ctime_file);
if ($contents >0)
{
if (ftp_get($conn_id, $local_dir . $last_ctime_file,
$server_dir . $last_ctime_file, FTP_BINARY))
echo "infoMsg('Successfully downloaded');";
else
echo "alertMsg('Unable to download');";
}
else
echo "alertMsg('File is empty.');";
}
ftp_close($conn_id);
Source : Stackoverflow : Get the lastest file in a directory

PHP- Count files on a server that connected with FTP

How to count number of files on a remote server that connected with FTP?
This is my code but it doesn't work
<?php
#$ftp = ftp_connect("host");
#ftp_login($ftp, "usr", "pwd");
ftp_chdir($ftp,'uploads/');
echo count(glob(ftp_pwd($ftp) . '*'));
?>
Thanks!
Try to use count() and ftp_nlist() functions combination:
$ftp = ftp_connect("host");
ftp_login($ftp, "usr", "pwd");
echo count(ftp_nlist($ftp, 'uploads/'));
ftp_close($ftp);
use ftp_rawlist :
$files = ftp_rawlist($ftp, '/');
echo count($files).' files ..';
instead of
echo count(glob(ftp_pwd($ftp) . '*'));
Try something like this
<?php
#$ftp = ftp_connect("host");
#ftp_login($ftp, "usr", "pwd");
//ftp_chdir($ftp,'uploads/');
//echo count(glob(ftp_pwd($ftp) . '*'));
if ($handle = opendir(ftp_chdir($ftp,'uploads/'))) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
echo "Total number of files:$i";

Categories