I'm trying to create an Intranet page that looks up all pdf documents in a UNC path and the returns them in a list as hyperlinks that opens in a new window. I'm nearly there however the following code displays the FULL UNC path - My question how can I display only the Filename (preferably without the .pdf extension too). I've experimented with the basename function but can't seem to get the right result.
//path to Network Share
$uncpath = "//myserver/adirectory/personnel/";
//get all files with a .pdf extension.
$files = glob($uncpath . "*.pdf");
//print each file name
foreach ($files as $file)
{
echo "<a target=_blank href='File:///$file'>$file</a><br>";
}
The links work fine it just the display text shows //myserver/adirectory/personnel/document.pdf rather than just document. Note the above code was taken from another example I found whilst researching. If there's a whole new better way then I'm open to suggestions.
echo basename($file);
http://php.net/basename
Modify your code like this:
<?
$uncpath = "//myserver/adirectory/personnel/";
//get all files with a .pdf extension.
$files = glob($uncpath . "*.pdf");
//print each file name
foreach ($files as $file)
{
echo "<a target=_blank href='File:///$file'>".basename($file)."</a><br>";
}
?>
You may try this, if basename() does not work for some reason:
$file_a = explode('/',$file);
if (trim(end($file_a)) == '')
$filename = $file_a[count($file_a)-2];
else
$filename = end($file_a);
Related
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
The code I have should output a jpg from a list of files in a directory however it is not. I have trawled this site and tried different methods but not helped. I am a relative beginner at php so looking for any help at all.
I have tried using img src in the php code but I am trying to get the image to display within a Wordpress post so I cannot echo the img src within the script. I have tried file_get_contents and read file as well but it may be my lack of knowledge holding me back.
<?php
$imagepath = htmlspecialchars($_GET["image"]);
$imagenum = htmlspecialchars($_GET["num"]);
define('LOCALHOST', 'localhost' === $_SERVER['SERVER_NAME'] );
If(LOCALHOST){
define('PATH_IMAGES', 'this_path');
}else{
define('PATH_IMAGES', '../../../Images/');
}
$arrnum = $GLOBALS[imagenum] - 1;
$dirname = PATH_IMAGES . $GLOBALS[imagepath]."/";
$images = scandir($dirname);
rsort($images);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
header('Content-type: image/jpeg');
file_get_contents('$dirname$images[$arrnum]');
}
}
?>
Have you tried readfile(...); should read and output the file. In your example you are not outputting the image data
http://php.net/manual/en/function.readfile.php
I need open rar archive, search all *.txt files, read this files and put content in php array
$file="archive.rar";
$ext = pathinfo($file, PATHINFO_EXTENSION);
$tmp=$_SERVER['DOCUMENT_ROOT'].'/tmp';
if($ext=='rar'){
$archive = RarArchive::open($file);
$entries = $archive->getEntries();
foreach ($entries as $entry) {
echo file_get_contents($entry->getName());// not working
$entry->extract($tmp);
}
$archive->close();
}
The RarEntry::getName() method returns only path relative to archive. The file_get_contents() function knows nothing about this archive and it just try to find a regular file in current directory. You can use the rar:// protocol wrapper according to format:
rar://<url encoded archive name>[*][#[<url encoded entry name>]]
e.g.
echo file_get_contents('rar://' . $file . '#' . $entry->getName());
I have a html file listing links to artists' pages. What I want to do is to use a php script to list them instead of listing them manually. I also would like to have a thumbnail image above each corresponding link, but I want to get the links first before I add the images. I'm using the following script but it's not working:
<?php
$directory = "C:/wamp/myprojects/UMVA/web/includes/artists";
$phpfiles = glob($directory . "*.html");
foreach($phpfiles as $phpfile)
{
echo ''.$phpfile.'';
}
?>
The folder containing the html files is artists. It doesn't work using the full pathname and it doesn't work using just 'artists' or '/artists' as the pathname. The 'artists' folder is in the same directory 'web' as the php file with the script. What am I missing here?
this should actually do the trick:
$htmlFiles = glob("$directory/*.{html,htm}", GLOB_BRACE);
source
Not sure where is the error, but you can also use SPL Iterators, like GlobIterator, in a more reusable way. GlobIterator returns SplFileInfo objects that provides many useful informations about your file.
Here are the doc pages:
http://fr2.php.net/manual/en/class.globiterator.php
http://fr2.php.net/manual/en/class.splfileinfo.php
Here is an example:
$it = new GlobIterator('C:/wamp/myprojects/UMVA/web/artists/*.jpg');
foreach ($it as $file) {
// I added htmlspecialchars too, never output unsafe data without escape them
echo '' . htmlspecialchars($file->getFilename()) . '';
}
if your directory is always 'C:/wamp/myprojects/UMVA/web/artists', I think you can try scandir( $dirname ) instead of glob().
Here is a simple script that will look for html files in the current directory create and a hyperlink based on the title tag.
<?php
// Get all HTML files in the directory
$html_files = glob("*.{html,htm}", GLOB_BRACE);
$url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// Print out each file as a link
foreach($html_files as $file) {
$contents = file_get_contents($file);
$start = strpos($contents, '<title>');
if ($start !== false) {
$end = strpos($contents, '</title>', $start);
$line = substr($contents, $start + 7 , $end - $start - 7);
echo "<center>$line</center><br>\n";
}
}
?>
Save this file as index.php place the html files in the folder and browse to the URL.
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']
}