I have 2 questions about a PHP file with an array like so:
$test = array('test1.txt' => '<random>', 'test2.txt' => '<random>', 'test3.txt' => '<random>', 'test4.txt' => '<random>', 'test5.txt' => '<random>');
I also have files on my server like so:
/home/test1.txt
/home/test2.txt
/home/test3.txt
/home/test4.txt
/home/test5.txt
How would I go by checking that every file that is defined in the array also exists in the folder /home/ and that all files in /home/ are defined in the array?
Q2) Is there a way to automatically grab the file names in /home/*.txt and automatically insert them into an empty array like:
$test = array('' => '<random>',
'' => '<random>',
'' => '<random>',
'' => '<random>',
'' => '<random>');
Thank you!
try this:
foreach ($test as $fileName => $value) {
if(file_exists("/home/{$fileName}")) {
//exists
} else {
//Does not exist.
}
}
Q1) You can check if a file is on your server from an array of path with file_exists function.
foreach ($test as $str_filename=> $random) {
if (file_exists('/home/' . $str_filename) === false) {
echo 'A file is missing on server';
}
}
You can grab .txt file with glob function like this.
foreach (glob('/home/*') as $str_filename) {
if (array_key_exists($str_filename, $test) === false) {
echo 'A file is missing on array';
}
}
Q2) If random is the content from the file, you can grab it with file_get_contents function.
$test = [];
foreach (glob('/home/*.txt') as $str_filename) {
$test[$str_filename] = file_get_contents('/home/' . $str_filename);
}