Home > Net >  How to set php varible set in php and get filenames fromfolder
How to set php varible set in php and get filenames fromfolder

Time:10-28

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

CodePudding user response:

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>

CodePudding user response:

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>
  • Related