简体   繁体   English

在PHP中包含一个已经打开的文件?

[英]Include an already open file in PHP?

I'd like to include an already opened file. 我想include一个已经打开的文件。 As include wants a filename this seems untrivial. 正如include想要文件名一样,这似乎是无可厚非的。

The only thing I can find on http://php.net/manual/en/wrappers.php.php is to somehow coax the file descriptor out of the return value of fopen and use php://fd/$fd . http://php.net/manual/en/wrappers.php.php上,我唯一能找到的就是以某种方式将文件描述符从fopen的返回值中fopen出来,并使用php://fd/$fd I can't get any further. 我再也没有办法了。

Edit: apparently it is not clear, I would like to reuse the file descriptor and not reopen the file. 编辑:显然不清楚,我想重用文件描述符,而不是重新打开文件。

This might work for you. 这可能对您有用。 Depending on how the stream was opened, it might return either the full path name or just the base name, so you'll probably have to do some munging to check and make sure the right path is supplied. 根据流的打开方式,它可能返回完整路径名或仅返回基本名,因此您可能必须做些调整以检查并确保提供正确的路径。 (Or the script is run from the correct directory.) (或者脚本从正确的目录运行。)

<?php

    $fh = fopen('include_source.php', 'r');
    $md = stream_get_meta_data($fh);
    include $md['uri'];
?>

You can use a temp file: 您可以使用一个临时文件:

$return_to_position = ftell($fp);
$temp_path = tempnam('/tmp', 'INC');
$temp_fp = fopen($temp_path, 'w');
rewind($fp);
while(!feof($fp)) {
   fwrite($temp_fp, fread($fp, 1024));
}
fclose($temp_fp);
fseek($fp, $return_to_position);
include $temp_path;

edit as an in-memory alternative 编辑为内存替代

Similar to my previous answer, but completely in memory... and using the dreaded eval()... ( don't hate on eval : this is equivalent to the previous answer in terms of security) (I mean, the idea in general makes me uneasy... but it's cool to try and solve ;-) 与我先前的答案类似,但完全在内存中...并使用了可怕的 eval()...( 不要讨厌eval :就安全性而言,这等效于先前的答案)(我的意思是,一般使我不安...但是尝试解决问题很酷;-)

NOTE eval does not like php tags, this may not work if the file has them... 注意 eval不喜欢php标记,如果文件包含php标记则可能不起作用...

$return_to_position = ftell($fp);
rewind($fp);
$fp_php_code = "";
while(!feof($fp)) {
  $fp_php_code .= fread($fp, 1024);
}
fseek($return_to_position);
eval($fp_php_code);

I'm not sure what you are after, but if it's something like adding classes dynamically (as opposed to procedural code), you could explore the experimental PECL extension bcompiler_read 我不确定您要做什么,但是如果是像动态添加类(而不是过程代码)那样,则可以探索实验性的 PECL扩展bcompiler_read

Apparently you can give it a file descriptor and it will read it and create classes... seems pretty cool. 显然,您可以给它一个文件描述符,它将读取它并创建类...似乎很酷。

There is also runkit , which allows runtime manipulation of several facets, including class hierarchy. 还有runkit ,它允许对多个方面(包括类层次结构)进行运行时操作。 Also experimental. 也是实验性的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM