PHP文件上传异常:文件不存在且无法识别为Excel文件求助
Excel转CSV上传功能问题排查
我正在尝试实现Excel文件转CSV文件的功能,但上传文件时程序提示文件不存在,且无法将其识别为Excel文件,不知道该如何解决。
- 主页面截图:可见上传的是Excel文件
- 运行结果截图:提示文件不存在且无法识别为Excel文件
以下是相关代码:
<?php $folder_dir = "uploads/"; $target_file_dir = $folder_dir . ($_FILES["uploadFile"]["name"]); $target_file_ext = strtolower(pathinfo($target_file_dir, PATHINFO_EXTENSION)); $target_file_name = $_FILES["uploadFile"]["name"]; $output_dir = "outputs/"; // Check if file already exists if ($target_file_ext != "xls" && $target_file_ext != "xlsx") { header("Location: error.php"); } else { if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_file_dir)) { if ($target_file_ext == "xls") { $target_file_name_without_ext = substr($target_file_name, 0, -4); $output_file_dir = $output_dir . $target_file_name_without_ext; } if ($target_file_ext == "xlsx") { $target_file_name_without_ext = substr($target_file_name, 0, -5); $output_file_dir = $output_dir . $target_file_name_without_ext; } $output_file_name = $target_file_name_without_ext . ".csv"; exec("java -jar exceltocsvasg.jar $target_file_dir $output_file_dir"); header("Location: success_convert_file.php?converted_file={$output_file_name}"); } else { header("Location: error.php"); } }
代码问题及修复方案:
文件名截取逻辑漏洞:
若文件名包含多个点(如report.v2.xlsx),substr固定位数截取会丢失正确文件名,导致后续路径错误。改用pathinfo统一获取无扩展名文件名:$target_file_name_without_ext = pathinfo($target_file_name, PATHINFO_FILENAME);移除原有的两个扩展名判断截取逻辑,用上述代码替代即可。
缺少上传错误检查:
未验证$_FILES["uploadFile"]["error"]状态,上传过程中可能出现文件过大、临时目录不可写等错误,导致tmp_name无效。需先添加检查:if ($_FILES["uploadFile"]["error"] !== UPLOAD_ERR_OK) { error_log("上传错误代码: " . $_FILES["uploadFile"]["error"]); header("Location: error.php"); exit; }路径与权限问题:
确保uploads/和outputs/目录存在且拥有写权限;执行Java命令时使用绝对路径,避免因工作目录差异导致找不到jar包或上传文件:// 替换为实际服务器绝对路径 $absolute_upload_dir = "/var/www/html/uploads/"; $absolute_output_dir = "/var/www/html/outputs/"; $absolute_jar_path = "/var/www/html/exceltocsvasg.jar"; $target_file_dir = $absolute_upload_dir . basename($_FILES["uploadFile"]["name"]); $output_file_dir = $absolute_output_dir . $target_file_name_without_ext; exec("java -jar {$absolute_jar_path} {$target_file_dir} {$output_file_dir}");文件名安全风险:
直接使用用户上传的文件名存在路径遍历风险,用basename()过滤文件名:$target_file_dir = $folder_dir . basename($_FILES["uploadFile"]["name"]);
内容的提问来源于stack exchange,提问作者ariana
相关产品推荐
相关产品推荐

