Passing Array values into Function - php

I am trying to pass an array value into a function, but can't seem to get it to work. Here is what I am trying to do
I have a folder on my server called /Rpt
The /Rpt folder has a bunch of different folders inside of it (30 of them) - these folders contain a bunch of different files in them
I want to check most of the folders in /Rpt, and get the name and date of the latest file (based on last modified or created date) ... i want to store the results into an array, that has (folder path, file name of last file, file date of last file)
This query gets the folders that need to be checked
$sql = "my SQL here";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$arrValues = $stmt->fetchAll(PDO::FETCH_ASSOC);
This is a function that checks the specified folder, and displays the info i need (folder path, file name, file date)
function GetFileNameDate($location, $file_name, $file_date) {
$files = scandir($location);
$path = $location;
foreach ($files as $file) {
if (strpos($file, " ") !== false) {
$filename = $file;
$last_updated = date ("F d Y H:i:s", filemtime($path.'\\'.$file));
$results = array($filename=>$last_updated);
$file_name = key($results);
$file_date = reset($results);
return array($location, $file_name, $file_date);
}
}
}
When i call the function - and enter a specific path link in this example, it works OK and i shows the values i want to see
$FileNameDate = GetFileNameDate('E:\Rpt\FolderA');
echo $FileNameDate[0];
echo $FileNameDate[1];
echo $FileNameDate[2];
echo "<br/><br/>";
This is where I am having problems
I am trying to pass an array (list of folders from my SQL query) into the function, so i can output the (folder path, name of latest file, date of latest file) for each of the folders from SQL query
When i echo $locations (it lists all the folders which i am trying to pass to the function)
foreach ($arrValues as $row){
$locations = array($row['Folder']);
$FileNameDate = GetFileNameDate($locations);
echo $FileNameDate[0];
echo $FileNameDate[1];
echo $FileNameDate[2];
}
As per suggestion from #lovelace I also tried the following, but again just a blank page.
foreach ($arrValues as $row){
$locations = array($row['Folder']);
foreach ($locations as $FolderPath) {
$FileNameDate = GetFileNameDate($FolderPath);
echo $FileNameDate[0];
echo $FileNameDate[1];
echo $FileNameDate[2];
}
}
SOLUTION
see comment below to how above was fixed ... however I ended up implementing what i wanted a different way, sharing it in case anyone else needs similar functionality
function GetFileNameDate($location) {
$files = scandir($location);
$path = $location;
foreach ($files as $file) {
$iterator = new DirectoryIterator($path);
$mtime = 0;
$file = "";
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
if ($fileinfo->getMTime() > $mtime) {
$file = $fileinfo->getFilename();
$mtime = $fileinfo->getMTime();
}
}
}
return array($path, $file, $mtime);
}
}
foreach ($arrValues as $row){
$locations = array(rtrim($row['Folder']));
foreach ($locations as $FolderPath) {
$FileNameDate = GetFileNameDate($FolderPath);
echo $FileNameDate[0]; #folder
echo $FileNameDate[1]; #file
echo $FileNameDate[2]; #date
}
}

Related

Convert Recursive Directory Listing to MySQL Table

