重命名文件名并立即读取php中有问题的文件


Renaming filenames and immediately reading files having issues in php

我有pdf文件,这些文件是学生的成绩单。成绩单名称格式为<student full name(which can have spaces)><space><studentID>。我需要下载文件。为此,我使用了以下代码。

if(file_exists($folder_path.'/') && is_dir(folder_path)) { 
    $report_files = glob(folder_path.'/*'.'_*'.pdf' ); 
    if(count($report_files)>0)
    {
        $result_data = '';
        $result_data = rename_filenamespaces($report_files);
        var_dump($result_data);//this shows the edited filename
        foreach ($result_data as $file) { 
            if (strpos($file,$_GET['StudentID']) !== false) {
                 //code for showing the pdf docs to download
            }
        }
    }
}
//function for renaming if filename has spaces
function rename_filenamespaces($location)
{
    $new_location = $location; 
    foreach ($location as $file) {
       //check file has spaces and filename has studentID
       if((strpos($file," ")!==false)&& (strpos($file,$_GET['StudentID']) !== false))
       {
           $new_filename = str_replace(" ","-",$file);
           rename($file,$new_filename);
           $new_location = $new_filename;
       }
    }
    return $new_location;
}

变量$result_data给出了不带空格的文件名,但for each循环显示的是Warning:Invalid argument supplied for foreach()。但在运行该函数后,服务器目录中的文件名会立即更改。此警告仅首次显示。我无法解决这个问题。

$new_location = $new_filename;

$new_location是一个数组

$new_filename是字符串

您必须使用$new_location[$index]

或者尝试

foreach ($new_location as &$file) {
...
...
$file = $new_filename;