How do I copy a file thant contains random filename - php

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

Related

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

saving ms word docx file using edraw in php

I have used the following code for saving open docx file.
javascript:
function SavetoServer(){
OA1.Save();
OA1.CloseDoc();
OA1.HttpInit();
OA1.HttpAddPostFile("C:\wamp\www\rte\sample2.docx");
document.OA1.HttpPost("http://localhost/rte/actor2.php");
}
php code "actor2.php"
<?php
header("http/1.1 200 OK");
$handle = fopen($_FILES['trackdata']['name'],"w+");
if($handle == FALSE)
{
exit("Create file error!");
}
$handle2 = fopen($_FILES['trackdata']['tmp_name'],"r");
$data = fread($handle2,$_FILES['trackdata']['size']);
fwrite($handle,$data);
fclose($handle2);
fclose($handle);
exit(0);
?>
The file is not saving when we changed in browser. Can anyone see a problem with this?
The HttpAddPostFile can add only the file from the remote website. It does work for the local disk file.
function SavetoServer()
{
if(document.OA1.IsOpened)
{
document.OA1.SetAppFocus();
document.OA1.HttpInit();
var sFileName = document.OA1.GetDocumentName();
document.OA1.HttpAddPostOpenedFile (sFileName); //save as the same file format with the sFileName then upload
//document.OA1.HttpAddPostOpenedFile (sFileName, 16); //save as docx file then upload
//document.OA1.HttpAddPostOpenedFile (sFileName, 0); //save as doc file then upload
//document.OA1.HttpAddPostOpenedFile (sFileName, -4143); //save as xls file then upload
//document.OA1.HttpAddPostOpenedFile (sFileName, 51); //save as xlxs file then upload
document.OA1.HttpPost("upload_weboffice.php");
if(document.OA1.GetErrorCode() == 0 || document.OA1.GetErrorCode() == 200)
{
var sPath = "Save successfully! You can download it at http://www.ocxt.com/demo/" + sFileName;
window.alert(sPath);
}
else
{
window.alert("you need enable the IIS Windows Anonymous Authentication if you have not set the username and password in the HttpPost method. you need set the timeout and largefile size in the web.config file.");
}
}
else{
window.alert("Please open a document firstly!");
}
}
upload_weboffice.php
<?php
$sql = sprintf("username=%s passwd=%s param=%s", $_POST['user'],$_POST['password'],$_POST['param']);
echo $sql;
$filecount = count($_FILES["trackdata"]["name"]);
echo "\r\n";
echo "file account:";
echo $filecount;
echo "\r\n";
$sql = sprintf("file=%s size=%s error=%s tmp=%s", $_FILES['trackdata']['name'],$_FILES['trackdata']['size'],$_FILES['trackdata']['error'],$_FILES['trackdata']['tmp_name']);
echo $sql;
echo "\r\n";
$filen = $_FILES['trackdata']['name'];
//$filen = iconv("UTF-8", "GBK", $filen);
$handle = fopen($filen,"w+");
if($handle == FALSE)
{
exit("Create file error!");
}
$handle2 = fopen($_FILES['trackdata']['tmp_name'],"r");
$data = fread($handle2,$_FILES['trackdata']['size']);
echo $data;
//file_put_contents($handle, "\xEF\xBB\xBF". $data);
//fwrite($handle,pack("CCC",0xef,0xbb,0xbf));
fwrite($handle,$data);
fclose($handle2);
fclose($handle);
exit(0);
?>

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

Passing uploaded files to another part of the script for onward processing