I need to list all files/folders in a given parent folder, and dump it out to mysql.
So far I have:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$dir = '/home/kevinpirnie/www';
function dirToArray( $dir ) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value) {
if (!in_array($value, array(".", ".."))) {
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
$result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
} else {
$result[] = $value;
}
}
}
return $result;
}
$res = dirToArray($dir);
echo '<hr />';
echo '<pre>';
print_r($res);
echo '</pre>';
What I am stuck on is how I can assign ID's to the directories, and then associate them with their parent ID's.
Right now, this code sort of does what I need it to, I just need to be able to convert it to mysql insert statements, yet keep the associative structure, and I am braindead from a long long week of work.
In the end, I am looking to have a table structure similar to:
FileID, FolderID, ParentFolderID, FileName
How can I do this?
try something like this:
function dirToDb($res, $parentId = 0)
{
foreach ($res as $key => $value) {
if (is_array($value)) {
$db->exec("insert into table (path, parentId) VALUES (?, ?)", [$key, $parentId]);
dirToDb($value, $db->fetch("SELECT LAST_INSERT_ID()"));
} else {
$db->exec("insert into table (path, parentId) VALUES (?, ?)", [$value, $parentId]);
}
}
}
$res = dirToArray($dir);
dirToDb($res);
I have modified your code a little. Now for every directory,
index 0 point to directory index
index 1 point to parent directory index
index 2,3,....n points to files
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$dir = '/home/kevinpirnie/www';
$GLOBALS['I'] = 0; // root folder given index 0
function dirToArray( $dir , $parent) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value) {
if (!in_array($value, array(".", ".."))) {
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
$result[$value] = [++$GLOBALS['I']]; // add folder index
$result[$value][] = $parent; // add parent folder index
$result[$value][] = dirToArray($dir . DIRECTORY_SEPARATOR . $value, $GLOBALS['I']);
} else {
$result[] = $value;
}
}
}
return $result;
}
$res = dirToArray($dir, $GLOBALS['I']);
echo '<hr />';
echo '<pre>';
print_r($res);
echo '</pre>';
echo '</pre>';
You can now insert the data into mysql tables directly using a similar recursive loop (if you do not want to use mysql auto generated id)
If you want to use auto generated mysql id, you should do insertion in two passes. In first pass insert the folder data and get the id from mysql insert id function. Then create an associative array map
$array_map[$current_folder_id] = mysqli_insert_id()
Then update this id in the second recursive pass
I think you need to insert folder names too as records into the DB, otherwise you wont get parent ID. But, in your result the folder names are missing as record items. I modified your code with assumption that you don't need the result as array but the SQL statement only.
<?php
$qry = array();
$result = $conn->query("SELECT MAX(FileID) as lastid FROM YOUR-TABLE-NAME-HERE");
$row = $result->fetch_assoc();
$id = $row['lastid'];
function dirToSql($dir, $parent) {
global $qry;
global $id;
$result = array();
$cdir = scandir($dir);
foreach($cdir as $key => $value) {
if(!in_array($value, array('.', '..'))) {
$id++;
$qry[] = "('".$id."', '".$dir."', '".$parent."', '".$value."')";
if(is_dir($dir . DIRECTORY_SEPERATOR . $value)) {
dirToSql($dir . DIRECTORY_SEPERATOR . $value, $id);
}
}
}
return $qry;
}
$dir = '/home/kevinpirnie/www';
$sql = dirToSql($dir, 0);
//Here is your SQL Statement
echo $qry = "INSERT INTO YOUR-TABLE-NAME-HERE (`FileID`, `FolderID`, `ParentFolderID`, `FileName`) VALUES ".implode(',', $sql);
You can optimize the code & the query if needed
Every row in your Mysql directory table has three columns -
Directory Id, Directory name, parent id
For each insert the parent id will specify the parent of current directory in a row. For the Root directory parent id is 0
A really useful way to structure your database is with nested sets. Joomla uses this for things like article categories. These can be infinitely nested under one another.
enter link description here

Sort Images by Date Modified

I have a small script that puts images from a folder into a web page.
I would like to sort by DATE MODIFIED anyone know how to do this?
function php_thumbnails($imagefolder,$thumbfolder,$lightbox)
{
//Get image and thumbnail folder from function
$images = "portfolio/" . $imagefolder; //The folder that contains your images. This folder must contain ONLY ".jpg files"!
$thumbnails = "portfolio/" . $thumbfolder; // the folder that contains all created thumbnails.
//Load Images
//load images into an array and sort them alphabeticall:
$files = array();
if ($handle = opendir($images))
{
while (false !== ($file = readdir($handle)))
{
//Only do JPG's
if(eregi("((.jpeg|.jpg)$)", $file))
{
$files[] = array("name" => $file);
}
}
closedir($handle);
}
//Obtain a list of columns
foreach ($files as $key => $row)
{
$name[$key] = $row['name'];
}
//Put images in order:
array_multisort($name, SORT_ASC, $files);
//set the GET variable name
$pic = $imagefolder;
You need to use filemtime function to retrieve the files modification time, and then use it to build your multisort help array.
...
if(eregi("((.jpeg|.jpg)$)", $file))
{
$datem = filemtime($images . '/' . $file);
$files[] = array("name" => $file, "date" => $datem);
}
}
...
...
...
foreach ($files as $key => $row)
{
$date[$key] = $row['date'];
}
//Put images in order:
array_multisort($date, SORT_ASC, $files);

php - Compare name files in directory with sql row

I am trying to create a script that compare the names of the files in a directory with a row in my database in order to get all the files that are not present in the database list.
The script I have so far prints out the files in the directory however when I try to compare the values with my sql I have a lot of results repeated.
How can I compare the name of the files in order to get all the name files that are not listed in my database?
Directory:
a.mp4
0.mp4
b.mp4
34.mp4
c.mp4
Database rows:
> Date---------------Name---------------video_path
> 01-01-01----------|jonh--------------|a.mp4
> 02-01-01----------|andrea------------|b.mp4
> 03-01-01----------|faith-------------|c.mp4
result should be:
0.mp4
34.mp4
SCRIPT:
$directory = '/var/www/html/EXAMPLE/resources/';
$files1 = scandir($directory, 1);
if ( $files1 !== false )
{
//$filecount = count( $files );
foreach ($files1 as $i => $value) {
$sqlfindTmp = "SELECT * FROM `videos`";
if ($resultTmp = mysqli_query($conn,$sqlfindTmp)) {
while ($row=mysqli_fetch_row($resultTmp)) {
if ($row[3] == $value) {
}else{
echo $value . "<br/>";
}
}
}
}
}
else
{
echo 0;
}
The way you have structured your code right now is that it makes an SQL query for every file and on each of those queries it retrieves the whole database, which might not be a problem right now but when your dataset grows will slow things down.
I would suggest restructuring your code so you first query the database for all filenames, save this to an array and then loop through the files, checking if they are in the database.
// Query database
$sqlFind = 'SELECT `video_path` FROM `videos`';
$result = mysqli_query($conn, $sqlFind);
$db = []; // create empty array
while ($row = mysqli_fetch_row($result))
array_push($db, $row[0]);
// Check files
$files1 = scandir($directory, 1);
if ( $files1 !== false ) {
foreach ($files1 as $i => $value) {
if (in_array($value, $db)) {
// File exists in both
} else {
// File doesn't exist in database
}
}
} else {
echo 0;
}
I agree with Kalkran, get the 'video_path' values into an array and do this once. scandir returns all the filenames into an array as well. So you can use a simple array_diff to get an array of files in the directory that aren't in 'video_path'.
So I would try :
$sqlFind = 'SELECT `video_path` FROM `videos`';
$result = mysqli_query($conn, $sqlFind);
$db = []; // create empty array
while ($row = mysqli_fetch_row($result))
array_push($db, $row[0]);
// Check files
$files1 = scandir($directory, 1);
$filesOfInterest = $files1 ? array_diff($files1,$db) : null;

