0

how do i get a list of all the filenames of files in C:\xampp\htdocs\dump\uploads in php varible them get the value of php varible in js

  • You need [get all files in a directory php](https://stackoverflow.com/questions/15774669/list-all-files-in-one-directory-php) then [pass variable from php to javascript](https://stackoverflow.com/questions/23740548/how-do-i-pass-variables-and-data-from-php-to-javascript) – XMehdi01 Oct 27 '21 at 21:16
  • @TAHERElMehdi i got all files in a directory but i cant pass the varible i have tryed all ways listed in the wuestion u linked – Peter Playz Oct 27 '21 at 21:45
  • Yes there are a ways to do that and I answer with *JSON way*! – XMehdi01 Oct 27 '21 at 22:06

2 Answers2

0

To pass a variable from PHP to JS First you need to know that PHP is rendered on server side; However JS is executed on client side; So a way to send vars from PHP to JS is using JSON

<!-- In your file of PHP you have: -->
<!-- some code of php to generate variable of all your files... -->
<?php $files = ['dir1','file1.txt','img.jpg']; ?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<!-- here inside the same file you have your script js -->
<script type="text/javascript">
    // call your variable with format JSON
    var filesJSON = <?php echo "'".json_encode($files)."'"; ?>;
    console.log(JSON.parse(filesJSON)); //['dir1', 'file1.txt', 'img.jpg']
</script>
</body>
</html>
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
0

Serverside Read the files.

$files = [];
if ($handle = opendir('.')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $files[] = $entry;
        }
    }
    closedir($handle);
}

Render the page and echo $files in script tag. like below:

<script type="text/javascript">
    const files = JSON.parse(<?php echo "'".json_encode($files)."'"; ?>);    
    console.log('myFiles', files); 
</script>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79