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');
Related
I have a script that downloads images from the external server and saves them in a folder at the root of the website. The script file is also in the root of the website.
folder for images: /public_html/images/
script: /public_html/script.php
When i run file manually (example.com/script.php) all downloaded image files are saved in the folder correctly. But when the file is executed by the cron job all the images are saved with sizes of 0 bytes.
I've tried to empty the folder before the cron job run. I've changed the permissions to 777. Log file when the script runs manually and as cron looks the same.
The cron job is set up in the cpanel crontab.
Please help me figure out what is going on.
$dir = "/home/example/public_html/images/";
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') continue;
unlink($dir.DIRECTORY_SEPARATOR.$item);
}
$ftp_server = 'www2.housescape.org.uk';
$ftp_conn = ftp_connect($ftp_server);
$ftp_user = 'user';
$ftp_pass = 'password';
ftp_set_option($ftp_conn, FTP_TIMEOUT_SEC, 3600);
if(ftp_login($ftp_conn, $ftp_user, $ftp_pass)){
ftp_pasv($ftp_conn, true);
$images = ftp_nlist($ftp_conn, '/images/');
$c = 0;
foreach($images as $image){
$c = $c + 1;
echo "ftp://user:password#www2.housescape.org.uk:21".$image." / ";
$urltoget="ftp://user:password#www2.housescape.org.uk:21".$image;
echo $thefile=basename($image);
echo "<br>";
$content = file_get_contents("ftp://user:password#www2.housescape.org.uk:21".$image);
file_put_contents("/home/example/public_html/images/".$thefile, $content);
}
if ($count1>0) { echo "No File Change"; }
ftp_close($ftp_conn);
}
else{
echo 'Failed Login!';
}
This is only a suggestion to help track down the error, not an answer:
Did you check whether the CRON PHP environment has allow_url_fopen enabled?
<?php
if (!ini_get('allow_url_fopen')) {
die("'allow_url_fopen' is not enabled in the php.ini");
}
#!/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
I need to transfer a file from my Unix machine to a Windows machine. Problem is i can transfer a file already created on my machine via ftp from unix to any machine. also i can open webdav connection create new file and save it there.
What i am unable to do is to write my code to upload my file fro my local location using webdav.
i tried using pear client but due to lack of documentation, i am still not able to achieve the task .
Here is my attempt:
include("/usr/share/pear/HTTP/WebDAV/Client.php");
global $filename, $logger;
try {
/* $client = new HTTP_WebDAV_Client();
$user="username";
$pass = "pwd";
$dir = "webdavs://".$user.":".$pass."#hostname/";
var_dump($client->stream_open($dir."test4.txt","w",null,$path));
$client->stream_write("HELLO WORLD! , I am great ");
$client->stream_close();
$client->dir_opendir($dir,array());
var_dump($client->dirfiles);
$req =new HTTP_Request($dir);
$req->setBasicAuth($user, $pass);
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$result = $req->addFile('file_upload_field', $filename);
if (PEAR::isError($result)) {
echo $result->getMessage();
} else {
$response = $req->sendRequest();
if (PEAR::isError($response)) {
echo $response->getMessage();
} else {
echo $req->getResponseBody();
}
}*/
$ftp_server = "hostname-ftp";
//$ftp_server = "hostname-webdav";
$connection = ftp_connect($ftp_server);
ftp_login($connection, 'user', 'pwd);
ftp_put($connection, $filename, $filename, FTP_BINARY);
unlink($filename);
} catch(Exception $e){
$message = "There was a problem while uploading" . $filename;
$logger->error($message);
}
It was a togh call, but i figured it out. I am adding my code snippet so it may be helpful for someone. Instead of uploading the file, i converted that file into data stream and then copied that data stream to my call that writes stream on webdav server.
try {
$filecsv = file_get_contents($filename);
$client = new HTTP_WebDAV_Client_Stream();
$user="user";
$pass = "pass";
$dir = "webdavs://".$user.":".$pass."#hostname/";
$client->stream_open($dir."db_user_exports.csv","w",null,$path);
$client->stream_write($filecsv);
$client->stream_close();
unlink($filename);
} catch(Exception $e){
$message = "There was a problem while uploading" . $filename;
$logger->error($message);
}
How can I upload a remote file from a link for example, http://site.com/file.zip to an FTP server using PHP? I want to upload 'Vanilla Forum Software' to the server and my mobile data carrier charges high prices, so if I could upload the file w/o having to upload it from my mobile I could save money and get the job done too.
Made you this function:
function downloadfile($file, $path) {
if(isset($file) && isset($path)) {
$fc = implode('', file($file));
$fp = explode('/', $file);
$fn = $fp[count($fp) - 1];
if(file_exists($path . $fn)) {
$Files = fopen($path . $fn, 'w');
} else {
$Files = fopen($path . $fn, 'x+');
}
$Writes = fwrite($Files, $fc);
if ($Writes != 0){
echo 'Saved at ' . $path . $fn . '.';
fclose($Files);
}
else{
echo 'Error.';
}
}
}
You may use it like this:
downloadfile("http://www.webforless.dk/logo.png","folder/");
Hope it works well, remember to Chmod the destination folder 777.
((If you need it to upload to yet another FTP server, you could use one of the FTP scripts posted in the other comments))
Best regards. Jonas
Something like this
$con=ftp_connect("ftp.yourdomain.com");
$login_result = ftp_login($con, "username", "password");
// check connection
if ($conn_id && $login_result) {
// Upload
$upload = ftp_put($con, 'public_html/'.$name, "LOCAL PATH", FTP_BINARY);
if ($upload) {
// UPLOAD SUCCESS
}
}
More info: http://php.net/manual/en/function.ftp-put.php
A ) download the file via an url :
$destination = fopen("tmp/myfile.ext","w");
//Myfile.ext is an example you should probably define the filename with the url.
$source = fopen($url,"r");
while (!feof($source)) {
fwrite($destination,fread($source, 8192));
}
fclose($source);
fclose($destination);
B) Upload the file on FTP :
$file = 'tmp/myfile.ext';
$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 "UPLOAD OK";
} else {
echo "ERROR";
}
ftp_close($conn_id);
fclose($fp);
This just a quick example , there is probably lot of improvement which can be done on this code , but the main idea is here.
Note : if you have a dedicated server it's probably faster and easier to download the file with a call to wget.
More info on FTP can be found in the doc
Simply:
copy('ftp://user:pass#from.com/file.txt', 'ftp://user:pass#dest.com/file.txt');
The PHP server will consume bandwidth upload and download simultaneously.
Create a php script in a web-accessible folder on your target server, change the values of $remotefile and $localfile, point your browser to the script url and the file will be pulled.
<?php
$remotefile="http://sourceserver.com/myarchive.zip";
$localfile="imported_archive.zip";
if(!copy($remotefile, $localfile)) {
echo("Transfer Failed: $remotefile to $localfile");
}
?>
I have an FTP server, but don't know the command to upload from a PHP form. I need a command to upload with WinSCP. My code so far is below:
<html>
<body>
<?php
if(isset($_FILES["uploaded"]))
{
print_r($_FILES);
if(move_uploaded_file($_FILES["uploaded"]["tmp_name"],"<root>/domains/sigaindia.com/public_html/reymend/".$_FILES["uploaded"]["name"]))
echo "FILE UPLOADED!";
}
else
{
print "<form enctype='multipart/form-data' action='fup1.php' method='POST'>";
print "File:<input name='uploaded' type='file'/><input type='submit' value='Upload'/>";
print "</form>";
}
?>
</body>
</html>
$host = "ftp.example.com";
$user = "anonymous";
$pass = "";
// You get this from the form, so you don't need to do move_uploaded_file()
$fname = "/public_html/new_file.txt";
$fcont = "content";
function ftp_writeFile($ftp, $new_file, $content, $debug=false) {
extract((array)pathinfo($new_file));
if (!#ftp_chdir($ftp, $dirname)) {
return false;
}
$temp = tmpfile();
fwrite($temp, $fcont);
rewind($temp);
$res = #ftp_fput($ftp, $basename, $temp, FTP_BINARY);
if ($debug) echo "a- '$new_file'".(($res)?'':" [error]")."<br/>";
fclose($temp);
return $res;
}
$ftp = ftp_connect($host);
if (!$ftp) echo "Could not connect to '$host'<br/>";
if ($ftp && #ftp_login($ftp, $username, $password)) {
ftp_writeFile($ftp, $fname, $fcont, true);
} else {
echo "Unable to login as '$username:".str_repeat('*', strlen($password))."'<br/>";
}
ftp_close($ftp);
http://au.php.net/manual/en/book.ftp.php
I have an FTP server, but don't know the command to upload from a PHP form. I need a command to upload with WinSCP. My code so far is below:
If you're talking about PHP and forms than that's HTTP - HTTP is not FTP and vice versa.
WinSCP is an SSH client. SSH is a different protocol from HTTP. SSH is a different protocol from FTP.
If you want your PHP script to transfer files uploaded to the webserver to an FTP server, try something like:
foreach ($_FILES as $f) {
if (file_exists($f['tmp_name'])) {
$dest = 'ftp://' . $username . ':' . $password .
'#' . $ftpserver . $ftp_path;
file_put_contents($f['tmp_name'], $dest);
}
}