PHP, Create dynamic list from files in a directory

I have a directory of files who's main purpose is to store php variables for inclusion into other files in the site. Each file contains the same set of variables, but with different values.
for example:
event1.php
<?php
$eventActive = 'true';
$eventName = My First Event;
$eventDate = 01/15;
?>
event2.php
<?php
$eventActive = 'true';
$eventName = My Second Event;
$eventDate = 02/15;
?>
In addition to calling these variables in other pages, I want to create a page that contains a dynamic list, based on the variables stored in each file within the directory.
Something like (basic concept):
for each file in directory ('/events') {
if $eventActive = 'true'{
<p><? echo $eventName ?></p>
}
}
What is the best way to do this?
Create an Event class or an array of each event. Then populate it from the directory.
$index = 0;
foreach (array_filter(glob($dir.'/*'), 'is_file') as $file) {
#include $file; // Parses the file, so the variables within are set.
$events[$index]['active'] = $eventActive;
$events[$index]['name'] = $eventName;
$events[$index]['date'] = $evetnDate;
$index++;
// OR
// $events[] = new Event($eventName, $eventDate, $eventActive);
}
// Now the $events array contains all your events.
// List out the active ones
foreach ($events as $event) {
echo ($event['active'] === 'true') ? $event['name'] : '';
// OR
// echo $event->isActive() ? $event->getName() : '';
}
Ok, so I spend some time with it and was able to reslove the issue with a cleaner solution, but utilizing an external json file to store the values
<?php
$json = file_get_contents('events.json');
$jsonArray = json_decode($json, true); // decode the JSON into an associative array
foreach ($jsonArray as $value) {
if (($value['active'] === 't') && ($value['fromDate'] >= $currentDate)) {
echo '<p>'.$value['title'].' '.$value['fromDate'].' - '.$value['toDate'].'</p>';
}
}
echo $currentDate;
?>

Reading a File Name with PHP

I'm writing a news script, and I'm having trouble making a way for the files to be deleted.
How can I change this script so that the <input type="checkbox" /> has a value of the file in the same row?
<?php
// This function reads all available news
function getNewsList(){
$fileList = array();
// Open the actual directory
if ($handle = opendir("news")) {
// Read all file from the actual directory
while ($file = readdir($handle)) {
if (!is_dir($file)) {
$fileList[] = $file;
}
}
}
rsort($fileList);
return $fileList;
}
// new
$list = getNewsList();
print("<table>\n");
print("<tr><td> </td><td>Article Title:</td><td>Post Date:</td></tr>\n");
foreach ($list as $value) {
$newsData = file("news/".$value);
$newsTitle = $newsData[0];
$submitDate = $newsData[1];
unset ($newsData['0']);
unset ($newsData['1']);
$newsContent = "";
foreach ($newsData as $value) {
$newsContent .= $value;
}
print("<tr>");
print("<td><input type=\"checkbox\" name=\"check_files[]\" value=\"$file\" /></td>");
print("<td>$newsTitle</td>");
print("<td>");
print("$submitDate");
print("</td>");
print("</tr>\n");
}
print("</table>\n");
I have a similar script for managing files, and it's something like $dirArray[$index] for the file name, but I can't figure out how to adapt this script to work the same way, because I'm too new to PHP.
Thanks for the help!
EDIT: This is the line where the file name needs to be: (instead of $file, which doesn't work for some reason):
print("<td><input type=\"checkbox\" name=\"check_files[]\" value=\"$file\" /></td>");
The $file variable isn't defined anywhere, you could try this:
replace
$newsData = file("news/".$value);
with
$file="news/".$value;
$newsData = file($file);
In your script, it looks like the current file name is stored in $value, because $list = getNewsList(); is an array of filenames, and your doing a foreach on it : foreach ($list as $value) {
Try replacing the second foreach loop with:
foreach ($newsData as $content) {
$newsContent .= $content;
}
and then use this line to show the file:
print("<td><input type=\"checkbox\" name=\"check_files[]\" value=\"$value\" /></td>");

Categories