I have a directory with images and I need to check a specific column of a table in my joomla database to see which files exist in the directory but not in the database and delete them.
What I've tried so far has not worked at all
my code is this
$dir = 'directory/of/files';
$files1 = scandir($dir);
$db =& JFactory::getDBO();
$query = "SELECT image FROM #__tablename WHERE something LIKE 'something else'";
$db->setQuery($query);
$result = $db->loadResultArray();
foreach ( $files1 as $file ) {
if (stripos($result, $file) === false) {echo 'file '.$file.' does not exist in database '; unlink($dir.$file);}
else {echo 'file '.$file.' exists in db ';}
}
Any ideas?
Thank you in advance
You problem is that in if(stripos($result, $file)), $result is an array, not a string. Turn on error reporting in the Joomla Configuration to see this. You should be seeing a message like:
Warning: stripos() expects parameter 1 to be string
However, I recommend the following change as it is a bit cleaner:
$dir = 'directory/of/files';
$files1 = scandir($dir);
$db = JFactory::getDBO();
$query = "SELECT image FROM #__tablename WHERE something LIKE 'something else'";
$db->setQuery($query);
$result = $db->loadResultArray();
$diff = array_diff($files1, $result);
// print_r($diff);die;
foreach ( $diff as $file ) {
unlink($dir.$file);
}
Uncomment the print_r first to check it is what you want.
This is the code that I finally managed to write and do what I need
$preImagePath = 'some/path/';
$fullImagePath = $params->get('extra1');//more of the path
$value = $params->get('extra3');
$initfile = scandir($preImagePath.$fullImagePath);
$files1 = array_diff($initfile, array('.', '..'));
$db =& JFactory::getDBO();
$query = "SELECT image FROM #__table WHERE column LIKE '".$value."'";
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result ) {
$imagearray .= $result->image.' ';
}
foreach ( $files1 as $file ) {
if (strpos($imagearray, $fullImagePath.$file) === false) { unlink($preImagePath.$fullImagePath.$file); }
}
Related
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
}
}
How to delete folder with images and mysql record news that does not exist?
Dont work. Why?
$resnotid = mysqli_query($db, "SELECT id FROM objects");
$idarray[] = array();
$namefolderarray[] = array();
while($rownotid = mysqli_fetch_array($resnotid)) {
$idarray[] = $rownotid['id'];
}
$dir = opendir('upload');
while($folder = readdir($dir)) {
if (is_dir('upload/'.$folder) && $folder != '.' && $folder != '..') {
$namefolderarray[] = $folder;
}
}
$delid = array_diff($namefolderarray, $idarray);
rmdir('upload/'.$delid.'/');
The method array_diff returns an array. So you have to iterate over that array.
$del_arr = array_diff($namefolderarray, $idarray);
foreach ($del_arr as $delid) {
rmdir('upload/'.$delid.'/');
}
Update 1
The previous solution only works for empty folders. If you have any content in the folders you must first delete the content. This can be done with an recursive function that iterates over the contents.
function rmdir_recursively($path) {
if (is_dir($path)){
$list = glob($path.'*', GLOB_MARK);
foreach($list as $item) {
rmdir_recursively($item);
}
rmdir($path);
} else if (is_file($path)) {
unlink($path);
}
}
$del_arr = array_diff($namefolderarray, $idarray);
foreach ($del_arr as $del_id) {
rmdir_recursively('upload/'.$del_id.'/');
}
Update 2
To also delete the database-records without a folder you can extend the code like this:
foreach ($del_arr as $del_id) {
rmdir_recursively('upload/'.$del_id.'/');
$del_id_escaped = mysqli_real_escape_string($del_id);
mysqli_query($db, "DELETE FROM objects WHERE id='$del_id_escaped'");
}
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;
Ive the following Code , a function take a list of usernames and put in them in array then execute function called function get_all_friends , Code works fine and no error , my question here how to adjust the code if ive bulk of usernames lets say like 10k ?
Like reading from file include all usernames name and put them in array using
$file_handle = fopen("users.txt")
please advise !
<?PHP
$user1 = "usernamehere";
$user2 = "usernamehere";
$user3 = "usernamehere";
$u[] = $user1;
$u[] = $user2;
$u[] = $user3;
function get_all_friends($users)
{
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, TOKEN_KEY, TOKEN_SECRET);
$list = array();
foreach($users as $user)
{
$result = $connection->get( 'friends/ids', array(
"screen_name"=> $user)
);
foreach($result->ids as $friend)
{
$list[] = $friend;
}
}
return $list;
}
//call the function
$result = get_all_friends($u);
foreach($result as $res)
{
$query = "INSERT INTO friends (userid, name, grade, flag) VALUES ($res, 'name', 100, 0 ) ";
mysql_query($query);
}
//to print the databse result
echo "row<br />";
$res = mysql_query("SELECT * FROM friends");
while ($row = mysql_fetch_assoc($res))
{
print_r($row);
}
?>
Something like the following should work (untested):
$filename = "users.txt";
$file_handle = fopen($filename, "r");
$contents = fread($file_handle, filesize($filename));
$usernames = preg_split("/ (,|\\n) /", $contents);
fclose($file_handle);
The usernames must be separated by a comma or a new line.
Although, if you are positive that the usernames will only be separated by a new line OR a comma, this code will be faster:
$filename = "users.txt";
$file_handle = fopen($filename, "r");
$contents = fread($file_handle, filesize($filename));
// new line:
$usernames = explode("\n", $contents);
// or comma:
$usernames = explode(",", $contents);
fclose($handle);
Please choose only one of the $usernames definitions.
Specifically to answer the question, check file(..) - "Reads entire file into an array"
http://php.net/manual/en/function.file.php
Although you probably don't want to be doing it this way, if the file is large you'll be much better off reading sequentially or doing some sort of direct import.
I have a folder named "Comics" and sub folders in that directory with the names of comics + the issue
Example:
/Comics <-- Main Folder
/Amazing Spider-Man 129 <-- Sub Folder
/Hellblazer 100 <-- Sub Folder
/Zatanna 01 <-- Sub Folder
Now what i want to do is scan the Comics directory and output each folder name as a mysql insert query. The actual folder name needs to be seperated as "Comic Name" & "Comic Issue".
Example Query
mysql_query("INSERT INTO comics (name, issue) VALUES ('Amazing Spider-Man', '129')");
I got this far and now i want to add a query check to see if the comic exists or not.
<?php
$main_folder = 'K:/Comics/'; // should be K:\Comics\ but I changed it because of the highlighting issue
$folders = glob($main_folder.'* [0-9]*', GLOB_ONLYDIR);
$comics_series = array();
foreach($folders as $folder){
$comics_series[] = preg_split('/(.+)\s(\d+)/', str_replace($main_folder, '', $folder), -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
}
$values = array();
foreach($comics_series as $pair){
$values[] = "('".mysql_real_escape_string($pair[0])."', '".((int) $pair[1])."')";
}
$check_query = mysql_query("SELECT * FROM comics WHERE name='".$values[0]."' AND issue='".$values[1]."'");
if ($check_query == '0'){
$query = 'INSERT INTO comics (name, issue) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
}
?>
is that the right format for the query_check?
<?php
$main_folder = './Comics'; // should be K:\Comics\ but I changed it because of the highlighting issue
$folders = glob($main_folder.'* [0-9]*', GLOB_ONLYDIR);
$comics_series = array();
foreach($folders as $folder){
$comics_series[] = preg_split('/(.+)\s(\d+)/', str_replace($main_folder, '', $folder), -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
}
$values = array();
foreach($comics_series as $pair){
$values[] = "('".mysql_real_escape_string($pair[0])."', '".((int) $pair[1])."')";
}
$query = 'INSERT INTO comics (name, issue) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
?>
If you are just stuck on splitting the comic name plus issue, check out the explode function
If you are struggling with file/folder traversal, I suggest taking a look at glob. It's much easier.
<?php
if ($handle = opendir('K:\Comics')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$comicName = null;
$pieces = explode(' ', $file); // explode the $file
// if the last element is a number..
if(is_numeric(end($pieces))) {
$comicIssue = end($pieces); // set the issue to a variable
array_pop($pieces); // remove the last element of the array
// loop through the rest of the array and put the pieces back together
foreach($pieces as $value) {
$comicName .= " $value"; // append the next array element to $comicName
}
} else {
echo "not issue number";
}
}
}
closedir($handle);
}
?>