本文正在参与「金石计划 . 瓜分6万现金大奖」的活动,旨在分享关于php oss文件读取和写入文件的技术知识,同时介绍workerman框架如何生成临时文件并通过浏览器下载。
背景
本文将详细讲解如何使用php进行OSS文件的读取和写入,以及如何利用workerman框架生成临时文件并通过浏览器下载。
php文件操作介绍
php提供了一系列文件操作函数,下面是几个常用的函数及其用法:
fread(fp,filesize(file_path));函数读取文件内容。
file_put_contents(file_path,con,FILE_APPEND);函数写入文件。
copy("e:\\2.txt","d:\\1.txt")函数实现。mkdir($path,0777,true)函数创建。
workerman介绍
workerman是一款基于PHP开发的高性能应用容器。它不是一个MVC框架,而是一个更底层的服务框架。通过workerman,可以开发tcp代理、游戏服务器、邮件服务器、ftp服务器等,甚至可以开发php版本的redis、数据库、nginx、php-fpm等。workerman的核心是多进程+Epoll+非阻塞IO,能够维持上万并发连接。由于常驻内存,不依赖Apache、nginx、php-fpm等容器,workerman拥有超高的性能。同时,它支持TCP、UDP、UNIXSOCKET,长连接,Websocket、HTTP、WSS、HTTPS等多种通讯协议和自定义协议,内置定时器、异步socket客户端、异步Redis、异步Http、异步消息队列等高性能组件。
读取文件
以下是读取文件的示例代码:
//读取文件
header("Content-Type: text/html;charset=utf-8"); //设置字符编码
$file = base_path() . "/public/index.m3u8";
$read = fopen($file, 'r');
$contents = fread($read, filesize($file));
$string1 = getBeforeString($contents, 'enc.key');
$string2 = getLaterString($contents, 'enc.key');
$newContents = $string1 . 'enc.key?token=123' . $string2;
fclose($read);写入文件
以下是写入文件的示例代码:
//写入文件 $file = base_path() . "/public/test22.m3u8"; $handle = fopen($file, 'w'); //打开文件 fwrite($handle, $newContents); //写入内容 fclose($handle); //关闭文件 readfile($file); //读取并输出文件全部内容 return redirect(WEB_URL . '/test22.m3u8'); //调转页面
读取oss文件,读取文件每行内容
以下是读取OSS文件并处理每行内容的示例代码:
//读取OSS文件 $file =OSS_URL . $url1; //文件内容加入数组 $fileContent = @file($file); $newContent = ''; //遍历文件的每一行 foreach ($fileContent as $value) { //文件该行是否存在这个字符,有这替换内容 if (strpos($value, 'api.qingsong.chaotuapp.com/') !== false) { $value = str_replace('app.com/', "q.com/ckey", $value); } //文件该行是否存在这个字符,有这拼接内容 if (strpos($value, '.ts') !== false) { $value = $ossUrl . $value; } $newContent .= $value; }
临时文件写入,生成临时文件并浏览器下载workerman框架
以下是使用workerman框架生成临时文件并通过浏览器下载的示例代码:
//写入文件
$fileName = "$token.m3u8"; // ./59ee8147cf3f42575bc91ff586d54837.m3u8
$file = "./$fileName"; //打开文件
$handle = fopen($file, 'w');
//写入内容
fwrite($handle, $newContent);
//将文件转字符串
$content = file_get_contents($file);
//删除临时文件
unlink($file);
//输出浏览器
$response = new Response();
return $response->withHeader('content-description', 'File Transfer')
->withHeader('content-type', 'application/force-download')
->withHeader('content-disposition', "attachment; filename={$fileName}")
->withHeader('content-transfer-encoding', 'binary')
->withHeader('pragma', 'public')
->withBody($content);本文正在参加「金石计划 . 瓜分6万现金大奖」