PHP Search FTP for certain File by extension and Download it - php

i'm stuck with a Project i'm currently working on.
I have to make a PHP Script that uploads a File to a specific FTP, the file gets processed by another script which is observing the FTP on the Fly. After the processing is done a new File is generated with one of 4 possible file extensions and the original file gets deleted automaticly. Here's where my Problem starts, i'm not that much into PHP for i'm working with it far too rarely.
So i have to search for the file with one of the four possible Extensions and download it to the machine where the PHP Script is running on and the search needs to be done by this PHP Script. Any suggestions how to achieve this for i have not a glimps of a clue :(

You can not search through FTP protocol.
You have to list a directory and then search for desired file(s) locally:
$ftp = ftp_connect( $ftpHost );
ftp_login( $ftp, $ftpUsername, $ftpPassword ) or die( 'Oh No!' );
$files = ftp_nlist( $ftp, 'www/myDir' );
$filteredFiles = preg_grep( '/\.php$/i', $files );
ftp_close($ftp);
With above example all the files in www/Dir directory with .php extension are now in $filteredFiles array.
Alternatives:
If your remote server allow SSH2 connection, you can retrieve the files list through a SSH2 connection;
If your remote server is php/HTTP enabled, you can write a php script on remote server to search file(s) and then perform an HTTP request.

Related

php FTP file: How can check if a file is open by another process

I have a list of videos (.mp4) in a remote server.
From my application codeigniter, I connect with FTP to the remote server and I can list those videos.
I want to rename those files, but I should verify if file is opened by another process (video is playing) before renaming it.
How can check if a file is opened by another process with php?
This my code:
$ftp = new Simple_ftp();
$ftp->init("server",'login','password');
$conn_id = $ftp->connexion();
if($conn_id == 3){
$files = $ftp->ls('path_files');
foreach($files as $file){
...
}
}
You cannot check for that having only FTP access.
If the server is using Linux based OS and you have ssh access, you can remotely connect and use the lsof program.
There is no way of knowing by FTP, however other methods I suggest taking a look at the following: flock
It checks for file locking

How to upload file in php from browser with no user input

I am working on a php web app .
I need to upload a file to the web server, with customer info - customers.csv.
but this process needs to be automated ,
The file will be generated in a Point of Sale app , and the app can open a browser window with the url ...
first i taught i would do something like this www.a.com/upload/&file=customers.csv
but read on here that is not possible,
then i taught i would set a value for the file upload field and submit form automatically after x seconds. Discovered thats not possible .
Anybody with a solution , will be appreciated .
EDIT
I have tried this and it works ,file is uploaded to remote server
is it working only because the php script is running on the same pc where csv is sitting ???
$file = 'c:\downloads\customers.csv';
$remote_file = 'customers.csv';
// set up basic connection
$conn_id = ftp_connect('host.com');
// login with username and password
$login_result = ftp_login($conn_id,'user','password');
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
// close the connection
ftp_close($conn_id);
This is of course not possible, imagine how this could be abused to upload on linux as example the /etc/passwd. The only way it might be possible is to use a Java Applet, but this is for sure not the best way.
You could try to let your PoS Application make a web request with the customers.csv file and let a WebAPI handle the upload, this may be possible, but I have no expierence with Point of Sale Applications.
Best might be, if the solution above cannot be considered, to just prompt the user to provide the file above and check over name + content if it is the correct one.
This is a bit tricky, but if your CSV is not too long, you could encode it in base64, send to the webserver as a GET parameter and then, in the server side, decode and store it as a CSV file.
If the file is too big to do that, you have to use other method, like the java applet pointed by #D.Schalla or even install and configure a FTP server, and make the Point of Sale app uploads the file there.
Other alternative, specially good if you cannot modify the sale app, is to install a web server in the client side and write a small php script to handle the upload process. In this way, the sale app could call a local url (something like: http:// localhost/upload.php) and it's this script the one in charge to upload the file which can be achieve with a classical HTTP POST, a FTP connection or any other way you can think about.
MY Solution , which will work with out setting up web server on client side.
This is for windows but can be adapted to linux
On client side
Local Application opens cmd and runs this command ftp -n -s:C:\test.scr
WHICH opens test.scr - a file with ftp commands e.g.
open host.com
user1
passwOrd
put C:\downloads\customers.csv public_html/customers.csv
more info here :
http://support.microsoft.com/kb/96269
more commands :
http://www.nsftools.com/tips/MSFTP.htm#put

PHP Read/Write files on remote server

I'm making a utility that provides a GUI to easy edit certain values in a csv file on a remote server. My boss wants the utility in php running on the private webserver. I'm new to php, but I was able to get the GUI file modifier working locally without issues. The final piece now is rather than the local test file I need to grab a copy of the requested file off of the remote server, edit it, and then replace the old file with the edited one. My issue is uploading and downloading the file.
When I searched for a solution I found the following:
(note in each of these I am just trying to move a test file)
$source = "http://<IP REMOTE SERVER>/index.html";
$dest = $_SERVER['DOCUMENT_ROOT']."index.html";
copy($source, $dest);
This solution ran into a permissions error.
$source ="http://<IP REMOTE SERVER>/index.html";
$destination = $_SERVER['DOCUMENT_ROOT']."newfile.html";
$data = file_get_contents($source);
$handle = fopen($destination, "w");
fwrite($handle, $data);
fclose($handle);
This also had a permissions error
$connection = ssh2_connect('<IP REMOTE SERVER>', 22);
ssh2_auth_password($connection, 'cahenk', '<PASSWORD>');
ssh2_scp_recv($connection, '/tmp/CHenk/CHenk.csv', 'Desktop/CHenk.csv');
This solution has the error Fatal error: Call to undefined function ssh2_connect() which I have learned is because the function is not a part of the default php installation.
In closing, is there any easy way to read/write files to the remote server through php either by changing permissions, having the php extension installed, or a different way entirely that will work. Basically I'm trying to find the solution that requires the least settings changes to the server because I am not the administrator and would have to go through a round about process of getting any changes done. If something does need to be changed instructions on doing so or a link to instructions would be greatly appreciated.
Did you set the enable-url-fopen-wrapper in your php.ini?(only if your php version is older)
Please look # php remote files storing in example 2

Mirror folder from remote server in pure PHP

I want to keep a folder on one machine in sync with a folder on another. This is for a WordPress deployment plugin so I can't rely on rsync or other commands being present on either machine. PHP and a web server will be available on both machines and ideally it would work over HTTP.
My current thinking is that the requesting machine posts the local file list with last modified dates to a script on the other machine. The other machine compares with its files and responds with the modified files - either a list of files to be fetched individually or with the changed files inlined in the response.
I'd rather use an existing solution if one exists, though. Any ideas?
I've created a simple set of classes to implement this: https://github.com/outlandishideas/sync
On the server, e.g. example.com/remote.php:
const SECRET = '5ecR3t'; //make this long and complicated
const PATH = '/path/to/source'; //sync all files and folders below this path
$server = new \Outlandish\Sync\Server(SECRET, PATH);
$server->run(); //process the request
On the client:
const SECRET = '5ecR3t'; //this must match the secret key on the server
const PATH = '/path/to/destination'; //target for files synced from server
$client = new \Outlandish\Sync\Client(SECRET, PATH);
$client->run('http://example.com/remote.php'); //connect to server and start sync
Your best bet is checking when the script was last run and then uploading the folder with ftp_* functions.
<?php
$username = 'root'; // and this
$password = 'password'; // this also
$host = 'my-remote-server.com'; // and this
$remote_backup = 'backups/'; // folder on remote server to upload to
$backup_folder = 'to_backup/'; // folder to backup
$temp_folder = 'temp_files/'; // a folder on the local server i can write to
$last_run = file_get_contents("{$temp_folder}last_run.txt"); // You'll probably want to get this from a database instead
if($last_run <= strtotime('-1 day'))
{
file_put_contents("{$temp_folder}last_run.txt", time()); // Update the last time this was ran
$file = time() . '_backup.zip'; // what the file will be called both remotely and locally
$ftp = ftp_connect($host); // connect to the ftp server
ftp_login($ftp, $username, $password); // login to the ftp server
$zip = new ZipArchive; // create a new instance of ZipArchive
$zip->open($temp_folder . $file, ZIPARCHIVE::CREATE); // Create a new archive
foreach(glob($backup_folder . '*') as $file) // Loop through all files in the local backup directory
{
$zip->addFile($file); // add that file
}
ftp_chdir($ftp, $remote_backup); // cd into the remote backup folder
$upload = ftp_nb_put($ftp, $remote_backup . $file, $temp_folder . $file); // non-blocking put, uploads the local backup onto the remote server
while($upload === FTP_MOREDATA)
{
// do something else while we're waiting for the non-blocking upload to finish
}
ftp_close($ftp); // closes the connection
}
It should be non-blocking (well - the upload to the remote server), so if you don't have many files to zip it'll be fine to include on the index page for example. There isn't any error handling so you may want to add that in. It also doesn't delete the local backup, either, you may want to handle that.
In PHP I would not recommend it for a bunch of reasons.
I have exactly what you need as a python app.
This app is built to run as a service, you simply start it and forget about it :)
App: https://gist.github.com/8f62786582c6933395eb
Shell: https://gist.github.com/e08a99937c6f5deac4ab
Note: the shell file should be called fsyncd not fsyncd.sh :)
The PHP version of the above:
https://gist.github.com/3963cbc58793ff7e9773
Note: You need to get it running on both sites and configure each to connect to the other and set them to be executed by crons. Preferably not by WP crons.
I have the path to the directory that will be synced defined here:
define("PATH_DATA", PATH_ROOT . "data" . DIRECTORY_SEPARATOR);
In my case the data folder is in the script folder. You should just set an absolute path or use the WP core to get the WP uploads dir.
The principal is:
find a way to get the two servers capable of talking to each other.
I used a socket server/client approach.
You could do a HTTP _POST processor (server) and a HTTP _POST maker (client).
Keep a record of last sync time.
At certain intervals read folder for and record any files modified from the last sync time.
Send list of files to be updated with their modified timestamp to the other server.
It should compare your list to his records and tell you which of the files he does not have.
Send those files.
The receiver will write the files and set modified date to the one on the other server. (this is important, to avoid infinite loops)
Good luck.

PHP FTP transfer

I have files that are automatically uploaded onto a server from mobile phones, and I need to automatically transfer these files from the server to another server using PHP.
Could someone please explain how I would do this?
Thanks for any help
PHP has FTP functionality built in with FTP wrappers:
Allows read access to existing files and creation of new files via FTP. If the server does not support passive mode ftp, the connection will fail.
This means you can use FTP like any other file - an extremely simple example:
<?php
$data = file_get_contents('some/other/file.txt');
$fname = "ftp://name:yourpassword#127.55.41.10:21/some/path/filename.txt";
file_put_contents($fname,$data);
?>

Categories