I have searched the forum but the closest question which is about the control stream did not help or I did not understand so I want to ask a different question.
I have an html form which uploads multiples files to a directory. The upload manager that handles the upload resides in the same script with a different code which I need to pass the file names to for processing.
The problem is that the files get uploaded but they don't get processed by the the other code. I am not sure about the right way to pass the $_FILES['uploadedFile']['tmp_name']) in the adjoining code so the files can be processed with the remaining code. Please find below the script.
More specif explanation:
this script does specifically 2 things. the first part handles file uploads and the second part starting from the italised comment extracts data from the numerous uploaded files. This part has a variable $_infile which is array which is suppose to get the uploaded files. I need to pass the files into this array. so far I struggled and did this: $inFiles = ($_FILES['uploadedFile']['tmp_name']); which is not working. You can see it also in the full code sample below. there is no error but the files are not passed and they are not processed after uploading.
<?php
// This part uploads text files
if (isset($_POST['uploadfiles'])) {
if (isset($_POST['uploadfiles'])) {
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/Uploads/';
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
}
echo "Files successfully uploaded . <br/>" ;
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode(',', $uploaded_files);
*/* This is the start of a script to accept the uploaded into another array of it own for* processing.*/
$searchCriteria = array('$GPRMC');
//creating a reference for multiple text files in an array
**$inFiles = ($_FILES['uploadedFile']['tmp_name']);**
$outFile = fopen("outputRMC.txt", "w");
$outFile2 = fopen("outputGGA.txt", "w");
//processing individual files in the array called $inFiles via foreach loop
if (is_array($inFiles)) {
foreach($inFiles as $inFileName) {
$numLines = 1;
//opening the input file
$inFiles = fopen($inFileName,"r");
//This line below initially was used to obtain the the output of each textfile processed.
//dirname($inFileName).basename($inFileName,'.txt').'_out.txt',"w");
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inFiles)) {
$line = fgets($inFiles);
$lineTokens = explode(',',$line);
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile,$line)===FALSE){
echo "Problem w*riting to file\n";
}
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(',',$line);
$searchCriteria2 = array('$GPGGA');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile2,$line)===FALSE){
echo "Problem writing to file\n";
}
}
}
}
echo "<p>For the file ".$inFileName." read ".$numLines;
//close the in files
fclose($_FILES['uploadedFile']['tmp_name']);
fflush($outFile);
fflush($outFile2);
}
fclose($outFile);
fclose($outFile2);
}
?>
Try this upload class instead and see if it helps:
To use it simply Upload::files('/to/this/directory/');
It returns an array of file names that where uploaded. (it may rename the file if it already exists in the upload directory)
class Upload {
public static function file($file, $directory) {
if (!is_dir($directory)) {
if (!#mkdir($directory)) {
throw new Exception('Upload directory does not exists and could not be created');
}
if (!#chmod($directory, 0777)) {
throw new Exception('Could not modify upload directory permissions');
}
}
if ($file['error'] != 0) {
throw new Exception('Error uploading file: '.$file['error']);
}
$file_name = $directory.$file['name'];
$i = 2;
while (file_exists($file_name)) {
$parts = explode('.', $file['name']);
$parts[0] .= '('.$i.')';
$new_file_name = $directory.implode('.', $parts);
if (!file_exists($new_file_name)) {
$file_name = $new_file_name;
}
$i++;
}
if (!#move_uploaded_file($file['tmp_name'], $file_name)) {
throw new Exception('Could not move uploaded file ('.$file['tmp_name'].') to: '.$file_name);
}
if (!#chmod($file_name, 0777)) {
throw new Exception('Could not modify uploaded file ('.$file_name.') permissions');
}
return $file_name;
}
public static function files($directory) {
if (sizeof($_FILES) > 0) {
$uploads = array();
foreach ($_FILES as $file) {
if (!is_uploaded_file($file['tmp_name'])) {
continue;
}
$file_name = static::file($file, $directory);
array_push($uploads, $file_name);
}
return $uploads;
}
return null;
}
}

swfupload destroy session? php

hy, i need a little help here:
i use SWFupload to upload images!
in the upload function i make a folder call $_SESSION['folder'] and all the files i upload are in 1 array call $_SESSION['files'] after uploads finish i print_r($_SESSION) but the array is empty? why that?
this is my upload.php:
if($_FILES['image']['name']) {
list($name,$error) = upload('image','jpeg,jpg,png');
if($error) {$result = $error;}
if($name) { // Upload Successful
$result = watermark($name);
print '<img src="uploads/'.$_SESSION['dir'].'/'.$result.'" />';
} else { // Upload failed for some reason.
print 'noname'.$result;
}
}
function upload($file_id, $types="") {
if(!$_FILES[$file_id]['name']) return array('','No file specified');
$isimage = #getimagesize($_FILES[$file_id]['tmp_name']);
if (!$isimage)return array('','Not jpg');
$file_title = $_FILES[$file_id]['name'];
//Get file extension
$ext_arr = split("\.",basename($file_title));
$ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,10);
//$file_name = $uniqer . '_' . $file_title;//Get Unique Name
//$file_name = $file_title;
$file_name = $uniqer.".".$ext;
$all_types = explode(",",strtolower($types));
if($types) {
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
return array('',$result);
}
}
if((!isset($_SESSION['dir'])) || (!file_exists('uploads/'.$_SESSION['dir']))){
$dirname = date("YmdHis"); // 20010310143223
$pathtodir = $_SERVER['DOCUMENT_ROOT']."/ifunk/uploads/";
$newdir = $pathtodir.$dirname;
if(!mkdir($newdir, 0777)){return array('','cannot create directory');}
$_SESSION['dir'] = $dirname;
}
if(!isset($_SESSION['files'])){$_SESSION['files'] = array();}
//Where the file must be uploaded to
$folder = 'uploads/'.$_SESSION['dir'].'/';
//if($folder) $folder .= '/'; //Add a '/' at the end of the folder
$uploadfile = $folder.$file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
} else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
} else {
//$_SESSION['files'] = array();
$_SESSION['files'][] .= $file_name;
chmod($uploadfile,0777);//Make it universally writable.
}
}
return array($file_name,$result);
}
SWFUpload doesn't pass the session ID to the script when you upload, so you have to do this yourself. Simply pass the session ID in a get or post param to the upload script, and then in your application do this before session_start:
if(isset($_REQUEST['PHPSESSID'])) {
session_id($_REQUEST['PHPSESSID']);
}
you must pass the session ID to the upload file used by swfupload.
more details here

Categories