open file on client stored on server - php

I want to open a server stored html report file on a client machine.
I want to bring back a list of all the saved reports in that folder (scandir).
This way the user can click on any of the crated reports to open them.
So id you click on a report to open it, you will need the location where the report can be opend from
This is my dilemma. Im not sure how to get a decent ip, port and folder location that the client can understand
Here bellow is what Ive been experimenting with.
Using this wont work obviously:
$path = $_SERVER['DOCUMENT_ROOT']."/reports/saved_reports/";
So I though I might try this instead.
$host= gethostname();
$ip = gethostbyname($host);
$ip = $ip.':'.$_SERVER['SERVER_PORT'];
$path = $ip."/reports/saved_reports/";
$files = scandir($path);
after the above code I loop through each file and generate a array with the name, date created and path. This is sent back to generate a list of reports in a table that the user can interact with. ( open, delete, edit)
But this fails aswell.
So im officially clueless on how to approach this.
PS. Im adding react.js as a tag, because that is my front-end and might be useful to know.

Your question may be partially answered here: https://stackoverflow.com/a/11970479/2781096
Get the file names from the specified path and hit curl or get_text() function again to save the files.
function get_text($filename) {
$fp_load = fopen("$filename", "rb");
if ( $fp_load ) {
while ( !feof($fp_load) ) {
$content .= fgets($fp_load, 8192);
}
fclose($fp_load);
return $content;
}
}
$matches = array();
// This will give you names of all the files available on the specified path.
preg_match_all("/(a href\=\")([^\?\"]*)(\")/i", get_text($ip."/reports/saved_reports/"), $matches);
foreach($matches[2] as $match) {
echo $match . '<br>';
// Again hit a cURL to download each of the reports.
}

Get list of reports:
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/reports/saved_reports/";
$files = scandir($path);
foreach($files as $file){
if($file !== '.' && $file != '..'){
echo "<a href='show-report.php?name=".$file. "'>$file</a><br/>";
}
}
?>
and write second php file for showing html reports, which receives file name as GET param and echoes content of given html report.
show-report.php
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/reports/saved_reports/";
if(isset($_GET['name'])){
$name = $_GET['name'];
echo file_get_contents($path.$name);
}

Related

PHP save the file using the link found by the block ID on the page

On the page https://data.mos.ru/opendata/61241/ the first url with parameter "export/get?id=" contains the last actual link to download the open data csv file //op.mos.ru/EHDWSREST/catalog/export/get?id=989116 .
The problem is that the digital ending of the url after each update is different and is not known in advance.
I have a script that works and allows me to save a file at a pre-known file url (but it only saves the old version of the file, not the current one):
<?php
function downloadJs($file_url, $save_to)
{
$content = file_get_contents($file_url);
file_put_contents($save_to, $content);
}
downloadJs('https://op.mos.ru/EHDWSREST/catalog/export/get?id=989116', realpath("./img/feeds") . '/61241.zip');
$zip = new ZipArchive;$zip->open('./img/feeds/61241.zip');$zip->extractTo('./img/feeds/61241');$zip->close();
$directory = './img/feeds/61241/'; if ($handle = opendir($directory)) { while (false !== ($fileName = readdir($handle))) { $dd = explode($fileName); $newfile = '61241.csv'; rename($directory . $fileName, $directory.$newfile); } closedir($handle); }
echo "Ok!";
?>
I need to change this PHP script so that on the page https://data.mos.ru/opendata/61241/ first determined the first link to the download file by the parameter "export/get?id=", where the link is located.
I'm not sure if you understand what you mean.
we have:
<a target="_blank" href="//op.mos.ru/EHDWSREST/catalog/export/get?id=989116" onclick="yaCounter29850344.reachGoal('download_csv')...
Perhaps we will use a little regex to get that id.
Let's say you already have its html with file_get_contents:
preg_match('#get\?id=(\d+)".* onclick="[^"]+csv[^"]+"#', $html, $matches);
echo $matches[1]; // 989116

Mysql file upload and pdf browser viewer failing to work

I am trying to build an interface with between my Wordpress page and my practice management software. When I upload files directly to my practice management software a physical copy shows up in the patient file. When browsing files within the software, on first click, I am able to view them in a browser based pdf viewer. If I click again on the file link, the file downloads and opens on my PC's PDF software.
PROBLEM: currently my file uploads to the server and a physical file is placed in the patient file. When browsing files it will not show up in my PDF viewer. It downloads to my PC on the first click and opens into my PDF software. However, the same file, when uploaded directly to the software behaves as expected.
I see no difference in the two files. So I assume there must be a problem with the $contents variable in my query. I am only working with PDF files. To upload attachments in my private messaging software I am using the following code:
function action_getmsgup($uploadid) {
global $wpdb, $out;
$query = $wpdb->prepare("SELECT ID, post_mime_type, guid FROM {$wpdb->prefix}posts WHERE ID = %d", array($uploadid));
$rows = $wpdb->get_results($query, ARRAY_A);
foreach ($rows as $row) {
$url = $row['guid'];
$filename = basename($url);
$path = parse_url($url, PHP_URL_PATH); // just the path part of the URL
$parts = explode('/', $path); // all the components
$parts = array_slice($parts, -6); // the last six
$path = implode('/', $parts);
$filepath = ABSPATH . $path;
// Get file contents and make a blob.
$tmpfile = fopen($filepath, "r");
$contents = fread($tmpfile, filesize($filepath));
$out['filename'] = $filename;
$out['mimetype'] = $row['mimetype'];
$out['contents'] = $contents;
}
}
QUESTION: Is there a problem with my upload method that is not filling $contents correctly?

