Search through multiple directories for files PHP - php

New to php. I need to search through multiple directories on an ftp server and download files contained in them according to their date (which is contained in each file's name). So far I am running into issues with Array to string conversion - hopefully you can see what I am "trying" to do here and might be able to help me out.
<?php
$url = ' MY FTP SERVER';
$user = ' USERNAME ';
$pass = ' PASSWORD';
$target = 'LOCAL DIRECTORY';
$connection = ftp_connect($url) or die ("Could not connect to $url");
$loginBool = ftp_login($connection, $user, $pass);
if ($loginBool)
{
echo "Connected as $user at $url";
}else{
echo "Could not connect as $user";
}
ftp_chdir($connection, 'MOVE ONE FOLDER IN');
$ftpDirectories = ftp_nlist($connection, ".");
for($i=0; $i < (count($ftpDirectories)); $i++){
$directory = ("/MAIN DIR/$ftpDirectories[$i]/");
echo $directory;
ftp_chdir($connection, $directory);
echo ftp_nlist($connection, $directory);
}
?>
The logic, as I see it, works as follow:
Get a listing of all folders under the main folder which is stored in Array
Loop through each element of the array(folders on the ftp)and change into the directory
one by one
Print out the files (so I know its working)
What I still need to add:
After changing into a directory split the filenames into an array and compare them to
today's date -> download if the filenameDate[index] == today's date
THANK YOU FOR YOUR HELP!
EDIT
<?php
$url = 'pmike86.zxq.net';
$user = 'pmike86_zxq';
$pass = '******';
$target = 'C:\Folder\\';
$connection = ftp_connect($url) or die ("Could not connect to $url");
$loginBool = ftp_login($connection, $user, $pass);
if ($loginBool)
{
echo "Connected as $user at $url";
}else{
echo "Could not connect as $user";
}
ftp_chdir($connection, 'HW');
$ftpDirectories = ftp_nlist($connection, ".");
for($i=0; $i < (count($ftpDirectories)); $i++){
$directory = ("/HW/$ftpDirectories[$i]/");
echo $directory;
ftp_chdir($connection, $directory);
foreach (ftp_nlist($connection, $directory) as $item)
{
ftp_get($connection, $target, $item, FTP_BINARY);
}
}
?>

Related

Php: How can one automate a script to change dates everyday? [duplicate]

This question already has answers here:
PHP, How to get current date in certain format [duplicate]
(3 answers)
Closed 5 years ago.
#!/usr/bin/php
<?php
$username = "user";
$password = "pass";
$url = '10.168.8.666';
// 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/batman/Downloads/dbs';
$remoteDir = '/home/batbackup/Dropbox/dbs';
// 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)=='07-Jun-2017'){
# code...
ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
}
}
}
}
?>
I use this script to download backups from an sftp server everyday but i ve to manually change the date (in bold) in the script everyday. Question: is there a way i can make the script to change the date automatically so that i can set up a cron job?
Use date().
date('d-M-Y')
It will become
#!/usr/bin/php
<?php
$username = "user";
$password = "pass";
$url = '10.168.8.666';
// 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/batman/Downloads/dbs';
$remoteDir = '/home/batbackup/Dropbox/dbs';
// 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')) {
# code...
ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
}
}
}
}
?>
If you want it to always be, let's say, yesterday, you may use it with strtotime(), so
date('d-M-Y', strtotime('yesterday'))
Replace your date with
date('d-M-Y')
http://php.net/manual/fr/function.date.php
This will take server current time.

how to upload a csv file from any direcory to database

