PHP Formatted Date Links from files in a folder - php

I am very inexperienced with PHP. I have a folder on a website which will receive files named with a numeric date structure. I need href links to be created for the files which are dropped into this folder. I need the link text to be formatted by with a textual month and numeric day. For example:
File name "01-02-22 BULLETIN.pdf" becomes
<href="bulletins/2022/$file">January 2</a>.
I have been messing with the code below from this post PHP to create Links for files in a folder, but I can't seem to figure it out. The links are appearing but any date formatting I attempt returns "error Call to a member function format()."
Thanks for your help!
<?php
$dir = "bulletins/2022/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "<a href=bulletins/2022/$file>$file</a><br>";
}
closedir($dh);
}
}
?>

The html mark up is missing quotes
Here an example:
$some_path = "bulletins/2022";
$readdir=opendir($some_path);
while ($file = readdir($readdir))
{
if($file != '..' && $file !='.' && $file !='' && $file != ".htaccess")
{
echo "$file<br>"; // yours is missing the quotes which should always be escaped in php with a backslash
}
}
closedir($readdir);
You could also concider using php time(); as the filename which will give you a unix timestamp which can then be sorted and converted into a date and time.
This example will sort the files in a natural order
$some_path = "demo_track_previews";
$readdir=opendir($some_path);
while ($file = readdir($readdir))
{
if($file != '..' && $file !='.' && $file !='' && $file != ".htaccess")
{
if(!empty(file))
{
$all_files[] = $file; //put all files in array ready to sort
}
}
}
closedir($readdir);
if(!empty($all_files))
{
sort($all_files,SORT_NATURAL); //You can also try rsort($all_files,SORT_NATURAL);
foreach ($all_files as $key => $each_file)
{
echo "".$each_file."<br>";
}
}
EDIT: after comment
if you need just the date from the filename "01-02-22 BULLETIN.pdf"
then try this
foreach ($all_files as $key => $each_file)
{
$file_name_parts = explode(" ", $each_file); // seperate the filename where there is a space - $file_name_parts[0] will be 01-02-22
echo "".$file_name_parts[0]."<br>";
}

Related

Find file in a directory using preg_match?

I need to find a file in a directory that matches a certain condition. For example, I know the file name starts with '123-', and ends with .txt, but I have no idea what is in between the two.
I've started the code to get the files in a directory and the preg_match, but am stuck. How can this be updated to find the file I need?
$id = 123;
// create a handler for the directory
$handler = opendir(DOCUMENTS_DIRECTORY);
// open directory and walk through the filenames
while ($file = readdir($handler)) {
// if file isn't this directory or its parent, add it to the results
if ($file !== "." && $file !== "..") {
preg_match("/^".preg_quote($id, '/')."\\-(.+)\\.txt$/" , $file, $name);
// $name = the file I want
}
}
// tidy up: close the handler
closedir($handler);
I wrote up a little script here for ya, Cofey. Try this out for size.
I changed the directory for my own test, so be sure to set it back to your constant.
Directory Contents:
123-banana.txt
123-extra-bananas.tpl.php
123-wow_this_is_cool.txt
no-bananas.yml
Code:
<pre>
<?php
$id = 123;
$handler = opendir(__DIR__ . '\test');
while ($file = readdir($handler))
{
if ($file !== "." && $file !== "..")
{
preg_match("/^({$id}-.*.txt)/i" , $file, $name);
echo isset($name[0]) ? $name[0] . "\n\n" : '';
}
}
closedir($handler);
?>
</pre>
Result:
123-banana.txt
123-wow_this_is_cool.txt
preg_match saves its results to $name as an array, so we need to access by it's key of 0. I do so after first checking to make sure we got a match with isset().
You must test if the match was successful.
Your code inside the loop should be this:
if ($file !== "." && $file !== "..") {
if (preg_match("/^".preg_quote($id, '/')."\\-(.+)\\.txt$/" , $file, $name)) {
// $name[0] is the file name you want.
echo $name[0];
}
}

Listing Directories: Opendir()

I'm working on a small script and I want to list the contents of a directory, make them into hyperlinks, and then edit those hyperlinks to look pretty (I.e. not show an ugly super long path name), then limit the number files echoed back to the browser. Also, I need the most recent files echoed back only.
I was thinking about using this:
<?php
$path = "/full/path/to/files";
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$files .= ''.$file.'';
}
}
closedir($handle);
}
?>
or this:
<?php
$sub = ($_GET['dir']);
$path = 'enter/your/directory/here/';
$path = $path . "$sub";
$dh = opendir($path);
$i=1;
while (($file = readdir($dh)) !== false) {
if($file != "." && $file != "..") {
if (substr($file, -4, -3) =="."){
echo "$i. $file <br />";
}else{
echo "$i. <a href='?dir=$sub/$file'>$file</a><br />";
}
$i++;
}
}
closedir($dh);
?>
But I dont want to list the files like this:
C:/example/example2/Hello.pdf
I want to edit the variable. Is that possible? To make it say something as simple as "Hello."
I want to limit the amount of files listed as well. For example: only list the first 5 files, or last 5, etc. Is there a function or some kind of parameter for that?
I appreciate any help or push in the right direction. Thanks
I'm on my phone so providing a code example will be tough. Why not iterate through the directories, storing the file name in an array, with the absolute path as the value for that key?
EDIT: You can use basename to aid you in doing this.

