PHP- Count files on a server that connected with FTP - php

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";

Related

PHP: read contents from a file and echo the name of the folder that file belongs to

There are a directory full of random folders and inside all those folders is name.txt
Example: abcd/name.txt, 1234/name.txt, xyz/name.txt
<?php $users_input = "Jonathan"; ?>
I want to check if $users_input is equal to the contents of any random folder's name.txt and echo THAT folder's name.
Like (if $users_input is equal to contents of 1234/name.text) {echo folder's name which is 1234}
You can use a RecursiveDirectoryIterator to achieve this, as follows:
$users_input = 'Jonathan';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/target/path'));
foreach ($iterator as $file)
{
if ($file->isDir()) {
continue;
}
$path = $file->getPathname();
$contents = file_get_contents($path);
if (strcmp($contents,$users_input)) {
echo $path.'<br\>';
}
}
You may want to include an additional check on the file name if the folders can contain other files with a different name and or extension.
Here's how the solution will look like based on Barmar's suggestion:
<?php
$users_input = "Jonathan";
$file_arr = glob("*/name.txt");
foreach ($file_arr as $path) {
$content = file_get_contents($path);
if (trim($content) === $users_input) {
echo "dirname: " . dirname($path) . "\n";
}
}
Thanks everyone.
Concluded with
$users_input = "Jonathan";
$directory = glob("*");
foreach ($directory as $path) {
if (is_dir($path)) {
$myfile = fopen($path."/name.txt", "r") or die("Unable to open file!");
if (fread($myfile,filesize($path."/name.txt")) == $users_input) {echo $users_input . " is in " . $path;}
fclose($myfile);
}
}

PHP Scandir Cloud Folder

I Would like to know how i could do a simple scandir of a folder in a cloud storage, or if it's even possible.
<?php
$dir = "C:/wamp64/www/test";
$a = scandir($dir);
$files = array_diff($a, array('.', '..'));
file_put_contents("C:/wamp64/www/test.txt", "");
foreach ($files as $key) {
file_put_contents("C:/wamp64/www/test.txt","$key \r\n", FILE_APPEND);
}
?>
I have this code currently working fine, but my cloud path is L:\2017 and putting those values will just say No such file or directory
Any help appreciated, and sorry for the inconvenience!
You should do something like this:
<?php
$path = '\\2017\somepath\';
$user = "username";
$pass = "password";
$drive_letter = "L";
system("net use ".$drive_letter.": \"".$path."\" ".$pass." /user:".$user." /persistent:no>nul 2>&1");
$location = $drive_letter.":/somepath/your_directory";
if ($handle = opendir($location)) {
while (false !== ($entry = readdir($handle))) {
echo "$entry";
}
closedir($handle);
}
?>

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

#!/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

php sftp file or folder

i am attempting to create a web based sftp page, the only part i am having problems with is trying to determin the the listed file is a file or folder. i am sucessfully listing a directory using
$connection = ssh2_connect($_SESSION['Server'], $_SESSION['Port']);
if(ssh2_auth_password($connection, $_SESSION['Username'], $_SESSION['Password']))
{
$sftp = ssh2_sftp($connection);
$dir = "ssh2.sftp://$sftp/$directory";
$handle = opendir($dir);
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$temp=$file;
if(strlen($directory) > 0)
$Path=$directory."/".$file;
else
$Path=$file;
$statinfo = ssh2_sftp_stat($sftp, "/".$Path);
echo "$temp<br />";
}
}
closedir($handle);
}
i attempted to use the is_dir() and is_file() php function on $file which works sucessfully when working on local filesystem, but when using SFTP both come back FALSE, i attempted to use ssh2_sftp_stat() but this only gives uid, gid, size access and modified times and i dont think there is anyting that can be used to identify files of folders, if anyone has a way to resolve this i would appreaciate it greatly
Vip32
I would strongly suggest using phpseclib for SSH2 purposes. It greatly simplifies tasks like this.
Solution for your problem using phpseclib should go something like this:
include('Net/SFTP.php');
$sftp = new Net_SFTP($_SESSION['Server'] . ':' . $_SESSION['Port']);
if (!$sftp->login($_SESSION['Username'], $_SESSION['Password'])) {
exit('Login Failed');
}
foreach($sftp->rawlist($dir) as $filename => $attrs) {
if ($attr['type'] == NET_SFTP_TYPE_REGULAR) {
echo $filename . ' is a regular file!';
}
if ($attr['type'] == NET_SFTP_TYPE_DIRECTORY) {
echo $filename . ' is a directory!';
}
}
These are the file type constants phpseclib uses:
file_types = array(
1 => 'NET_SFTP_TYPE_REGULAR',
2 => 'NET_SFTP_TYPE_DIRECTORY',
3 => 'NET_SFTP_TYPE_SYMLINK',
4 => 'NET_SFTP_TYPE_SPECIAL'
);

PHP - opendir on another server

I'm kinda new to PHP.
I've got two different hosts and I want my php page in one of them to show me a directory listing of the other. I know how to work with opendir() on the same host but is it possible to use it to get access to another machine?
Thanks in advance
Try:
<?php
$dir = opendir('ftp://user:pass#domain.tld/path/to/dir/');
while (($file = readdir($dir)) !== false) {
if ($file[0] != ".") $str .= "\t<li>$file</li>\n";
}
closedir($dir);
echo "<ul>\n$str</ul>";
You could use PHP's FTP Capabilities to remotely connect to the server and get a directory listing:
// set up basic connection
$conn_id = ftp_connect('otherserver.example.com');
// login with username and password
$login_result = ftp_login($conn_id, 'username', 'password');
// check connection
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
exit;
}
// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);
// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}
// Retrieve directory listing
$files = ftp_nlist($conn_id, '/remote_dir');
// close the FTP stream
ftp_close($conn_id);
I was unable to get the FTP suggestions to work so I took a more unconventional route, basically it yanks the html from the "Index of" page and extracts the filenames.
Index page:
Index of /files
Parent Directory
1.jpg
2.jpg
Extraction code:
$dir = "http://www.yoursite.com/files/";
$contents = file_get_contents($dir);
$lines = explode("\n", $contents);
foreach($lines as $line) {
if($line[1] == "l") { // matches the <li> tag and skips 'Parent Directory'
$line = preg_replace('/<[^<]+?>/', '', $line); // removes tags, curtousy of http://stackoverflow.com/users/154877/marcel
echo trim($line) . "\n";
}
}

Categories