Php我怎样才能检查文件夹中是否有同名文件?[closed]

vngu2lb8  于 2023-03-16  发布在  PHP
关注(0)|答案(1)|浏览(96)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

5天前关闭。
Improve this question
表单中有一个数字,这个数字构成了我将要创建的json文件的名称。

1.json
2.like 
3.json

我试着用下面的代码确认1.json文件是否在名为“json”的文件夹中,但是每次“文件名存在。请提供另一个文件名”时,它都会发出警告。我应该如何组织代码?

$open = "./json/$s_id" . '.json';
if(file_exists($open)) {
    echo "The File Name Is Available. Please Provide Another File Name";
    exit();
}
nr9pn0ug

nr9pn0ug1#

您可以尝试读取/json目录中的所有文件,并在文件列表中搜索以检查名称是否已被使用。
在这里我提供了一个小例子,我认为可以帮助您报告的问题:

<?php

//get the id form the $_GET Array or any other input
$file_id = $_GET['id_file'];

/**
 * So i create a filepath supposing that the json Dir is on the same level of the
 * php file, for convenience, in a rela world application this could be a problem in terms of security
 * if the json directory contains sensitive data.
 */
$jsonDir = __DIR__ . DIRECTORY_SEPARATOR . "json";

//We can use the scandir function to get the list of all the files presents in the json directory

$files = scandir($jsonDir);

//Now we can create the name of th json file, in this case combining the id received by the form and the json extension
$fileName = "$file_id.json";

/**
 *
 * if there aren't file int the directory or there is non file with the computed name
 * the filename is available.
 *
 */

if (count($files) < 1 || !in_array($fileName, $files)){
   //The filename is Available
    echo "Available";
}
else{
    //The filename is not Available
    echo "Not Available";
}

exit;

相关问题