Dynamic link created based on new file upload?

Every 72 hours I upload a new PHP file to my server. (well actually it is an xml file transformed on the server with php) Is there a method to create a link on an html page that links to the "new" PHP doc automatically everytime a new file is uploaded?
I don't want to manually change the link every 72 hours. I would ultimately like to have an html page with a list of links to every new doc that is uploaded. I found this for images but I need someting like this but for PHP files and links.
http://net.tutsplus.com/articles/news/scanning-folders-with-php/
Any help would be very appreciated.
I found a solution that add links to the xml files. Now I just need to figure out how to add a link to reference the xslt sheet for each new xml file that is upload AUTOMATICALLY. I am not sure how to do this but any help would be very helpful. Thanks for everyones help.
<?php
$count = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {$count++;
print("".$file."<br />\n");
}
}
echo '<br /><br />Return';
closedir($handle);
}
?>
To read in a directory of files and then sort them by upload time you can just use:
$files = glob("files/*.xml");
$files = array_combine($files, array_map("filemtime", $files));
arsort($files);
print "link: " . current($files); // make that an actual <a href=
You can do that pretty easily with PHP function readdir:
http://php.net/manual/en/function.readdir.php
Simply loop through the files in the directory where you upload files and have php output a link for each.
ie:
<?php
if ($handle = opendir('/path/to/upload_dir')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo '' . $file . '<br />';
}
}
closedir($handle);
}
?>
You'll need to edit the http:// URL on the href to point to the correct download URL for your server, as well as the server path for opendir.
Hope that helps.
list by filetype
<?php
if ($handle = opendir('/path/to/dir')) {
while (false !== ($file = readdir($handle))) {
if (strpos($file, '.php',1)||strpos($file, '.xml',1) ) {
echo "<p>$file</p>";
}
}
closedir($handle);
}

Read File Names From folder Only Keep Files with .iso extention

I have a script that gets a string from a config file and based on that string grabs the file names of a folder.
I now only need the iso files. Not sure if the best way is to check for the .iso string or is there another method?
<?php
// Grab the contents of the "current.conf" file, removing any linebreaks.
$dirPath = trim(file_get_contents('current.conf')).'/';
$fileList = scandir($dirPath);
if(is_array($fileList)) {
foreach($fileList as $file) {
//could replace the below if statement to only proceed if the .iso string is present. But I am worried there could be issues with this.
if ($file != "." and $file != ".." and $file != "index.php")
{
echo "<br/><a href='". $dirPath.$file."'>" .$file."</a>\n";
}
}
}
else echo $dirPath.' cound not be scanned.';
?>
If you only need the files with an extension of .iso, then why not use:
glob($dirPath.'/*.iso');
rather than scandir()
try this:
if(is_array($fileList)) {
foreach($fileList as $file) {
$fileSplode = explode('.',$file); //split by '.'
//this means that u now have an array with the 1st element being the
//filename and the 2nd being the extension
echo (isset($fileSplode[1]) && $fileSplode[1]=='iso')?
"<br/><a href='". $dirPath.$file."'>" .$file."</a>\n":'');
}
}
If you want it in an OOP style you could use:
<?php
foreach (new DirectoryIterator($dirPath) as $fileInfo) {
if($fileInfo->getExtension() == 'iso') {
// do something with it
}
}
?>

php sorted array and readfile not reading in order

I am trying to write a php function to save and then display comments on an article.
In my save.php, I am formulating the file with:
$file = "article1/comments/file".time().".txt";
Then using fwrite() to write to a directory.
In my index I have:
if ($handle = opendir('article1/comments')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files = array($file);
sort($files);
foreach($files as $comments){
echo "<div class='message'>";
readfile('article1/comments/'.$comments);
echo "&lt/div>";
}
}
}
closedir($handle);
}
For the most part this displays the comments in the correct order, but for some reason, some files are displaying out of order. Furthermore, if I change sort() to rsort(), there is no change in how they are displayed.
I presume this is because readfile() is not following the sorted array's order. So I am wondering for one, why readfile does not display the files in order from newest to oldest, and two, how can I make it display them correctly?
Thanks.
edit: I copied the directory of comments from the live site to my local xampp installation, and the comments are displayed in order locally, but using the same code on my site results in comments not being in order.
Take a look at DirectoryIterator, make sure to check 1st comment for DirectoryIterator's isFile() method, it should be enough to solve this question.
Try this:
$files = array();
if ($handle = opendir('article1/comments')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[] = $file; //adding file to array
}
}
closedir($handle);
}
//if array is not empty-check (can go here)
if(count($files)>0) {
sort($files);
foreach($files as $comments){
echo "<div class='message'>";
readfile('article1/comments'.$comments);
echo "</div>";
}//~foreach
}//~if
Please, use any database for this stuff! Don't use files! This is not realy secure and has low performance

Categories