note 120345 deleted from function.tmpfile by cmb
| From: | cmb@php.net | Date: | Fri, 16 Dec 2016 23:06:37 +0000 |
| Subject: | note 120345 deleted from function.tmpfile by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208612@lists.php.net to get a copy of this message | ||
Note Submitter: ivan dot vlk at develart dot de
----
It's not obvious, but if you create method within any class and use tempfile() in within, then
returning path to this temp file - you wont get the file, it's already removed on the return
from function.
To avoid that, you need to keep reference outside of the used function and just pass it as variable.
<?php
class A {
public function writeToFile( $tempFile) {
fwrite($tempFile, "something");
}
public function doSomething() {
$tempFile = tmpfile();
$this->writeToFile($tempFile);
// file is still living here, because variable with reference is in sacope
}
}
class B {
public function writeToFile() {
$tempFile = tmpfile();
fwrite($tempFile, "something");
$tempPath = stream_get_meta_data($tempFile);
return $tempPath['uri'];
}
public function doSomething() {
$tempFile = tmpfile();
$path = $this->writeToFile($tempFile);
// file is already gone, $path is pointing to non-existent
}
}
?>