Hello I suspect I am being silly but I am new to PHP coding. All I want to do is sort my results from this script below in a descending order, but I don't know what code to add and where to add it. Please can you help me with this.
<?php
$d = dir("01-Newsletters");
while (false != ($entry = $d->read())) {
if ($entry != "." && $entry != "..") {
echo "<tr><td>{$entry}</td><td><a href='01-Newsletters/{$entry}' target=_blank><img src='../../Site_data/Images/more.gif'/></a></td></tr>";}
}
$d->close();
?>
Currently it is giving this result
Previous Newsletters 2014-04-Newsletter.pdf
2014-07-Newsletter.pdf
2014-10-Newsletter.pdf
2015-01-Newsletter.pdf
2015-04-Newsletter.pdf
2015-08-Newsletter.pdf
You can use the following solution:
<?php
$d = dir("01-Newsletters");
$entries = [];
while (false != ($entry = $d->read())) {
if ($entry != "." && $entry != "..") {
$entries[] = $entry;
}
}
$d->close();
//order the entries...
sort($entries, SORT_STRING);
$entries = array_reverse($entries);
//output the $entries in DESC order...
for ($i = 0; $i < count($entries); $i++) {
echo "<tr><td>{$entries[$i]}</td><td><a href='01-Newsletters/{$entries[$i]}' target=_blank><img src='../../Site_data/Images/more.gif'/></a></td></tr>";
}
?>
if the folder name is 2015-8 I assume it is created on that particular day. On the basis of this assumption, you can use the following approach. Get files modified time store it in an array and then sort that array
$dir = "jays";
$d = dir($dir);
while (false != ($entry = $d->read()))
{
if ($entry != "." && $entry != "..")
{
$files[$entry] = filemtime( $dir.'/' . $entry);
}
}
arsort($files);
print_r($files);
$d->close();
Related
I want to copy images from one folder to another on server, now I use this code:
<?php
function read_dir($dir)
{
$list = array();
if (is_dir($dir))
{
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$list[] = $file;
}
}
}
closedir($handle);
}
return $list;
}
$src="oldfolder";
$dest="newfolder";
$list= read_dir($src);
foreach($list as $key => $val)
{
copy("$src/$val","$dest/$val");
}
echo "Done";
?>
But I need to copy just images selected by time - for example images uploaded between "now" and 5 min. ago..
Can anyone help?
Thanks
Now my PHP is like below. It seems that it run with "Done" result, but nothing is copied..
<?php
function read_dir($dir)
{
$list = array();
if (is_dir($dir))
{
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
$fpath = 'oldfolder'.$file;
if (file_exists($fpath)) {
if($file != "." && $file != ".." &&
DateTime::createFromFormat('U', filemtime($file)) < new DateTime("-5
minutes"))
{
$list[] = $file;
}
}
}
}
closedir($handle);
}
return $list;
}
$src="oldfolder";
$dest="newfolder";
$list= read_dir($src);
foreach($list as $key => $val)
{
copy("$src/$val","$dest/$val");
}
echo "Done";
?>
So this is my code, that works for me well - copy images between folders according to time (- 5 sec) set by other code in "time.txt" file:
<?php
function read_dir($dir)
{
$list = array();
if (is_dir($dir))
{
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
$fpath = 'oldfolder/'.$file;
if (file_exists($fpath)) {
$subor = fopen("./time.txt", "r");
$cas_txt=fgets($subor, 11);
fclose($subor);
$cas_zac = DateTime::createFromFormat('U', $cas_txt)->modify('-5 seconds');
if ($file != "." && $file != ".." && DateTime::createFromFormat('U',
filemtime($fpath)) > $cas_zac)
{
$list[] = $file;
}
}
}
}
closedir($handle);
}
return $list;
}
$src="oldfolder";
$dest="newfolder";
$list= read_dir($src);
foreach($list as $key => $val)
{
//copy file to new folder
copy("$src/$val","$dest/$val");
}
echo "Done";
?>
I have two more questions:
Please how can I rotate images in 180° by or after copy? Is it possible in one php code?
How can I send multiple files - images from my code - like an attachments by mail in php?
Thanks for your help.
You should use the filemtime function
Ok I have a directory with files named by date with the extension ".html".
What I am trying to do is list the contents of the directory, minus the file extension, ordered by date with newest on top.
I have been fiddling with the below code for hours.
<?php
if ($handle = opendir('update_table_cache')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." ) {
$dirFiles[] = $entry ;
rsort($dirFiles);
foreach($dirFiles as $entry) {
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry);
echo ''.$withoutExt.'<br>';
}
}
}
closedir($handle);
}
?>
This outputs something like this:
2016-01-18
2016-01-19
2016-01-18
There should only be one 2016-01-18 and it should be at the bottom. Why is there an extra 2016-01-18 at the top?
Edit: ok I changed it to the following:
<?php
if ($handle = opendir('update_table_cache')) {
$dirFiles[] = $entry ;
rsort($dirFiles);
foreach($dirFiles as $entry) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." ) {
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry);
echo ''.$withoutExt.'<br>';
}
}
}
closedir($handle);
}
?>
But this outputs:
2016-01-18
2016-01-17
2016-01-19
(I added another file "2016-01-17.html")
You're doing the output in the middle of the loop...
First you sort one element and print it, then sort two elements and print it.
Do the output after the loop.
This is what worked:
<?php
$dir = opendir('update_table_cache'); // Open the sucker
$files = array();
while ($files[] = readdir($dir));
sort($files);
closedir($dir);
foreach ($files as $file) {
//MANIPULATE FILENAME HERE, YOU HAVE $file...
if ($file != "." && $file != ".." ){
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file);
echo ''.$withoutExt.'<br>';
}
}
?>
Thanks to user CBroe for pointing me in the right direction!
I'm trying to write a program that will open up a directory (in this case: files/), scan all of the filenames (not including any directories or ".." or ".") within this directory, and search for the filenames in the specified files from the "pages" array. If the filename is NOT found in the pages, the file will be moved to "unused-content".
My current code does not work. How can I achieve this goal?
<?php
if($handle = opendir('files/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$file_names[] = $entry;
}
}
closedir($handle);
}
$pages = array("page1.html","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
for($x=0; $x<sizeOf($pages); $x++) {
$current_page = file_get_contents($pages[$x]);
for($i=0; $i<sizeOf($file_names); $i++) {
if(!strpos($current_page,$file_names[$i])) {
if (copy("files/".$file_names[$i],"files/unused-content/".$file_names[$i])) {
unlink("files/".$file_names[$i]);
}
}
}
}
?>
Thank you!
You don't need all that long code .. all you need is FilesystemIterator
$pages = array("1.xml","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
$dir = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
foreach ( $dir as $file ) {
if ($file->isFile() && in_array(strlen($file->getFilename()), $pages)) {
// copy
// unlink
}
}
See another example using GlobIterator
Try to do something like this:
<?php
if($handle = opendir('files/')) {
$i=0;
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$file_names[$i] = $entry;
}
$i++;
}
closedir($handle);
}
$pages = array("page1.html","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
for($x=0; $x<sizeOf($pages); $x++) {
$current_page = file_get_contents($pages[$x]);
for($i=0; $i<sizeOf($file_names); $i++) {
if(!strpos($current_page,$file_names[$i])) {
if (copy("files/".$file_names[$i],"files/unused-content/".$file_names[$i])) {
unlink("files/".$file_names[$i]);
}
}
}
}
?>
Hay all im using a simple look to get file names from a dir
if ($handle = opendir('news_items/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
}
}
}
the files are being outputted news last, oldest first.
How can i reverse this so the newest files are first?
Get the file list into an array, then array_reverse() it :)
the simplest option is to invoke a shell command
$files = explode("\n", `ls -1t`);
if, for some reason, this doesn't work, try glob() + sort()
$files = glob("*");
usort($files, create_function('$a, $b', 'return filemtime($b) - filemtime($a);'));
Pushing every files in an array whit mtime as key allow you to reverse sort that array:
<?php
$files = array();
if ($handle = opendir('news_items/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$mtime = filemtime('news_items/' . $file);
if (!is_array($files[$mtime])) {
$files[$mtime] = array();
}
array_push($files[$mtime], $file);
}
}
}
krsort($files);
foreach ($files as $mt=>$fi) {
sort($fi);
echo date ("F d Y H:i:s.", $mt) . " : " . implode($fi, ', ') . "\n";
}
?>
I have written this code having not used PHP for 2 years now to loop through a folder of photos and write them to the page in alphabetical order. It is a fairly simple request but it took me the best part of 15 minutes to write.
if ($handle = opendir('photos')) {
$count = 0;
$list[] = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$list[$count] = $file;
$count ++;
}
}
closedir($handle);
asort($list);
$sorted_list = array();
$sorted_list = array_values($list);
foreach ($sorted_list as $i => $value) {
echo "<li><img src=\"photos/$sorted_list[$i]\" alt=\"$sorted_list[$i]\" title=\"\"></li>\n";
}
}
Have I written it totally the wrong way? Are there ways I can improve the code? Any constructive feedback gladly received.
You could take advantage of the scandir() function, which will handle reading the directory as well as sorting the results.
$files = scandir('photos');
if ($files !== false)
{
foreach($files as $f) {
if ($f == '..' || $f == '.') continue;
echo '<li><img src="photos/'.$f.'" alt="'.$f.'" title=""></li>'."\n";
}
}
I edited it a bit for readability.
Try this:
$photos = glob('photos/*');
foreach($photos as $photo) {
echo "<li><img src=\"{$photo}" alt=\"{$photo}\" title=\"\"></li>\n";
}
http://us.php.net/manual/en/function.glob.php
You don't need the $count. This will give you the same result
$list[] = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$list[] = $file;
}
}
Replace sorting and displaying with just:
sort($list);
for ($i = 0; $i < count($list); $i++) {
echo "<li><img src=\"photos/{$list[$i]}\" alt=\"{$list[$i]}\" title=\"\"></li>\n";
}
You can replace
foreach ($sorted_list as $i => $value) {
echo "<li><img src=\"photos/$sorted_list[$i]\" alt=\"$sorted_list[$i]\" title=\"\"></li>\n";
}
with
foreach ($sorted_list as $value) {
echo "<li><img src=\"photos/$value\" alt=\"$value\" title=\"\"></li>\n";
}
Then you don't need to call array_values(), because it doesn't matter that the array keys aren't in numeric order.
A simplier way is using the scandir function:
$dir = 'photos';
$files = array_diff( scandir($dir), array(".", "..") );
foreach ($files as $i => $value) {
echo "<li><img src=\"photos/$value\" alt=\"$value\" title=\"\"></li>\n";
}
good luck!