php 文件指针如何php实现文件下载停留

PHP 中如何在同一个文件中写入而不覆盖以前写的内容_百度知道
PHP 中如何在同一个文件中写入而不覆盖以前写的内容
提问者采纳
以a方式打开文件可以在文件的末尾写入内容,例如下面的代码在文件的a.txt的末尾添加123:&?php&&&&$fp=fopem(&a.txt&,&a&);&&&&fputs($fp,&123&);&&&&fclose($fp);?&其它打开方式的说明:'r' & &只读方式打开,将文件指针指向文件头。 & & & && &'r+' & &读写方式打开,将文件指针指向文件头。 & & & && &'w' & &写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 & & & && &'w+' & &读写方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 & & & && &'a' & &写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 & & & && &'a+' & &读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。 & & & && &'x' & &创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 & & & &fopen() 调用失败并返回 FALSE,并生成一条 & & & &E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 & & & &底层的 open(2) 系统调用指定 & & &nbs怠肠壁课撰酒辩旬菠莫p; &O_EXCL|O_CREAT 标记是等价的。此选项被 & & & & PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。 & & & && &'x+' & &创建并以读写方式打开,将文件指针指向文件头。如果文件已存在,则 & & & &fopen() 调用失败并返回 FALSE,并生成一条 & & & &E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 & & & &底层的 open(2) 系统调用指定 & & & &O_EXCL|O_CREAT 标记是等价的。此选项被 & & & &PHP 4.3.2 以及以后的版本所支持,仅能用于本地文件。 & & && & &
其他类似问题
php的相关知识
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁更多频道内容在这里查看
爱奇艺用户将能永久保存播放记录
过滤短视频
暂无长视频(电视剧、纪录片、动漫、综艺、电影)播放记录,
使用您的微博帐号登录,即刻尊享微博用户专属服务。
使用您的QQ帐号登录,即刻尊享QQ用户专属服务。
使用您的人人帐号登录,即刻尊享人人用户专属服务。
方式2:免费发送短信到手机
请输入正确的手机号
此短信不收取任何费用,保证您的手机号安全不被泄露
下载APP到本机
当前浏览器仅支持手动复制代码
视频地址:
flash地址:
html代码:
收藏成功,可进入查看所有收藏列表
爸爸去哪儿2游戏 立即参与
30秒后自动关闭
PHP文件处理(四)文件资源处理、文件指针、文件锁定
发布时间:
播放量数据:
你可能还想订阅他们:
周围人都在搜-百度搜索提供
&正在加载...
由于版权原因,此视频暂不支持播放
Sorry,due to copyright issues
you can’t watch the video
这些视频最近很火,赶紧看看吧
很抱歉,您所观看的视频已经下线
这些视频最近很火,赶紧看看吧
呃......网络出错了
Hi,{{username}}:
,请继续享受影片无限看、全站无广告等特权。
您的会员还有{{_remainDays}}天就要到期了
VIP还有{{_remainDays}}天到期
您的会员已经过期{{_remainDays}}天
VIP已过期{{_remainDays}}天
您使用浏览器不支持直接复制的功能,建议您使用Ctrl+C或右键全选进行地址复制
色情低俗内容
血腥暴力内容
广告或欺诈内容
侵犯了我的权力
还可以输入300字
&li data-elem="tabtitle" data-seq="{{seq}}"&
&a href="javascript:void(0);"&
&span>{{start}}-{{end}}&/span&
&li data-downloadSelect-elem="item" data-downloadSelect-selected="false" data-downloadSelect-tvid="{{tvid}}"&
&a href="javascript:void(0);"&{{pd}}&/a&
选择您要下载的《》剧集:
安装爱奇艺视频客户端,
马上开始为您下载本片
5秒后自动消失
免费发送到手机,下载手机APP
请输入正确的手机号
此短信不收取任何费用,保证您的手机号安全不被泄露php实现文件下载功能的几个代码分享,PHP教程,PHP案例,PHP实例
本站中文域名:、 
        
     
 |  |  |  |  
     |     |     |   
您的位置: &&
&& php实现文件下载功能的几个代码分享
php实现文件下载功能的几个代码分享
  本文标签:php,文件下载代码
