2010-06-07 42 views
3

我试图通过添加一个方法来允许我使用字符串数据而不是文件路径添加附件,从而扩展了Worx的PHP邮件程序类。使用php://内存包装会导致错误

我想出了这样的事情:

public function addAttachmentString($string, $name='', $encoding = 'base64', $type = 'application/octet-stream') 
{ 
    $path = 'php://memory/' . md5(microtime()); 
    $file = fopen($path, 'w'); 
    fwrite($file, $string); 
    fclose($file); 

    $this->AddAttachment($path, $name, $encoding, $type); 
} 

但是,我得到的是一个PHP的警告:

PHP Warning: fopen() [<a href='function.fopen'>function.fopen</a>]: Invalid php:// URL specified 

有与原文档的任何像样的例子,但我在互联网上发现了一对夫妇(包括one here on SO),根据他们的说法,我的用法显得很正确。

有没有人有使用过这方面的成功?

我的选择是创建一个临时文件并清理 - 但这意味着必须写入光盘,并且此功能将用作大批量处理的一部分,并且我希望避免缓慢的光盘操作(旧服务器) 在可能的情况。这只是一个简短的文件,但脚本电子邮件的每个人都有不同的信息。

+0

我waaay到这个晚了,但不会在fclose()上删除内存缓冲区? – 2015-01-28 10:35:37

回答

1

快速查看http://php.net/manual/en/wrappers.php.php和源代码,我没有看到对“/”。md5(microtime())的支持;“位。

示例代码:

<?php 
print "Trying with md5\n"; 
$path = 'php://memory/' . md5(microtime()); 
$file = fopen($path, 'w'); 
if ($file) 
{ 
    fwrite($file, "blah"); 
    fclose($file); 
} 
print "done - with md5\n"; 

print "Trying without md5\n"; 
$path = 'php://memory'; 
$file = fopen($path, 'w'); 
if ($file) 
{ 
    fwrite($file, "blah"); 
    fclose($file); 
} 
print "done - no md5\n"; 

输出:

buzzbee ~$ php test.php 
Trying with md5 

Warning: fopen(): Invalid php:// URL specified in test.php on line 4 

Warning: fopen(php://memory/d2a0eef34dff2b8cc40bca14a761a8eb): failed to open stream: operation failed in test.php on line 4 
done - with md5 
Trying without md5 
done - no md5 
+0

嗯...是的,我也试过这个 - 我遇到的一个问题是我没有得到附加的内容。这可能是因为phpmailer使用错误的方法来做这件事情...我刚刚意识到,在phpmailer中已经有了一个AddStringAttachment方法(解决了即时问题) - 但是了解php:// memory wrapper – HorusKol 2010-06-07 07:30:35

+0

$ path ='php:// memory /'很好。 MD5(microtime中());打破了一切,你需要使用$ path ='php:// memory'; – Jaro 2014-08-06 13:07:12

15

这只是php://memory。例如,

<?php 
    $path = 'php://memory'; 
    $h = fopen($path, "rw+"); 
    fwrite($h, "bugabuga"); 
    fseek($h, 0); 
    echo stream_get_contents($h); 

产生“bugabuga”。

1

这里简单is the type and the syntax的问题:

php://memoryphp://temp读写流,让临时数据存放在以类似文件的包装。两者之间的唯一区别是php://memory将始终将其数据存储在内存中,而php://temp将在存储的数据量达到预定义限制(缺省值为2 MB)后使用临时文件。该临时文件的位置与sys_get_temp_dir()函数的确定方式相同。

总之,你想要的类型为temp,而不是你想要的语法是:

php://temp/maxmemory:$limit 

$limit是以字节为单位。你想用safe byte functions来计算。

+0

所以如果我使用fopen('php:// temp/maxmemory:1048576','w'),那么我的'filepath'会是什么?整个“'php:// temp/maxmemory:1048576'”?我需要这个文件路径用于其他功能。谢谢 – Andrew 2017-01-12 08:42:16

+0

@Andrew检查'sys_get_temp_dir()'...甚至更好:打开一个新问题,引用这个问题并在那里回答。 – kaiser 2017-01-12 08:48:44

相关问题