I'm using xampp in Windows for local developing environment. I tried to create a simple logger which appends to a text file.
function Logger ($logmessage)
{
$filename = '/errorlog-' . date('Ymd') . '.txt';
file_put_contents($filename, $logmessage, FILE_APPEND | LOCK_EX);
}
I've tried to echo the $filename, and it says '/errorlog-20140427.txt' which means it already has valid filename (I think).
But when I call this logger function, there's no error raised, but I can't find the file everywhere. I tried to search for the whole htdocs for *.txt but no files found. Do you know why I can't write file using php? Do I need to use fopen first? As I refer to another help, I can just use file_put_contents directly without fopen. Thanks for the help.
You're trying to write to the root of your filesystem, e.g.
$file = '/error-log-' etc...
is essentially the same as
$file = 'c:/error-log' etc...
The webserver account is highly unlikely to have the rights to do anything in C:\.
If you'd bothered checking the return value of file_put_contents, you'd have seen it was returning a boolean false to indicate failure.
Related
Hello I am relatively new to PHP and I was trying to replace a row in a csv file, i didnt find an optimal solution so I concocted script (a work around) which suits my needs for the time being till I grasp a better understanding of PHP
I tested it on my localhost using XAMPP and everything was working fine , it was replacing the row as intended but when i uploaded the files to my cpanel it stopped replacing and instead it just goes the normal route and write the row on new line.
this is my code :
$fileName = 'Usecase.csv'; //This is the CSV file
$tempName = 'temp.csv';
$inFile = fopen($fileName, 'r');
$outFile = fopen($tempName,'w');
while (($line = fgetcsv($inFile)) !== FALSE)
{
if(($line[0] == "$fin") ) //Here I am checking the value of the variable to see if same value exists in the array then i am replacing the array which will be later written into the csv file
{
$line = explode (",", "$tempstr10");
$asd=$asd+1; //this is the variable that i defined and assigned value 0 in the top most section, this is used later in the code
}
fputcsv($outFile, $line );
}
fclose($inFile);
fclose($outFile);
unlink($fileName);
rename($tempName, $fileName);
if( $asd==0 && filesize("Usecase.csv")>0) // here its checking if the value is 0 , if value is 0 then that means the above code didnt execute which means the value wasnt present in the file , this is to avoid writing the same string again into the file
{ file_put_contents("Usecase.csv", "$tempstr10\r\n",FILE_APPEND | LOCK_EX); }
if( $asd==0 && filesize("Usecase.csv")==0)
{ file_put_contents("Usecase.csv", "$tempstr10\r\n",FILE_APPEND | LOCK_EX); }
and as I mentioned above , its working on the localhost but not on the cpanel , can someone point out if something is wrong with the code ? or if its something else ?
thank you
The most likely problem is that your local version of PHP or your local configuration of PHP is different from what is on the server.
For example, fopen is a feature that can be disabled on some shared servers.
You can check this by creating a php file with the following conents:
<?php phpinfo();
Then visit that PHP file in your browser. Do this for both your local dev environment and your cPanel server to compare the configuration to identify the differences that may be contributing to the differing behavior.
You should also check the error logs. They can be found in multiple different places depending on how your hosting provider has things configured. If you can't find them, you'll need to ask your hosting provider to know for sure where the error logs are.
Typical locations are:
The "Errors" icon in cPanel
A file named "error_log" in one of the folders of your site. Via ssh or the Terminal icon in cPanel you can use this command to find those files: find $PWD -name error_log
If your server is configured to use PHP-FPM, the php error log is located at ~/logs/yourdomain_tld.php.error.log
You should also consider turning on error reporting for the script by putting this at the very top. Please note that this should only be used temporarily while you are actively debugging the application. Leaving this kind of debugging output on could expose details about your application that may invite additional security risks.
<?php
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
... Your code here ...
Here is a snippet of what I'm trying to do:
$file = fopen($path, "wb");
fwrite($file, $data);
fclose($file);
Simple enough.
But when I open the created file, I see 0x0D inserted before 0x0A everywhere. I understand that this will happen if I open the file without binary mode.
But I've clearly specified I want binary mode. Maybe my brain isn't functioning right or something, so.. Anyone got a solution?
It turns out, for some weird reason, the problem was with my $path. My $path value was "temp".
It would generate the file named "temp" but would refuse to open it in binary mode. Giving the file an extension like "temp.bin" or "temp.tmp" allowed it to work in binary mode.
Problem solved for now but I'm still wondering why it works like this.
Seems the problem is with the $path. Please make sure you have given the correct file path.
If you are defining the $path with a dynamic file name, use / before the file name. For example, $var = "/var/www/html/projectFolder/folderFile/". "Filename.fileformat"
If you're working with URLs in a redirection context, then the root directory ('/') refers to your domain's root. The same goes for paths for linking files or images and for include and require directives.
You're making the classic mistake of confusing data with the representation of that data.
Let's say you have a text file. If you open it in Notepad, you'll see the following:
$str = "Hello world!";
echo bin2hex($str); // output: 48656c6c6f20776f726c6421
$file = fopen($path, "wb");
$data = bin2hex($data);
fwrite($file, $data);
fclose($file);
I have a PHP code that connects to a FTP server, reads a file's content, makes a minor change, and than overrides the original file.
it looks like:
$stream_context = stream_context_create(array('ftp' => array('overwrite' => true)));
$file_content = file_get_contents($ftp_file); // this line works
$file_content = str_replace('some content', 'another content', $file_content); // this also..
file_put_contents($ftp_file, $file_content, 0, $stream_context); // this one doesn't :/
the real issue is that the "file_put_contents" worked for a long time, but now it doesn't.
what it does now is weird: it deletes the original file from the server..
also, if i'm changing it to something like:
file_put_contents($new_ftp_file, $file_content);
from what I know, it should create the new file and put the content in it, but it doesn't create it at all.
the hosting service i'm using has a PHP version change a few days ago. I don't remember the what the previous version was, but the current is: 5.2.17
thanks! :)
some changes
I found this piece: http://www.php.net/manual/en/function.file-put-contents.php#86864
doting the same as "file_put_contents" but with foen, fwrite and fclose (I send his example because of the results..). his functions is returning "false" if it couldn't to "fopen" the file, or the "bytes" if it succeeded. I got "false" :/
which means it couldn't even do the:
#fopen($filename, 'w');
although the "file_get_contents" with the same file address is working.
reading is working (but if you take the $filename and use it yourself on a client FTP - it works):
#fopen($filename, 'r');
the "open base_dir" for my hosting (which makes the action) is set to false, but the target hosting (which has the target-file) is set to be true.
I had an idea to save the new content on a new file, so I tried something like:
$f = #fopen($new_ftp_file, 'w'); //this one seems to work and connect
fwrite($f, $file_content); // this one seems to work either and returning the number of byes..
fclose($f);
the problem is that none of them really works. I logged in to the FTP address, using the same credentials that my script is using, and I haven't found the new file. It wasn't created at all. (as I remind you, "$new_ftp_file" is a path to a file that doesn't exists, so "w" mode on "fopen" should create it).
file_put_contents do erase the file by default if it already exists. You have to ask him to don't.
Look at here:
http://www.php.net/manual/en/function.file-put-contents.php
See: If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.
this is not the best solution (definitely), but I managed to figure something..
I used 2 different hosts on them same hosting service, both of the having "open base_dir = On" & "safe mode = Off".
it looks something like:
$ftpstring = "ftp://user:password#anotherhosteddomain.com";
$file = file_get_contents($ftpstring . 'index.html'); // this line works as expected. (yeah, the other hosting has this file);
and then, if you're trying to write something like:
$handler = fopen($ftpstring.'index.html', "w");
it wouldn't work, and tell you it cannot access on writing mode to an existing file.
so if you're doing something like:
$newfile_handler = fopen($ftpstring.'index_new_version.html', "w");
fwrite($newfile, "1122");
so yeah - it works!
but now is a tricky issue.. when i'm adding this line:
fclose($newfile_handler);
the new file is deleted from the hosting!!
I couldn't find any reason why "fclose" is deleting the file after it was create at "fopen" and written in at "fwrite".
so if you're not adding the "fclose" line - it works, but it doesn't close the connection, and also I have to actually delete the existing file before I can override it with a new content, which makes it silly..
although it works, I would really like someone to give me a better solution than mine.
I have read the documentation and it doesn't seem to indicate where can I expect the file to be created. I assumed that If I used file_put_contents on a server then a txt file would be created in the same place where the php file running it is. What am I missing here? I'm trying to save the url's in a text file as well.I just need them on my computer really not on the server.
while ($blekr<=$blekko_count)
{
echo '<a href='.$Blekko[$blekr]['url'].'><h4>'.$Blekko[$blekr]['url_title'].'</h4></a>';
echo '<p>'.$Blekko[$blekr]['snippet'].'<p>';
echo '<b>'.$Blekko[$blekr]['engine'].'</b>';
$file = 'Blekko.txt';
file_put_contents($file, $Blekko[$blekr]['url'], FILE_APPEND);
echo '<hr>';
$blekr++;
}
Unless you specify a different directory (using one or more slashes), the file is saved in the current working directory. getcwd() returns the current working directory; chdir() changes it.
The script is in myusername/public_html/item/index.php
code to save file:
$filename = $_SERVER['DOCUMENT_ROOT'].'/../data/guestbook.txt';
$filehandle = fopen($filename, 'ab+') or die("<p>Unable to create the file!</p>\n".$filename);
flock($filehandle, LOCK_EX) or die("<p>Unable to lock the file!</p>\n");
fwrite($filehandle, $new_entry) or die("<p>Unable to write to the file!</p>\n");
fclose($filehandle);
For some reason it fails on the fopen and the filename is actually ends up being literally with the /../ instead of navigating to the proper path.
What to do, what to do?
you can code like this if the php script is in the item folder and item and data are at the same level in the directory hierarchy
$savedir = '../data/';
$filename = $savedir.'guestbook.txt';
make sure apache user has the write access to the directory by "chown -R apache:apache" and "chmod 755".
Probably the " /../ " in your code is giving the error. Try removing the first forward slash.
For some reason it fails on the fopen
There is no "some reasons" in programming. There are always a certain reason.
And you have to know it.
filename is actually ends up being literally with the /../
That's exactly what you wrote, nothing to complain of.
How can I save a file in PHP to a directory higher than current?
Technically you are setting it correct.
But there can be another reason, other than wrong way of the path creation.
Yes, there always can be many reasons for the program to fail!
What to do, what to do?
Run this code and see what it says.
ini_set('display_errors',1);
error_reporting(E_ALL);
$filename = $_SERVER['DOCUMENT_ROOT'].'/../data/guestbook.txt';
file_put_contents($filename,$new_entry);
it will tell you the reason why it fails.