一个简单的php文件下载源代码,虽不支持传等,但是可以满足一些常用的需求了&。php下载文件其实用一个a标签就能实现,比如 &a href="web/magento-1.8.1.0.zip"&magento-1.8.1.0.zip&/a& &。但是遇到一些浏览器能识别的格式,比如.txt,.html,.pdf等,再用&a href="web/abc.txt"&abc.txt&/a& 想知道会发生什么了&。复制代码 代码如下:&?php
/**&* 文件下载&***/
header("Content-type:text/charset=utf-8");download(web/magento-1.8.1.0.zip, magento下载);
function download($file, $down_name){&$suffix = substr($file,strrpos($file,.));&//获取文件后缀&$down_name = $down_name.$&//新文件名,就是下载后的名字
&//判断给定的文件存在与否 &if(!file_exists($file)){&&die("您要下载的文件已不存在,可能是被删除");&} &$fp = fopen($file,"r");&$file_size = filesize($file);&//下载文件需要用到的头&header("Content-type: application/octet-stream");&header("Accept-Ranges: bytes");&header("Accept-Length:".$file_size);&header("Content-Disposition: filename=".$down_name);&$buffer = 1024;&$file_count = 0;&//向浏览器返回数据 &while(!feof($fp) && $file_count & $file_size){&&$file_con = fread($fp,$buffer);&&$file_count += $&&echo $file_&} &fclose($fp);}
也可以看看这个注释比较详细的代码:
复制代码 代码如下:&?php&//文件下载,下载一张图片&//$file_name="Angel.mp3";
&$file_name="bjnihao.jpg";& //出现中文 程序无法完成下载 提示:文件不存在 &//对文件进行转码(PHP文件函数 比较古老 需对中文码转成 gb2312)&//iconv ― Convert string to requested character encoding&//by www.jb51.net&$file_name=iconv("utf-8","gb2312",$file_name);
&//设置文件下载路径(相对路径)&//$file_path="./dowm/".$file_
&//使用绝对路径&$file_path=$_SERVER[DOCUMENT_ROOT]."/http/dowm/".$file_
&//打开文件---先判断再操作&if(!file_exists($file_path)){& echo "文件不存在";& //直接退出&}
&//存在--打开文件
&$fp=fopen($file_path,"r");&//获取文件大小&$file_size=filesize($file_path);
&//http 下载需要的响应头 &header("Content-type: application/octet-stream"); //返回的文件 &header("Accept-Ranges: bytes");&& //按照字节大小返回&header("Accept-Length: $file_size"); //返回文件大小&header("Content-Disposition: filename=".$file_name);//这里客户端的弹出对话框,对应的文件名
&//向客户端返回数据&//设置大小输出&$buffer=1024;
&//为了下载安全,我们最好做一个文件字节读取计数器&$file_count=0;&//判断文件指针是否到了文件结束的位置(读取文件是否结束)&while(!feof($fp) && ($file_size-$file_count)&0){
& $file_data=fread($fp,$buffer);& //统计读取多少个字节数& $file_count+=$& //把部分数据返回给浏览器& echo $file_&}&//关闭文件
&fclose($fp);?&
封装函数:
&?php&/*& 封装函数:& 参数说明----$file_name:文件名&&&& $file_sub_dir:文件下载的子路径 &*/&function file_dowm($file_name,$file_sub_dir){& //文件转码& $file_name=iconv("utf-8","gb2312",$file_name);
& //使用绝对路径& $file_path=$_SERVER[DOCUMENT_ROOT]."$file_sub_dir".$file_
& //打开文件---先判断再操作& if(!file_exists($file_path)){&& echo "文件不存在";&& //直接退出& }
& //存在--打开文件
& $fp=fopen($file_path,"r");& //获取文件大小& $file_size=filesize($file_path);& /*& //这里可以设置超过多大不能下载& if($file_size&50){&& echo "文件太大不能下载";&&& }*/
& //http 下载需要的响应头 & header("Content-type: application/octet-stream"); //返回的文件 & header("Accept-Ranges: bytes");&& //按照字节大小返回& header("Accept-Length: $file_size"); //返回文件大小& header("Content-Disposition: filename=".$file_name);//这里客户端的弹出对话框,对应的文件名
& //向客户端返回数据& //设置大小输出& $buffer=1024;
& //为了下载安全,我们最好做一个文件字节读取计数器& $file_count=0;& //判断文件指针是否到了文件结束的位置(读取文件是否结束)& while(!feof($fp) && ($file_size-$file_count)&0){
&& $file_data=fread($fp,$buffer);&& //统计读取多少个字节数&& $file_count+=$&& //把部分数据返回给浏览器&& echo $file_& }
& //关闭文件& fclose($fp);&}&file_dowm("bjnihao.jpg","/http/dowm/");?&
另一个代码:
复制代码 代码如下:public function downloads($name){&&$name_tmp = explode("_",$name);&&$type = $name_tmp[0];&&$file_time = explode(".",$name_tmp[3]);&&$file_time = $file_time[0];&&$file_date = date("Y/md",$file_time);&&$file_dir = SITE_PATH."/data/uploads/$type/$file_date/";&&&if (!file_exists($file_dir.$name)){&&&header("Content-type: text/ charset=utf-8");&&&echo "File not found!";&&& &&} else {&&&$file = fopen($file_dir.$name,"r"); &&&Header("Content-type: application/octet-stream");&&&Header("Accept-Ranges: bytes");&&&Header("Accept-Length: ".filesize($file_dir . $name));&&&Header("Content-Disposition: filename=".$name);&&&echo fread($file, filesize($file_dir.$name));&&&fclose($file);&&}&}
Google搜索中
搜狗搜索中
在线教程导航
数据库开发
热点软件下载
车友晒价详情
<font color="#FF
南京市大明路那边
<font color="#FF
赠送贴膜!
<font color="#FF
您的心理价位,特别购车要求!
<font color="#FF万
大厂这边,没有自动挡的
<font color="#FF万
汽车之家论坛
<font color="#FF万
只在车展上咨询过,当时销售人员报价说现金优惠4000,
<font color="#FF万
需要2月份产的车
<font color="#FF万
南京5个4s都去看过
<font color="#FF万
江阴永盛优惠1万,送5000元装修
团购车型:
加入微信号,了解汽车///活动
| 站长工具:
加入官方微信号
渠道报价/招聘
任你发任你查
All Rights Reserved.
珠江路在线版权所有
苏ICP备号 中文域名:
 |  | PHP 函数参考:PHP 文件指针函数 - 课程- 优才网
& &文件指针通俗的理解就像是平常操作文档时鼠标指针的位置。PHP 提供了丰富的文件指针函数供使用::关闭文件指针。:测试文件指针是否到了文件结束的位置。:在文件指针中定位。:倒回文件指针的位置。:返回文件指针读/写的位置。fclose() 函数用于关闭一个已打开的文件指针(将 handle 指向的文件关闭),如果成功则返回 TRUE,失败则返回 FALSE 。语法:bool fclose( resource handle )例子:&?php
$fh = fopen("test.txt","r");
fclose($fh);
?&文件指针必须有效,并且是通过 fopen() 或 fsockopen() 成功打开的。EOF(End Of File,文件结束位置)是文件处理中非常重要的概念,在 PHP 中提供了 feof() 函数来检测是否达到了 EOF。如果文件指针到了 EOF 或者出错时则返回 TRUE,否则返回一个错误(包括 socket 超时),其它情况则返回 FALSE。语法:bool feof( resource handle )例子:&?php
$fh = @fopen("test.txt","r") or die("打开 test.txt 文件出错!");
// if条件避免无效指针
while(!feof($fh)) {
echo fgets($fh), '&br /&';
fclose($fh);
?&重要提示如果传递的文件指针无效可能会陷入无限循环中,因为 EOF 不会返回 TRUE。所以在使用 feof() 函数之前对文件指针的有效性进行检测是十分必要的。fseek() 函数用于在文件指针中定位,成功则返回 0 ,否则返回 -1 。语法:int fseek( resource handle, int offset [, int whence] )参数说明:参数说明handle文件指针offset定位字节数whence可选,定位辅助说明,可能的值如下:如果没有指定 whence,默认为 SEEK_SET。例子:&?php
$fh = fopen('test.txt', 'r');
fseek($fh, 5);
echo ftell($fh);
?&提示:该函数可能不能用于在 fopen() 中以 &http://& 或 &ftp://& 格式打开所返回的文件指针。rewind() 函数用于倒回文件指针的位置到开头,如果成功则返回 TRUE,失败则返回 FALSE 。语法:bool rewind( resource handle )例子:&?php
$fh = fopen("test.txt","r");
rewind($fh);
echo ftell($fh);
?&ftell() 函数用于返回文件指针读/写的位置,成功返回 0 ,出错返回 FALSE。语法:int ftell ( resource handle )文件指针必须是有效的,且必须指向一个通过 fopen() 或 popen() 成功打开的文件,使用例子见上。PHP 打开进程文件指针
在线手册:&
popen & 打开进程文件指针
resource popen
( string $command
, string $mode
返回一个和
所返回的相同的文件指针,只不过它是单向的(只能用于读或写)并且必须用
来关闭。此指针可以用于
当模式为 &#039;r&#039;,返回的文件指针等于命里的 STDOUT,当模式为 &#039;w&#039;,返回的文件指针等于命令的 STDIN。
如果出错返回 FALSE。
Example #1
popen() 例子
&?php$handle&=&popen("/bin/ls",&"r");?&
如果未找到要执行的命令,会返回一个合法的资源。这看上去很怪,但有道理。它允许访问
shell 返回的任何错误信息:
Example #2
popen() 例子
&?phperror_reporting(E_ALL);/*&加入重定向以得到标准错误输出&stderr。&*/$handle&=&popen('/path/to/executable&2&&1',&'r');echo&"'$handle';&"&.&gettype($handle)&.&"\n";$read&=&fread($handle,&2096);echo&$read;pclose($handle);?&
如果需要双向支持,使用
启用时,可仅可用
执行文件。实际上,现在不允许在到可执行的路径中存在 .. 组件。
Warning 启用时,命令字符串会被
转换。因此,echo y | echo x 会变成
echo y \| echo x。
- 关闭进程文件指针
- 打开文件或者 URL
- Execute a command and open file pointers for input/output
在线手册:&
fread&is&blocking&on&streams&from&popen.
That&means&that&if&you&do&
&?php
&&$stream&=&popen("tail&-f&myfile");
&&fread($stream,&100);
?&
then&fread&will&only&return&full&chunks&of&100&characters.&So&if&the&size&of&myfile&isn't&a&multiple&of&100,&the&last&chunk&will&not&be&returned.
This&is&documented&in&https://bugs.php.net/bug.php?id=51056&.&Some&people&in&that&bug&discussion&argue&that&this&should&be&kept&to&not&change&behaviour,&but&example&#3&on&http://php.net/fread&clearly&says&"When&reading&from&anything&that&is&not&a&regular&local&file,&such&as&streams&returned&when&reading&remote&files&or&from&popen()&and&fsockopen(),&reading&will&stop&after&a&packet&is&available."
A&workaround&is&to&call&
&&&?php&stream_set_blocking($stream,&0);&?&
on&the&stream&you&get&from&popen().
If, on windows, you need to start a batch file that needs administrator privileges, then you can make a shortcut to the batch file, click properties, check to on &run as administrator& on one of the property pages, and then double-click the shortcut once (to initialize that &run as administrator& business).
using popen(&/path/to/shortcut.lnk&) will then run your batch file with administrator privileges.
handy for when you want to use cli php to do some long running tasks and that php-cli needs to use sessions..
If you are running in a chroot'ed environment on Debian &Squeeze&, this command won' there is a problem with the kernel code that popen() eventually calls.
Note that pecl makes heavy use of this command, so if you are running in this environment you will need to install the pecl extension from source instead.
There&is&a&simple&way&to&start&a&process&in&the&background&but&still&find&out&what&the&process&result&is.&I&combined&the&information&from&some&users&below&with&some&of&my&own&coming&up&with&the&following:&?php$bat_filename&=&"C:\\my_bat_file.bat";$bat_log_filename&=&"C:\\my_bat_file_bat.log";$bat_file&=&fopen($bat_filename,&"w");if($bat_file)&{&&&&fwrite($bat_file,&"@echo&off"."\n");&&&&fwrite($bat_file,&"echo&Starting&proces&&&&".$bat_log_filename."\n");&&&&fwrite($bat_file,&"php&c:\\my_php_process.php&&&&".$bat_log_filename."\n");&&&&fwrite($bat_file,&"echo&End&proces&&&&".$bat_log_filename."\n");&&&&fwrite($bat_file,&"EXIT"."\n");&&&&fclose($bat_file);}&&&&&&&&&&&&////&Start&the&process&in&the&background//$exe&=&"start&/b&".$bat_filename;if(&pclose(popen($exe,&'r'))&)&{&&&&return&true;}return&false;?&In&my&case&the&file&names&of&the&.bat&and&.log&files&weren't&always&the&same,&so&I&needed&a&dynamic&way&to&create&the&.bat&file.&The&output&from&the&php&command&is&saved&to&the&log&file&with&the&&&&command.&All&prints&and&errors&are&stored&there.&At&a&later&time&you&can&open&the&log&file&and&see&what&happened.
Note&that&you&*have*&to&do&a&read&on&the&handle&before&you&can&feof(),&even&if&the&command&outputs&nothing!&So..&?php$f=popen("sleep&2","r");while&(!feof($f))&{}pclose($f);print&"done";?&will&never&finish.
To&run&a&php&script&and&not&wait&for&it&I&use&this&on&windows
$commandString&=&"start&/b&c:\\php\\php.EXE&c:\\image\\cleanup.php&--passaccount=$account&--passcount=$count";&
pclose(popen($commandString,&'r'));&
Note&to&pass&my&script&vars&you&need&dashdash.
to&read&the&var&use&--this&is&in&cleanup.php
&?php
function&arguments($argv)&{
&&&&$_ARG&=&array();
&&&&foreach&($argv&as&$arg)&{
&&&&&&&&if&(ereg('--[a-zA-Z0-9]*=.*',$arg))&{
&&&&&&&&&&&&$str&=&split("=",$arg);&$arg&=&'';
&&&&&&&&&&&&$key&=&ereg_replace("--",'',$str[0]);
&&&&&&&&&&&&for&(&$i&=&1;&$i&&&count($str);&$i++&)&{
&&&&&&&&&&&&&&&&$arg&.=&$str[$i];
&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&&&&&$_ARG[$key]&=&$arg;
&&&&&&&&}&elseif(ereg('-[a-zA-Z0-9]',$arg))&{
&&&&&&&&&&&&$arg&=&ereg_replace("-",'',$arg);
&&&&&&&&&&&&$_ARG[$arg]&=&'true';
&&&&&&&&}
&&&&
&&&&}
return&$_ARG;
}
sleep(5);
$var_array=&arguments($argv);
extract($var_array,&EXTR_PREFIX_SAME,&"wddx");//$user&comes&from&here
//echo&"hello&new&$user";
$account=$passaccount;
$count=$passcount;
?&
If&you&try&to&execute&a&command&under&Windows&the&PHP&script&normally&waits&until&the&process&has&been&terminated.&Executing&long-term&processes&pauses&a&PHP&script&even&if&you&don't&want&to&wait&for&the&end&of&the&process.
It&wasn't&easy&to&find&this&beautiful&example&how&to&start&a&process&under&Windows&without&waiting&for&its&termination:
&?php
$commandString&=&'start&/b&c:\\programToRun.exe&-attachment&"c:\\temp\file1.txt"';
pclose(popen($commandString,&'r'));
?&
If&you&want&to&download&files&from&a&linux&server&with&a&filesize&bigger&than&2GB&you&can&use&the&following:
&?php
function&serveFile(&$file&,&$as&){
&&&&header(&'Expires:&Mon,&1&Apr&:00&GMT'&);
&&&&header(&'Pragma:&no-cache'&);
&&&&header(&'Cache-Control:&must-revalidate,&post-check=0,&pre-check=0'&);
&&&&header(&'Content-Description:&File&Download'&);
&&&&header(&'Content-Type:&application/octet-stream'&);
&&&&header(&'Content-Length:&'.trim(`stat&-c%s&"$file"`)&);
&&&&header(&'Content-Disposition:&&filename="'.&$as&.'"'&);
&&&&header(&'Content-Transfer-Encoding:&binary'&);
&&&&//@readfile(&$file&);
&&&&flush();
&&&&$fp&=&popen("tail&-c&".trim(`stat&-c%s&"$file"`)."&".$file.'&2&&1',&"r");
&&&&while(!feof($fp))
&&&&{
&&&&&&&&//&send&the&current&file&part&to&the&browser
&&&&&&&&print&fread($fp,&1024);
&&&&&&&&//&flush&the&content&to&the&browser
&&&&&&&&flush();
&&&&}
&&&&fclose($fp);
}
?&
Note, when using this with a batch file in windows, you must put an &exit& at the end of your batch file or you will get a new cmd.exe stuck in your process list every time you execute the page.
Care&needs&to&be&taken&in&the&case&of&long&running&child&processes.&Say&you&want&to&run&tail&-f&/var/log/messages&or&in&my&case&burn&dvds.&If&you&have&a&busy&wait,&Apache2&can&sit&towards&100%cpu&and&steadily&grow&memory.&In&my&case&I&crashed&the&server&after&about&an&hour&and&90%&of&the&dvd&burned.&During&that&time&apache&had&consumed&a&gig&of&swap.
Offending&code&-&don't&copy:
&?php
&&&&&&&&$ThisCommand&=&sprintf("%s&%s",COMMAND,$ThisFile);
&&&&&&&&$fp=popen($ThisCommand,"r");
&&&&&&&&while&(!feof($fp))&{
&&&&&&&&&&&&&&&&set_time_limit&(20);
&&&&&&&&&&&&&&&&$results&=&fgets($fp,&4096);
&&&&&&&&&&&&&&&&if&(strlen($results)&==&0)&{
&&&&&&&&&&&&&&&&&&&//&stop&the&browser&timing&out
&&&&&&&&&&&&&&&&&&&echo&"&";
&&&&&&&&&&&&&&&&&&&flush();
&&&&&&&&&&&&&&&&}&else&{
&&&&&&&&&&&&&&&&&&&$tok&=&strtok($results,&"\n");
&&&&&&&&&&&&&&&&&&&while&($tok&!==&false)&{
&&&&&&&&&&&&&&&&&&&&&&&&echo&htmlentities(sprintf("%s\n",$tok))."&br/&";
&&&&&&&&&&&&&&&&&&&&&&&&flush();
&&&&&&&&&&&&&&&&&&&&&&&&$tok&=&strtok("\n");
&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&}
&&&&&&&&}
&&&&&&&&pclose($fp);
?&
to&go&from&zero&memory&and&100%&cpu&&to&negligible&memory&and&negligible&cpu&add&a&sleep.
&?php
&&&&&&&&while&(!feof($fp))&{
&&&&&&&&&&&&&&&&set_time_limit&(20);
&&&&&&&&&&&&&&&&$results&=&fgets($fp,&256);
&&&&&&&&&&&&&&&&if&(strlen($results)&==&0)&{
&&&&&&&&&&&&&&&&&&&//&stop&the&browser&timing&out
&&&&&&&&&&&&&&&&&&&echo&"&";
&&&&&&&&&&&&&&&&&&&flush();
&&&&&&&&&&&&&&&&}&else&{
&&&&&&&&&&&&&&&&&&&$tok&=&strtok($results,&"\n");
&&&&&&&&&&&&&&&&&&&while&($tok&!==&false)&{
&&&&&&&&&&&&&&&&&&&&&&&&echo&htmlentities(sprintf("%s\n",$tok))."&br/&";
&&&&&&&&&&&&&&&&&&&&&&&&flush();
&&&&&&&&&&&&&&&&&&&&&&&&$tok&=&strtok("\n");
&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&//&avoid&a&busy&wait
&&&&&&&&&&&&&&&&sleep(1);
&&&&&&&&}
?&
I&think&the&continued&banging&of&the&space&to&keep&the&browser&awake&triggered&some&issues&in&apache.
Note&that&under&Windows,&if&you&are&trying&to&write&data&to&be&available&to&your&pipe's&STDIN,&you&may&need&to&execute&php&directly,&rather&than&depending&on&file&associations.
&?php
&&&&//&with&$cmd&set&to&'foo.php',&STDIN&comes&up&blank.
&&&&//&with&$cmd&set&to&'php&foo.php',&STDIN&gets&filled
&&&&//&&&&&(assuming&php.exe&is&in&your&path)
&&&&$cmd&=&'foo.php';
&&&&if&(&($fh&=&popen($cmd,&'w'))&===&false&)
&&&&&&&&die("Open&failed:&${php_errormsg}\n");
&&&&fwrite($fh,&"Line&one\nLine&two\n");
&&&&pclose($fh);
?&
popen() seems to have problems dealing with binary data (piping audio data to the standard input of an encoding application). I changed to proc_open() instead and now everything is working fine.
Thanks a lot to tr4nc3 at msn dot com..
when using apache on Windows XP, on 'console mode' commands work fine, but as a system service, commands like 'popen' stop functioning, to resolve this:
Start&Run&services.msc
Right click &Apache...&, select properties.
Click on the &LOG ON& tab
Check the box &Allow this service to interact with desktop&
Restart Apache
&?php
//&The&above&import&function&can&be&easily&extended&using&
//&/usr/local/bin/xls2csv&(part&of&catdoc&)&and&popen&
//&to&read&excell&files&directly.&
//&In&our&particular&application&the&first&line&was&the&file&heading.
function&importxls($file,$head=true,$throwfirst=true,$delim=",",$len=1000)&{
&&&$return&=&false;
&&&$handle&=&popen("/usr/local/bin/xls2csv&$file",&"r");
//&or&die&if&not&there.
&&&if&($throwfirst)&{
&&&&&&&$throw&=&fgetcsv($handle,&$len,&$delim);
&&&}
&&&if&($head)&{
&&&&&&&$header&=&fgetcsv($handle,&$len,&$delim);
&&&}
&&&while&(($data&=&fgetcsv($handle,&$len,&$delim))&!==&FALSE)&{
&&&&&&&if&($head&AND&isset($header))&{
&&&&&&&&&&&foreach&($header&as&$key=&$heading)&{
&&&&&&&&&&&&&&&$row[$heading]=(isset($data[$key]))&?&$data[$key]&:&'';
&&&&&&&&&&&&&&&print&"&li&".&$heading&."=&"&.&$row[$heading]."&/li&";
&&&&&&&&&&&}
&&&&&&&&&&&$return[]=$row;
&&&&&&&}&else&{
&&&&&&&&&&&$return[]=$data;
&&&&&&&}
&&&}
&&&fclose($handle);
&&&return&$return;
}
?&
Truncated&output&from&ps&command?
The&solution&lies&in&the&way&ps&displays&it's&info
specifically&the&-w&option&which:
'uses&132&columns&to&display&information,
instead&of&the&default&which&is&your&window&size.'....
somehow&with&fgets&in&php&that&results&in&74&characters
regardless&off&the&init&length&parameter
a&bit&of&code:
&?php
echo&'&table&width="99%"&&tr&&td&cron&/td&&/tr&'&.&"\n";
$fp=popen("/bin/ps&-waux","r");
while&(!feof($fp))&{
&&&&$buffer&=&fgets($fp,&4096);
&&&&$croninf&.=&'&tr&&td&'&.&$buffer&.&'&/td&&/tr&'&.&"\n";
}
pclose($fp);
echo&$croninf;
echo&'&/table&&br&&br&'&.&"\n";
?&
Writing&and&executing&a&bash&script&is&as&simple&as&that:
&?php
$f&=&popen&("/bin/bash","w");
fwrite($f,&"export&KRB5CCNAME=`tempfile`\n");
fwrite($f,&"export&KRBTKFILE=`tempfile`\n");
fwrite($f,&"$KINIT&--keytab=$GLOBALS["KADMIN_KEYFILE"]&--use-keytab&--afslog&$GLOBALS["KADMIN_PRINC"]\n");
fwrite($f,&"pts&delete&$uid\n");
fwrite($f,&"fs&rmmount&$rwhome\n");
fwrite($f,&"vos&remove&sanjo&b&user.$uid\n");
fwrite($f,&"$KDESTROY\n");
pclose($f);
?&
Here&is&a&nice&little&script&for&monitoring&your&http&access&log.&?php$handle&=&popen("tail&-f&/etc/httpd/logs/access.log&2&&1",&'r');while(!feof($handle))&{&&&&$buffer&=&fgets($handle);&&&&echo&"$buffer&br/&\n";&&&&ob_flush();&&&&flush();}pclose($handle);?&----www.eviltree.co.ukwww.solidsites.co.uk
If&you&want&to&fork&a&process&under&windows,&this&is&the&function&to&use.&&I&created&a&batch&file&called&runcmd.bat&with&the&following&line
start&%1&%2&%3&%4
then&I&have&the&folowing&function
&?php
define('RUNCMDPATH',&'c:\\htdocs\\nonwebspace\\runcmd.bat');
function&runCmd($cmd)&{
&&&&$externalProcess=popen(RUNCMDPATH.'&'.$cmd,&'r');
&&&&pclose($externalProcess);
}&&&&
?&
with&this,&doing&something&like
&?php&runCmd('php.exe&printWorkOrder.php&3498');&?&
will&launch&php.exe&outside&of&apache&and&allow&the&script&calling&the&runCmd()&function&to&continue&without&waiting&for&the&command&line&process&to&return.&&The&process&will&run&under&the&same&user&account&that&Apache&(or&whatever&webserver&you're&running)&is&running&under,&so&make&sure&it&has&permissions&to&do&whatever&you&need&to&do.&&Also,&make&sure&that&the&batch&file&has&enough&%n&s&in&order&to&pass&all&the&command&line&variables&that&you&might&need&to&pass.
Special&thanks&to&kicken&from&the&devshed&forums&for&coming&up&with&the&idea.
I&should&say,&my&host&uses&a&modified&form&of&safe&mode,&so&I&don't&know&if&that&might&have&caused&a&problem&with&"popen"&as&opposed&to&"proc_open".&&With&safe&mode&enabled,&all&words&following&the&initial&command&string&are&treated&as&a&single&argument.&Thus,&echo&y&|&echo&x&becomes&echo&"y&|&echo&x".&&[Because&of&this,]&LinixDude010's&srcipt&did&not&work&for&me.&&Seems&wrong&to&read&and&write&with&popen,&according&to&the&manual.
The&script&produced&pgp&text,&but&there&was&something&wrong&with&the&text&and&I&could&not&decode&it.
This&replacement&script,&using&proc_open,&which&can&read&and&write,&DOES&work:
&?php
function&pgp_encrypt($keyring_location,&$public_key_id,&$plain_text)&{
&&$encrypted_text='';
&&$key_id&=&EscapeShellArg($public_key_id);
&&putenv("PGPPATH=$keyring_location");
&&//&encrypt&the&message
&&$descriptorspec&=&array(
&&&&0&=&&array("pipe",&"r"),&&//&stdin
&&&&1&=&&array("pipe",&"w"),&&//&stdout
&&&&2&=&&array("pipe",&"w")&&&//&stderr&??&instead&of&a&file
&&);
&&$process&=&proc_open("pgpe&-r&$key_id&-af",&$descriptorspec,&$pipes);
&&if&(is_resource($process))&{
&&&&fwrite($pipes[0],&$plain_text);
&&&&fclose($pipes[0]);
&&&&while($s=&fgets($pipes[1],&1024))&{
&&&&&&&&&&//&read&from&the&pipe
&&&&&&&&&&$encrypted_text&.=&$s;
&&&&}
&&&&fclose($pipes[1]);
&&&&//&optional:
&&&&while($s=&fgets($pipes[2],&1024))&{
&&&&&&$encrypted_text.=&"\n&p&Error:&$s&/p&\n";
&&&&}
&&&&fclose($pipes[2]);
&&}
&&return&$encrypted_text;
}
$message&=&pgp_encrypt("/home/username/.pgp",&"",&"dummy&text&to&be&encrypted");
print&nl2br($message);
Note&that&there&appears&to&be&a&limit&to&the&amount&of&data&that&fread()&will&return&from&a&handle&opened&with&popen().&A&call&to&fread()&may&not&return&as&much&as&you&ask&for.For&example,&suppose&I&have&a&file&"myfile.txt"&which&is&more&than&10KB&in&size.&The&following&code&works&as&expected:&?php$fp&=&fopen('myfile.txt',&'r');$data&=&fread($fp,&10240);echo&strlen($data);?&The&output&is&'10240.'&However,&popen()&behaves&differently:&?php$fp&=&popen('/bin/cat&myfile.txt',&'r');$data&=&fread($fp,&10240);echo&strlen($data);?&On&my&system,&this&code&prints&out&'8192'&instead&of&the&expected&'10240.'
If you're having trouble with the server (Apache) hanging when issuing system commands consider the following bug report:
http://bugs.php.net/bug.php?id=22526
basically, if you're using sessions issue a
session_write_close();
command before you execute your system command to keep the server from hanging.
This may also correct the problem when using other system command executing functions like exec.
Yet&another&workaround&for&not&having&bidirectional&pipes&in&php.
&?php
$Cmd&=
"bc&2&&1&&&&END\n"&.
"100+221\n"&.
"1+3*3\n"&.
"quit\n"&.
"END\n";
$fp&=&popen($Cmd,&'r');
$read&=&fread($fp,&1024);
echo&$read;
pclose($fp);
?&
From the popen linux programmers manual:
a pointer to a null-terminated string containing a shell command line.
using the -c flag.&
Since php uses this popen function, you need to be sure /bin/sh exists. This file may not exist in chroot()ed environments.
I&noticed&that&some&of&the&examples&above&seem&to&advocate&passing&unencrypted&data&to&gpg&via&the&pipe&shell&escape,&in&the&absence&of&a&bi-directional&popen&(on&some&OSes).
The&approach&I've&taken&is&similar&to:
&?php
&&$prefix&=&'example';
&&$command&=&'/usr/local/bin/gpg&--encrypt&--armor&--no-tty&--batch&--no-secmem-warning&--recipient&"joe."';
&&$tmpfile&=&tempnam('/tmp',&$prefix);
&&$pipe&=&popen("$command&2&&1&&$tmpfile",&'w');
&&if&(!$pipe)&{
&&&&unlink($tmpfile);
&&}&else&{
&&&&fwrite($pipe,&$plaintxt,&strlen($plaintxt));
&&&&pclose($pipe);
&&&&$fd&=&fopen($tmpfile,&"rb");
&&&&$output&=&fread($fd,&filesize($tmpfile));
&&&&fclose($fd);
&&&&unlink($tmpfile);
&&}
&&return&$output;
?&
This&means&that&unencrypted&information&is&not&passed&via&a&(potentially&readable)&shell&command,&and&only&encrypted&information&gets&stored&on&disc.
Here&is&a&workaround&for&not&having&bidirectional&pipes&in&php.
If&you&have&bidirectional&pipe&support,&don't&bother&with&this.
The&trick&here&is&to&send&the&input&on&the&command&line&to&the&target&application.&&In&particular&I&wanted&to&use&openssl&without&using&temp&files&or&named&pipes.&&This&solution&should&also&be&thread/process&safe.
This&does&work&on&Linux&(RedHat&7).
&?php
function&filterThroughCmd($input,&$commandLine)&{
&&$pipe&=&popen("echo&\"$input\"|$commandLine"&,&'r');
&&if&(!$pipe)&{
&&&&print&"pipe&failed.";
&&&&return&"";
&&}
&&$output&=&'';
&&while(!feof($pipe))&{
&&&&$output&.=&fread($pipe,&1024);
&&}
&&pclose($pipe);
&&return&$output;
}
#&example:
print&filterThroughCmd("hello",&"cat");
#&Piping&to&cat&has&the&effect&of&echoing&your&input.
?&
The&below&code&works&for&both&way&processing&;)&Have&fun&folks
&?php
&&&&system("mkfifo&pipeout");
&&&$pipe&=&popen("./nwserver&-module&Chapter1E&&&pipeout","w");
&&&$pipeout&=&fopen("pipeout",&"r");
&&&while&($s&=&fgets($pipeout,1024))&{
&&&&echo&$s;
&&&}
I&had&all&kinds&of&trouble&encrypting&a&message&with&PGP,&but&I&finanlly&got&it&to&work.&&The&trick&was&to&'chmod&o+r&pubring.pkr'&so&that&the&apache&server&could&read&the&public&keys!!!&&Then,&this&function&worked&fine:&?PHPfunction&pgp_encrypt($keyring_location,&$public_key_id,&$plain_text)&{&&&&&&&&$key_id&=&EscapeShellArg($public_key_id);&&&&&&&&putenv("PGPPATH=$keyring_location");&&&&&&&&//&encrypt&the&message&&&&&&&&$pipe&=&popen("pgpe&-r&$key_id&-af",&"r");&&&&&&&&&&&&&&&&&&&&&&&fwrite($pipe,&$plain_text);&&&&&&&&$encrypted_text&=&'';&&&&&&&&while($s&=&fgets($pipe,&1024))&{&&&&&&&&&&&&&&&&//&read&from&the&pipe&&&&&&&&&&&&&&&&$encrypted_text&.=&$s;&&&&&&&&}&&&&&&&&pclose($pipe);&&&&&&&&return&$encrypted_text;}$message&=&pgp_encrypt("/home/username/.pgp",&"",&"dummy&text&to&be&encrypted");print&nl2br($message);?&
ive&tried&using&popen&using&bidirectional&pipes&without&working&for&obvious&reasons,&but&i&managed&to&create&a&simple&script&that&managed&to&take&care&of&the&problem.&&This&example&is&for&gpg&encryption.
&?php
&&&$message&=&"this&is&the&text&to&encrypt&with&gpg";
&&&$sendto&=&'Dummy&Key&&another@fake.email&';
&&&system("mkfifo&pipein");
&&&system("mkfifo&pipeout");
&&&system("gpg&--encrypt&-a&-r&'$sendto'&&&pipeout&&&pipein&&");
&&&$fo&=&fopen("pipeout",&"r");
&&&$fi&=&fopen("pipein",&"w");
&&&fwrite($fi,&$message,&strlen($message));
&&&fclose($fi);
&&&while&(!feof($fo))&{
&&&&&&$buf&.=&fread($fo,&1024);
&&&}
&&&echo&$buf;
&&&unlink("pipein");
&&&unlink("pipeout");
?&
If&anyone&has&a&better&way&of&doing&this&I&would&love&to&see&it.
Just a quick note about your environment. None of the apache specific environment variables are available to the called program.
Just make sure that you check the user information being passed into the command (if any) before it executes.
Note that your OS must support bi-direction pipes for popen to be bi-directional.
FreeBSD and BSDI are known to support bi-pipes.
Not sure about Linux.

我要回帖

更多关于 文件指针 的文章

 

随机推荐