Check if file exists in .tar using PHP

In my program I need to read .png files from a .tar file.
I am using pear Archive_Tar class (http://pear.php.net/package/Archive_Tar/redirected)
Everything is fine if the file im looking for exists, but if it is not in the .tar file then the function timouts after 30 seconds. In the class documentation it states that it should return null if it does not find the file...
$tar = new Archive_Tar('path/to/mytar.tar');
$filePath = 'path/to/my/image/image.png';
$file = $tar->extractInString($filePath); // This works fine if the $filePath is correct
// if the path to the file does not exists
// the script will timeout after 30 seconds
var_dump($file);
return;
Any suggestions on solving this or any other library that I could use to solve my problem?
The listContent method will return an array of all files (and other information about them) present in the specified archive. So if you check if the file you wish to extract is present in that array first, you can avoid the delay that you are experiencing.
The below code isn't optimised - for multiple calls to extract different files for example the $files array should only be populated once - but is a good way forward.
include "Archive/Tar.php";
$tar = new Archive_Tar('mytar.tar');
$filePath = 'path/to/my/image/image.png';
$contents = $tar->listContent();
$files = array();
foreach ($contents as $entry) {
$files[] = $entry['filename'];
}
$exists = in_array($filePath, $files);
if ($exists) {
$fileContent = $tar->extractInString($filePath);
var_dump($fileContent);
} else {
echo "File $filePath does not exist in archive.\n";
}

Selecting file to be edited

i have an application that is used to edit .txt files. the application is made up of 3 parts
Displays contents of a folder with the files to be edited(each file is a link when clicked it opens on edit mode).
writing in to a file.
saving to file.
part 2 and 3 I have completed using fopen and fwrite functions that wasn't too hard. the part that i need help is part one currently I open the file by inputing its location and file name like so in the php file where i have the display function and save function:
$relPath = 'file_to_edit.txt';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath ! ");
but what i want is for the file to open in edit mode when clicked instead of typing in the files name every time.
$directory = 'folder_name';
if ($handle = opendir($directory. '/')){
echo 'Lookong inside \''.$directory.'\'<br><br>';
while ($file = readdir($handle)) {
if($file !='.' && $file!='..'){
echo '<a href="'.$directory.'/'.$file.'">'.$file.'<a><br>';
}
}
}
this is the code that ti use to display the list of files that are in a specified folder.
Can anyone give me some pointers how I can achieve this ? any help will be greatly appreciated.
To get content of file use file_get_contents();
To put content of file use file_put_contents(); with FILE_APPEND flag for editing.
To recieve list of files in directory you can use DirectoryIterator
Example:
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\n";
}
If you don't want to put filenames you can put read files once put in db assign ids to them and use links with id param. The other solution is to store files in session array and assign keys for them. When you want to get a file you just need to provide key instead of whole filename and path.
Example with $_SESSION
$file_arr = array();
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
if($fileInfo->isDot()) continue;
$file_arr[] = array("path" => $fileInfo->getPathname(), 'name' => $fileInfo->getFilename());
}
$_SESSION['files'] = $file_arr;
then in view you can use
foreach($_SESSION['files'] as $k=>$file)
{
echo "<a href='edit.php?f=".$k."'>'.$file['name'].'</a>";
}
and edit.php
$file = (int)$_GET['f'];
if(array_key_exits($file, $_SESSION['files'])
{
$fileInfo = $_SESSION[$file'];
//in file info you have now $fileInfo['path'] $fileInfo['name']
}

How to compare two file structures in PHP?

I have a function which gives me the complete file structure upto n-level,
function getDirectory($path = '.', $ignore = '') {
$dirTree = array ();
$dirTreeTemp = array ();
$ignore[] = '.';
$ignore[] = '..';
$dh = #opendir($path);
while (false !== ($file = readdir($dh))) {
if (!in_array($file, $ignore)) {
if (!is_dir("$path/$file")) {
//display of file and directory name with their modification time
$stat = stat("$path/$file");
$statdir = stat("$path");
$dirTree["$path"][] = $file. " === ".
date('Y-m-d H:i:s', $stat['mtime']) . " Directory ==
".$path."===". date('Y-m-d H:i:s', $statdir['mtime']) ;
} else {
$dirTreeTemp = getDirectory("$path/$file", $ignore);
if (is_array($dirTreeTemp))$dirTree =
array_merge($dirTree, $dirTreeTemp);
}
}
}
closedir($dh);
return $dirTree;
}
$ignore = array('.htaccess', 'error_log', 'cgi-bin', 'php.ini', '.ftpquota');
//function call
$dirTree = getDirectory('.', $ignore);
//file structure array print
print_r($dirTree);
Now here my requirement is , I have two sites
The Development/Test Site- where i do
testing of all the changes
The Production Site- where I finally
post all the changes as per test in
development site
Now, for example, I have tested an image upload in the Development/test site, and i found it appropriate to publish on Production site then i will completely transfer the Development/Test DB detail to Production DB, but now I want to compare the files structure as well to transfer the corresponding image file to Production folder.
There could be the situation when I update the image by editing the image and upload it with same name, now in this case the image file would be already present there, which will restrict the use of "file_exist" logic, so for these type of situations....HOW CAN I COMPARE THE TWO FILE STRUCTURE TO GET THE SYNCHRONIZATION DONE AS PER REQUIREMENT??
EDITED
the requirement has to be a script, which I am going to need as a joomla component functionality.. please reply as per this.
I would suggest using rsync for this.

Categories