php 下载文件的目录$download_dir = ; 获取文件内容$file_content = file_get_contentshttpslxopaoaeonet1txt; 将文件内容按行分割成数组$lines = exploden $file_content; 循环下载每一行的视频链接foreach $lines as $index = $line 去除空白字符 $lin
暂时没有发现代码缺陷,但需要注意以下几点:
-
在使用 file_get_contents() 函数时,应该先判断返回值是否为 false,如果是说明文件获取失败,需要进行相应的错误处理。
-
在使用 fopen() 函数时,应该先判断返回值是否为 false,如果是说明文件打开失败,需要进行相应的错误处理。
-
在下载文件时,应该先判断返回的 HTTP 状态码是否为 200,如果不是说明下载失败,需要进行相应的错误处理。
-
在下载文件时,应该先判断下载目录是否存在,如果不存在需要先创建目录。
-
在生成随机文件名时,应该使用更安全的随机数生成函数,比如 random_bytes()。
-
在下载文件时,应该使用更安全的文件名,可以使用 basename() 函数来获取 URL 中的文件名,然后使用 preg_replace() 函数过滤掉不安全的字符,比如 "../"。
-
代码中没有设置超时时间,如果下载的文件过大或者网络不稳定,可能会导致脚本长时间运行。可以使用 curl_setopt() 函数设置超时时间。
以下是修复后的代码:
$line) { // 去除空白字符 $line = trim($line); // 如果链接为空,则跳过 if (empty($line)) { continue; } // 生成随机文件名 $file_name = generate_random_file_name(); // 下载视频文件 download_file($line, $download_dir, $file_name . '.mp4'); } /** * 生成随机文件名 */ function generate_random_file_name() { $file_name = bin2hex(random_bytes(4)); return $file_name; } /** * 下载文件 */ function download_file($url, $dir, $file_name) { // 检查下载目录是否存在,如果不存在则创建目录 if (!file_exists($dir)) { mkdir($dir, 0777, true); } // 获取文件名 $file_name = basename($url); // 过滤不安全的字符 $file_name = preg_replace('/[^A-Za-z0-9-_.]/', '', $file_name); // 拼接完整的文件路径 $file_path = $dir . '/' . $file_name; // 初始化 curl $ch = curl_init($url); // 打开文件句柄 $fp = fopen($file_path, 'wb'); if ($fp === false) { die('Failed to open file: ' . $file_path); } // 设置 curl 选项 curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 设置超时时间为 60 秒 // 执行 curl $result = curl_exec($ch); if ($result === false) { die('Failed to download file: ' . $url); } // 获取 HTTP 状态码 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($http_code !== 200) { die('Failed to download file: ' . $url); } // 关闭 curl 和文件句柄 curl_close($ch); fclose($fp); } ?原文地址: https://www.cveoy.top/t/topic/clvX 著作权归作者所有。请勿转载和采集!