fwrite to txt-file - php

I'm currently trying to write to a txt-file with PHP, I've found this small script:
<?php
$filename = 'testFile.txt';
$somecontent = "Add this to the file\n";
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
}
else {
echo "The file $filename is not writable";
}
?>
I get a success-message, but nothing is written to the file. Even if I delete the txt-file I still get the success-message
Does anybody know how to troubleshoot a situation like this?

Your code works perfectly fine. However, note that the is_writable check will fail if the file does not exist yet.
If you execute it through a webserver, make sure you are not viewing a cached response.

Your first check with is_writable is not useful, as it fails if the file does not exist.
When you use fopen with the "a" parameter you appent to the file if it exists otherwise it will create a new one.
If you want to check if the file exists you can with file_exists ( http://php.net/manual/en/function.file-exists.php ), but it is not really necessary.
With your code, if you delete the file you should actually get a "the file is not writable" error... are you sure you have exactly that code?
Otherwise, I tried the code and it works fine (without the first if).

Related

php delete file with unlink()

I have read a lot of pages about this but I just can't get it to work.
I have a file on my server that needs to be deleted after the file has been imported.
The file is a .csv file and opened with fopen.
After import the file is closed with fclose.
Now I want to delete the file with:
chown($filepath, 666);
if (file_exists($filepath))
{
if (unlink($filepath))
{
echo "success";
}
else
{
echo "fail";
}
}
else
{
echo "file does not exist";
}
It keeps failing with file does not existbut I don't know why.
I use the exact same path to import
M.
You cant directly access the file using URL
$filepath = 'http://www.xxx.nl/files/testing.csv';
To access your file, use
$filepath = ./files/testing.csv
so file structure would be
- file
- testing.csv
- index.php

Cannot open file using fopen (php)

I am trying to open a file for reading in php script but having trouble.
This is my code
$fileHandle = fopen("1234_main.csv", "r")or die("Unable to open");
if (!file_exists($fileHandle))
{
echo "Cannot find file.";
}
The script is in the same directory as the file I am trying to read and there are no other read/write permission errors as I can create/read other files in the same directory.
When I run the script I just get the "Cannot find file" error message. Why is this error message being shown? Surely if fopen() can't open the file the "or die statement" should end the script?
Also, why can't I open the file when it definitely exists and is in the same location as the script (I have also tried using the full path of the filename instead of just the filename).
I am fairly new to php (but have exp in c++) so if its a stupid question I apologize.
Many thanks
In PHP, file_exists() expects a file name rather than a handle. Try this:
$fileName = "1234_main.csv";
if (!file_exists($fileName))
{
echo "Cannot find file.";
} else {
$fileHandle = fopen($fileName, "r")or die("Unable to open");
}
Also keep in mind that filenames have to be specified relative to the originally requested php-script when executing scripts on a web server.
You can use file_get_content() for this operation. On failure, file_get_contents() will return FALSE.For example
$file = file_get_contents('1234_main.csv');
if( $file === false ){
echo "Cannot find file.";
}
file_exists() take the file-name as input, but the logic of your code has problem. You first try to open a file then you check its existence?
You first should check its existence by file_exists("1234_main.csv") and if it exists try to open it.
file_exists takes a string, not a file handle. See http://php.net/manual/en/function.file-exists.php

Using fopen and fwrite with Zend Framework?

I'm attempting to check for file existence with Zend Framework and, if the file doesn't exist, have it be created. Here's the code being used:
$filename = "/assessmentsFile/rubrics/$rubricID.php";
$somecontent = "test";
if (!$handle = fopen($filename, 'w+')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === false) {
echo "Cannot write to file ($filename)";
exit;
}
However, I assume due to Zend's way of handling file structure, if a file doesn't exist it just spits out:
Warning: fopen(/assessmentsFile/rubrics/1.php) [function.fopen]: failed to open stream: No such file or directory
Because the fopen function isn't working, fwrite is unable to write the file.
Is there another way of doing this?
Most likely the issue is with the path to $filename.
You have
$filename = "/assessmentsFile/rubrics/$rubricID.php";
which tries to create a file in the root of the server in a directory called assessmentsFile.
Most likely you need to be using:
$filename = $_SERVER['DOCUMENT_ROOT'] . "/assessmentsFile/rubrics/$rubricID.php";
$_SERVER['DOCUMENT_ROOT'] should do the trick if the assessmentsFile folder is in your web root. Otherwise there are other variables you can use to get a fully qualified path, or you can simply hard-code the path:
$filename = "/home/yoursite/public_html/assessmentsFile/rubrics/$rubricID.php";
There's a function file_exists that tells you if the file exists, and with is_file you can check it's a file (and not a directory for example).
(Another way is to suppress warnings by putting an # before the function call (e.g. $handle=#fopen(...), but it's better to check for file existence)
Try this:
if(is_file($filename)){ // exists
$handle=fopen($filename,"w+");
}else{
$handle=fopen($filename,"w"); // create it
}
// ...

Php fopen write in css file -> file empty

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);

Unable to open a file for writing

I am trying to write to a file. I do a file_exists check on it before I do fopen and it returns true (the file does exist).
However, the file fails this code and gives me the error every time:
$handle = fopen($filename, 'w');
if($handle)
{
flock($handle, LOCK_EX);
fwrite($handle, $contents);
}
else
{
echo 'ERROR: Unable to open the file for writing.',PHP_EOL;
exit();
}
flock($handle, LOCK_UN);
fclose($handle);
Is there a way I can get more specific error details as to why this file does not let me open it for writing? I know that the filename is legit, but for some reason it just wont let me write to it. I do have write permissions, I was able to write and write over another file.
Just because the file exists doesn't mean that you have permission to write to it. Before trying to write to a file, you should check to see if PHP has permission to do so using is_writable.
or general way of getting errors:
ini_set('display_errors',1); // for the development PC only
error_reporting(E_ALL); // ALWAYS
to see the actual error message
If you're using php 5.2+ you might be interested in error_get_last().
On your development system you can also increase the error reporting level, either within the script via error_reporting() or (preferably) in your php.ini.
error_reporting(E_ALL);
ini_set('display_errors', 1);
$handle = fopen($filename, 'w');
if(!$handle) {
echo 'ERROR: Unable to open the file for writing.',PHP_EOL;
var_dump(error_get_last());
exit();
}
flock($handle, LOCK_EX);
fwrite($handle, $contents);
flock($handle, LOCK_UN);
fclose($handle);
Sounds like the directory you're writing to doesn't have the correct permissions.

Categories