I'm new in using PHP and I would like ask for this question;
I have variable
$content = $recfile[0]['name'];
This variable $content include name selected from mysql DB.
I would like variable $content save to the file.
I used:
$fp = fopen(DIR_PATH . "\\public\\temp\\myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
I don't know where is the mistake. I tried various options as serialize or var_export but nothing worked.
If you are writing to a linux file system, you should use forward slashes
$fp = fopen(DIR_PATH . "/public/temp/myText.txt","wb");
You should also check if fopen worked. If fopen failed, the value of $fp will be false
if($fp) {
//code to write to the file
}
Have you checked if $content does indeed have any content (by f.i. echo $content;) and if your constant DIR_PATH holds the right path?
If those are correct, try forward slashes (though escaped backslashes should work)
$fp = fopen(DIR_PATH . "/public/temp/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
Related
I have the contents of a file in a string. I need to pass this file to a function where the function is expecting the parameter to be the name of the file, not the contents. The obvious and probably simplest way to do this would be to write the contents to a temp file, then pass that file name to the function, and unlink the file once I'm finished.
However, I'm looking for a solution that doesn't involve writing the file out to the file system and then reading it back in. I've had a need for this in multiple cases, so I'm not looking for a work-around to a specific function, but more of a generic method that will work for any function expecting a file name (like file_get_contents(), for instance).
Here are some thoughts, but not sure how to pursue these yet:
Is it possible to write the contents somewhere in memory, and then
pass that to the function as a filename? Perhaps something using
php://memory.
Is it possible to write the contents to a pipe, then pass the name of the
pipe to the function?
I did a short proof-of-concept trying with php://memory as follows, but no luck:
$data = "This is some file data.\n";
file_put_contents( 'php://memory', $data );
echo file_get_contents( 'php://memory' );
Would be interested in knowing of good ways to address this. Googling hasn't come up with anything for me.
It mainly depends on what the target function does with the file name. If you're lucky, you can register your own stream wrapper:
stream_wrapper_register('demo', 'DemoStream');
$data = "This is some file data.\n";
$filename = 'demo://foo';
file_put_contents($filename, $data );
echo file_get_contents($filename);
Why not use a file in the /tmp/ directory? Like this:
<?php
$filename = '/tmp/mytmpfile';
$data = "This is some file.\n";
file_put_contents($filename, $data);
$result = file_get_contents($filename);
var_dump($result);
Well, as you say you don't want to use a file, you shouldn't use file_get_contents().
But you can achieve the same result by using stream_get_contents(), like this:
<?php
$data = "This is some file data.\n";
$handle = fopen('php://memory', 'r+'); // open an r/w handle to memory
fputs($handle, $data); // write the data
rewind($handle); // rewind the pointer
echo stream_get_contents($handle); // retrieve the contents
I'm writing a function in php, client side I have a canvas image which I use toDataUrl() along with a file name to save the image on the server. The here's the code:
<?php
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
$data = json_decode($imageData, true);
$file = $data["file"];
$image = $data["data"];
$filteredData=substr($image, strpos($image, ",")+1);
$unencodedData=base64_decode($filteredData);
$fp = fopen( 'image/' . $file , 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
?>
The thing is that this code works. And for two out of three of the pages I used it on it works fine. The problem is when I copy and pasted it a third time to implement it again, for some reason the file is made on the server except that no data get's written into the file. I don't think it's a problem client side because I write in a debug alert message in the javascript and a debug echo into the PHP and both are able to print out the data fine. I made this short debug file:
<?php
$fp = fopen('data.txt', 'wb');
if(is_writable('data.txt')){
echo "file is writable<br>";
}
if(fwrite($fp, 'test') == FALSE){
echo "failed to write data<br>";
}
fclose($fp);
?>
And the output is
file is writable
failed to write data
I've tried using chmod and setting everything, the folder, the text file before I write to it to 0777 and I still get the same result; the file is made but no data is written into it. Is there anything I'm missing or any other approaches that might help. I haven't found anything on google and am still baffled as to why the same code worked exactly as expected twice before suddenly stopping for no apparent reason.
Thanks in advance.
I know this is an old post, but I had a very similar problem and found a solution (for me at least)! I ran out of disk space on my server, so it could create a 0 byte file, but wouldn't write to it. After I cleared out some space (deleted a 13gb error.log file) everything started working again as expected.
If fopen works but fwrite mysteriously doesn't, check your disk space. 'df -h' is the command to check disk space on a linux server.
instead of $fp = fopen('data.txt', 'wb'); give $fp = fopen('data.txt', 'w'); and try
Changed "wb" to "w"
When you write $fp = fopen('data.txt', 'w'); for your domain website.com having root at /var/www/website/ and if the php file is located at /var/www/website/php/server/file/admin.php or something similar, it will actually create a file at /var/www/website/data.txt
Try giving absolute path or path relative to your domain root to create files like,
$fp = fopen('php/server/file/data.txt', 'w');
Try the find command to see if the file is created anywhere else in the folder directory by using the following in Ubuntu,
find /var/www/website/ -name 'data.txt'
I had this issue, probably can help you solve if you have similar issue.
i have this following php code :
$filename = '/front/style.css';
$cssfile='#h1{font-size:12px}';
if($id_file=fopen($filename, "w+"))
{
echo'file exist';
$id_file=fopen($filename, "w+");
flock($id_file,1);
fwrite($id_file,$cssfile);
flock($id_file,3);
fclose($id_file);
}
else
{
echo "file don t exist";
}
My file is empty but with space.
My file exist and it s writable.
I have nothing in my apache logs.
I m using Mamp with php 5.3.2.
Any ideas ?
Thx
A few mistakes I can see are:
You are using fopen to check if a file exists. That does not work. With the w+ mode PHP will try to create the file if it does not exist. Use the file_exits function to check the existence of a file.
You are opening the same file twice.
Also use PHP constants(LOCK_SH, LOCK_UN) for the second argument of flock. That will make your program more readable.
Updated
Have you checked if its writing to a different directory than you expect? Check your path to see where it defaults to, or even just do a search for the file and see where else it turns up. getcwd() will show what the current working dir is.
Have you checked the return value of fwrite to see if the write is actually working? If fwrite is successful, then try read the file in the code using the same $id_file and see if there is anything there while the program is still running.
You are calling fopen twice. w+ truncates the file and you are writing to the 2nd $id_file so my guess is that its being truncated when the 1st $id_file is being closed.
You can use this approach if your file empty after using fopen w+ option.
// only read
$filename = '/path/to/blah.txt';
$myfile = fopen($filename, "r");
$mydata = fread($myfile, filesize($filename));
$mynewdata = $mydata + 'abc';
fclose($myfile);
// only write
$myfile = fopen($filename, "w");
fwrite($myfile, $mynewdata);
fclose($myfile);
I'm writing tests for my CodeIgniter site using simpletester.
One of the things that it does is offer autogenerated files.
I want to test if the output of a file is correct.
However, if I do this:
function testFunction1(){
$url = site_url('downloader/function1');
$handle = fopen($url,'r');
$contents = stream_get_contents($handle);
echo $contents;
fclose($handle);
}
It outputs a 404.
It works perfectly when I put "www.google.com" as the url.
I can also download the file if I copy paste the URL in the browser.
Thanks!
edit:
Even if I try to download a regular file (so not a php function), with the full url, it gives the 404.
when your using relative paths, simply remove site_url() for relative path instances.
fopen accepts the following:
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password#example.com/somefile.txt", "w");
But site_url seems to be adding something.
also be sure to check the relative path directory is corrent.
If you're accessing locally then just use
$url = "main/function":
$file_content = file_get_contents("http://localhost/codeignitor/" . $url);
Code works fine, except for the fact that there is a problem here:
//Log Events
function logEvent($newinput) {
if ($newinput !== NULL) {
// Add a timestamp to the start of the $message
$newinput = date("Y/m/d H:i:s").': '.$newinput;
$fp = fopen('log.txt', 'w');
fwrite($fp, $newinput."\n");
fclose($fp);
}
}
//Problem writing these two lines to log.txt?
//The bad, the two lines below are not on the log.txt
logEvent('Selection'.$selections[$selection]);
logEvent('Change' . $change. 'cents.');
//This line is written to a text file (log.txt), okay that's good.
logEvent('Input' . $newinput);
i think you're not appending to the file, you're rewriting it. try fopen with 'a' instead of 'w'.
You need to use the append modifier when opening the file, you've gone
fopen('log.txt', 'w');
this means that every time you call that function, the log file is getting blown out and recreated, if you instead used
fopen('log.txt', 'a');
then your new log entries will append to the file instead.
You could also look into keeping the file open for later inserts too, but there may be issues with multiple updates in other requests.