I am adding data from a file to my database. Currently the location of the files are limited to only those inside directory D:/. I want to be able to support adding files from multiple directories.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "stdprt";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$filename = "d:/" . $_POST['fname'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle)) !== FALSE) {
$num = count($data);
$row;
$sql = "INSERT into marks(regno,semister,subcode,subname,internals,externals,credits)values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]')";
//echo "INSERT into marks(regno,semister,subcode,subname,internals,externals,credits)values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]')";
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
echo "<br>";
}
?>
<h2>Uploaded Successfully....</h2>
back
If you are wanting to choose a file in another drive you can modify this line in your code and change the directory at the start.
$filename="d:/".$_POST['fname'];
So for example if you wanted to change the directory to drive F it would be like so:
$filename="f:/".$_POST['fname'];
If you wanted to enable the ability to specify a custom directory in your request then you could pass it through the same way you are passing fname. Say for example you passed your custom directory along in a key named cust_dir you could add it as the directory like so.
if($_POST['cust_dir']{
$filename=$_POST['cust_dir'].$_POST['fname'];
} else {
$filename="d:/".$_POST['fname'];
}
The code above would use a custom directory path that you passed in the $_POST variable if you passed one. If you do not pass cust_dir then it will default to directory d:/.

can't download file from ftp with ftp_get (no error)

I'm trying to download file from ftp, but whatever i tried i couldn't download any file from ftp and it is not giving any error.
My code fetching file names from database and compares these file names with existing ftp file(names). If file name exist on ftp i want to download this file to my local-destination folder.
I can read ftp file names but i can't download them. Hope you can help me.
Here is my code
error_reporting(E_ALL);
$ftp_server = "xx.xx.y12.34"; //server
$bt = ftp_connect($ftp_server); // connect to ftp
$username = "myusername"; $pass = "mypass"; //username and password
$connection = ftp_login($bt, $username, $pass); // login ftp with username and password
ftp_pasv($bt, true);
if ((!$bt) || (!$connection)) {
echo "failed";
exit;
}else {
$path = "/1_Swatch Files/LG Swatches/";
$destination_folder = "/home/faruk/lasenza/media/color_samples/";
// mysql connection codes..
$results = $readConnection->fetchAll($query); // fetch file names from database
$contents_on_server = ftp_nlist($bt, $path);
foreach($results as $result){
$check_file_exist = $result["CLR_CODE"].".gif";
if(in_array($check_file_exist, $contents_on_server)) {
$server_file = $result["CLR_CODE"].".gif";
if (ftp_get($bt, $destination_folder , $server_file, FTP_BINARY)) {
echo 'Succeeded';
}else{
echo "There was a problem";
}
break;
}
}
}

PHP download from remote server via sftp

This may have been asked before, I'm new to PHP and I'm trying to learn as much as I can, but this has really thrown me.
Basically what I want to know is, how would I use PHP code to get it to download everything from a remote server to a local location. It's getting it to download everything not just one file that I'm stuck on. So please can someone show/explain to me how I would do this?
What I've got so far:
<?php
$connection - ssh2_connect('example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$remote_dir="/remote_dir/";
$local_dir="/local_dir/";
$remote ="$remote_dir";
$stream = ssh2_exec($connection, $remote);
stream_set_blocking($stream,true);
$command=fread($stream,4096);
$array=explode(\n,$command);
$total_files=sizeof($array);
for($i=0;$i<$total_files;$i+++){
$file_name=trim($array[$i]);
if($file_name!=''{
$remote_file=$remote_dir.$file_name;
$local_file=$local_dir.$file_name;
if(ssh2_scp_recv($connection, $remote_file,$local_file)){
echo "File ".$file_name." was copied to $local_dir<br />";
}
}
}
fclose($stream);
?>
I think my $remote ="$remote_dir"; is wrong, and to be honest I've got $filename when I want the whole directory, this is all I have so far.
Here is a small code on how to read the folder and download all its files:
<?php
$host = 'localhost';
$port = 22;
$username = 'username';
$password = 'password';
$remoteDir = '/must/be/the/complete/folder/path';
$localDir = '/can/be/the/relative/or/absolute/local/path';
if (!function_exists("ssh2_connect"))
die('Function ssh2_connect not found, you cannot use ssh2 here');
if (!$connection = ssh2_connect($host, $port))
die('Unable to connect');
if (!ssh2_auth_password($connection, $username, $password))
die('Unable to authenticate.');
if (!$stream = ssh2_sftp($connection))
die('Unable to create a stream.');
if (!$dir = opendir("ssh2.sftp://{$stream}{$remoteDir}"))
die('Could not open the directory');
$files = array();
while (false !== ($file = readdir($dir)))
{
if ($file == "." || $file == "..")
continue;
$files[] = $file;
}
foreach ($files as $file)
{
echo "Copying file: $file\n";
if (!$remote = #fopen("ssh2.sftp://{$stream}/{$remoteDir}{$file}", 'r'))
{
echo "Unable to open remote file: $file\n";
continue;
}
if (!$local = #fopen($localDir . $file, 'w'))
{
echo "Unable to create local file: $file\n";
continue;
}
$read = 0;
$filesize = filesize("ssh2.sftp://{$stream}/{$remoteDir}{$file}");
while ($read < $filesize && ($buffer = fread($remote, $filesize - $read)))
{
$read += strlen($buffer);
if (fwrite($local, $buffer) === FALSE)
{
echo "Unable to write to local file: $file\n";
break;
}
}
fclose($local);
fclose($remote);
}
You can also resume this code to (it will not copy directories):
while (false !== ($file = readdir($dirHandle)))
{
if ($file == "." || $file == "..")
continue;
echo "Copying file: $file\n";
if(!ssh2_scp_recv($connection, $remoteDir . $file, $localDir . $file))
echo "Could not download: ", $remoteDir, $file, "\n";
}
If you do not use the full path on the remote folder it will not work:
opendir("ssh2.sftp://{$stream}{$remoteDir}")
Update: I was kindly corrected that this doesn't use sftp, but instead uses ftps. Here's a Stackoverflow link discussing using PHP to do SFTP.
The PHP docs already cover most of what you should need for this. Here's an example for fetching a list of the contents in the remote directory:
<?php
// set up basic connection
$ftp_server = "example.com";
$conn_id = ftp_ssl_connect($ftp_server);
// login with username and password
$ftp_user_name = "myuser";
$ftp_user_pass = "mypass";
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
// check connection
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name";
}
$buff = ftp_rawlist($conn_id, '.');
var_dump($buff);
ftp_close($conn_id);
?>
Here you will find all the examples for what you can do with SFTP using PHP.
http://phpseclib.sourceforge.net/sftp/examples.html
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
// outputs the contents of filename.remote to the screen
echo $sftp->get('filename.remote');
// copies filename.remote to filename.local from the SFTP server
$sftp->get('filename.remote', 'filename.local');
?>

saving mysql query as csv file on remote ftp server using php

I am trying to export a MySQL query result to a remote ftp server.
I have the below code but I am currently getting an error:
Warning: ftp_put() [function.ftp-put]: Opening ASCII mode data connection. in /home/hulamyxr/public_html/kisv2/xmltest/export.php on line 50
I would think that my $file = $csv_filename; might be the issue as this is fetching the csv file that has just been created on my local server?
any ideas?
My syntax is:
<?php
$host = 'localhost';
$user = 'un';
$pass = 'pwd';
$db = 'dbname';
$table = 'v2ReportingTable';
$file = 'export';
$datetime=date("Y-m-d H:i:s");
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
//Create a CSV for
$result = mysql_query("SELECT * FROM dbname.v2ReportingTable");
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$csv_filename = "export-" .$datetime.".csv";
$fp = fopen($csv_filename, 'w+');
if ($fp && $result)
{
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
}
//works till here
$ftp_server = "ftp.server.co.za";
$ftp_user_name = "un";
$ftp_user_pass = "pw";
$file = $csv_filename;
$remote_file = "/LocExports/".$file;
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// 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);
?>
Thanks Again
and it creates the file in the correct location but is a 0kb file and all FTP commands thereafter fail. It is likely that the client is behind a firewall. To rectify this use:
<?php
ftp_pasv($resource, true);
?>

Categories