


Output format requirements: PHP obtains the directory file list and uses it in JavaScript
Aug 22, 2025 pm 05:51 PMPHP side: Get the file list
First, we need to use PHP to read all file names in the specified directory. Here is a simple example code showing how to implement this function using opendir, readdir, and closedir functions.
<?php $files = []; $directory = 'C:\xampp\\htdocs\\dump\\uploads'; // Replace with your directory path if ($handle = opendir($directory)) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { $files[] = $entry; } } closedir($handle); } else { echo "Cannot open directory"; } // Output file list, convenient for debugging print_r($files); ?>
Code explanation:
- $files = [];: Initialize an empty array to store file names.
- $directory = 'C:\xampp\htdocs\dump\uploads';: Specify the directory path to read. Please modify this path according to your actual situation.
- opendir($directory): Opens the specified directory and returns a directory handle.
- readdir($handle): Read an entry from a directory handle, which can be a file or a subdirectory.
- $entry != "." && $entry != "..": Filter out the current directory (.) and the parent directory (..).
- $files[] = $entry;: Add the read file name to the $files array.
- closedir($handle): Close the directory handle and release the resource.
- print_r($files);: Print a file list for debugging.
Notes:
- Please make sure PHP has permission to access the specified directory.
- The directory path needs to use double backslashes (\\) or forward slashes (/).
Passing PHP array to JavaScript
Next, we need to pass the list of files obtained by PHP into JavaScript. A common method is to use the json_encode function to convert a PHP array into a JSON string and parse that string in JavaScript.
<script type="text/javascript"> const files = JSON.parse(<?php echo "'".json_encode($files)."'"; ?>); console.log('myFiles', files); </script>
Code explanation:
- json_encode($files): Convert PHP array $files to JSON string.
- echo "'".json_encode($files)."'";: output JSON strings to HTML pages and wrap them in single quotes to prevent JavaScript parsing errors.
- JSON.parse(): Use the JSON.parse() function in JavaScript to parse JSON strings and convert them into JavaScript arrays.
- console.log('myFiles', files);: Print the file list to the console for easy debugging.
Another way:
You can also directly embed JSON data into HTML's data attributes and then read in JavaScript:
<div id="file-list" data-files="'<?php" echo json_encode>'></div> <script> const fileListElement = document.getElementById('file-list'); const files = JSON.parse(fileListElement.dataset.files); console.log('Files from data attribute:', files); </script>
This method is clearer and avoids the direct output of PHP variables in script tags.
JavaScript side: Use file list
Now, we have successfully passed the list of files obtained by PHP to JavaScript. These file names can be used in JavaScript for various operations, such as dynamically generating lists, filtering files, etc.
// Example: Dynamically generate file list const fileListContainer = document.getElementById('file-list-container'); files.forEach(file => { const listItem = document.createElement('li'); listItem.textContent = file; fileListContainer.appendChild(listItem); });
Code explanation:
- document.getElementById('file-list-container'): Gets the HTML element used to display the file list.
- files.forEach(file => { ... });: Iterate over the file list array.
- document.createElement('li'): Create a new li element.
- listItem.textContent = file;: Set the text content of the li element to the file name.
- fileListContainer.appendChild(listItem): Adds the li element to the file list container.
Summarize:
Through the above steps, we have successfully implemented the function of using PHP to obtain a list of directory files and pass these file names into JavaScript for use. This method can be applied to various scenarios where file lists need to be loaded dynamically, such as image libraries, file management systems, etc. Please note that security is crucial, and it is important to verify and filter the files uploaded by users to prevent malicious code injection.
The above is the detailed content of Output format requirements: PHP obtains the directory file list and uses it in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Usefilter_var()tovalidateemailsyntaxandcheckdnsrr()toverifydomainMXrecords.Example:$email="user@example.com";if(filter_var($email,FILTER_VALIDATE_EMAIL)&&checkdnsrr(explode('@',$email)[1],'MX')){echo"Validanddeliverableemail&qu

Useunserialize(serialize($obj))fordeepcopyingwhenalldataisserializable;otherwise,implement__clone()tomanuallyduplicatenestedobjectsandavoidsharedreferences.

Usearray_merge()tocombinearrays,overwritingduplicatestringkeysandreindexingnumerickeys;forsimplerconcatenation,especiallyinPHP5.6 ,usethesplatoperator[...$array1,...$array2].

NamespacesinPHPorganizecodeandpreventnamingconflictsbygroupingclasses,interfaces,functions,andconstantsunderaspecificname.2.Defineanamespaceusingthenamespacekeywordatthetopofafile,followedbythenamespacename,suchasApp\Controllers.3.Usetheusekeywordtoi

ToupdateadatabaserecordinPHP,firstconnectusingPDOorMySQLi,thenusepreparedstatementstoexecuteasecureSQLUPDATEquery.Example:$pdo=newPDO("mysql:host=localhost;dbname=your_database",$username,$password);$sql="UPDATEusersSETemail=:emailWHER

The__call()methodistriggeredwhenaninaccessibleorundefinedmethodiscalledonanobject,allowingcustomhandlingbyacceptingthemethodnameandarguments,asshownwhencallingundefinedmethodslikesayHello().2.The__get()methodisinvokedwhenaccessinginaccessibleornon-ex

Usepathinfo($filename,PATHINFO_EXTENSION)togetthefileextension;itreliablyhandlesmultipledotsandedgecases,returningtheextension(e.g.,"pdf")oranemptystringifnoneexists.

Use the ZipArchive class to create a ZIP file. First instantiate and open the target zip, add files with addFile, support custom internal paths, recursive functions can package the entire directory, and finally call close to save to ensure that PHP has write permissions.
