I'm want to read a simple string from a text file which is around 3-4 mb but fopen() fails ("can't open file" from die() is called). Here's the code:
clearstatcache();
$fh = fopen("/my/path/to/file.txt", "r") or die("can't open file");
$sql = fread($fh,filesize("/my/path/to/file.txt"));
Have you firstly checked to see if the file exists?
if (!file_exists("/my/path/to/file.txt") {
die('File does not exist');
}
clearstatcache();
$fh = fopen("/my/path/to/file.txt", "r") or die("can't open file");
$sql = fread($fh,filesize("/my/path/to/file.txt"));
you have to add to your code this line
error_reporting(E_ALL);
and ALWAYS keep this line in ALL your codes
and also this line
ini_set('display_errors',1);
and keep this line only on development server.
while on the production it should be changed to
ini_set('display_errors',0);
ini_set('log_errors',1);
By doing this you will not need Stackoverflow assistance in reading the now obvious error messages.
Change that second line to:
$fh = fopen("/my/path/to/file.txt", "r") or die($php_errormsg);
and see what it outputs as the cause.
Try to output system errors in die or try use try…catch. Also turn on php errors while development. Also check if file is readable before open it.
Most common issues are: file does not exists (or just incorrect path provided?), there is not enough permissions to read this file.
In your FTP file permissions tend to need to be 646 (or -rw-r--rw-), not 777 (always ignore those kind of comments). You want to give a key to someone you trust, setting permissions to 777 is like giving a copy of your key to everyone.
You should check that the specified file directory is inside the working directory. You can do this with 'getcwd'
echo getcwd();
If you still get the error, you should check the file permissions.
ls -l /my/path/to/file.txt
If you get this output "-rw-r--r--" you will see the file is writable for admin only.
To make the file writable for everyone use chmod command:
chmod 666 file.txt
You can check again with "ls -l", the z output should be "-rw-rw-rw-"
Related
How do I get something more meaningful than 'FALSE' when I can't open a file.
$myFile = "/home/user/testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
When I use the die statement, can't open file is returned to the client, and it is almost useless. If I remove it, no error is raised. If I return $fh it is FALSE. I tried both local file name and absolute file name. My index.html file is in one of the sub folders of my hole folder. Furthermore, I am using suPHP with the folder I am trying to write to having a permission of 0755 (suPHP requires this for all folders).
How do I figure out why there was a problem, or at least query it before trying to open the file.
Use error_get_last() to catch the (supressed) errors in php:
$f = #fopen("x", "r") or die(print_r(error_get_last(),true));
fopen should raise an E_WARNING if it fails. See error_get_last or set_error_handler(*) to catch it. Other than that you can use file_exists and is_readable to check whether the file is missing or there's another (probably permission-related) problem.
(*) I consider it good practice to always set an error handler that turns all PHP errors into exceptions.
While testing the following code on my local machine, no error was reported. But after testing it on our server at work, I got the following strange error: php is not writing files on the server.
code I am using :
$myfile = fopen( "results/co".$a[$i].".txt", "w") or die("Unable to open file!");
fwrite($myfile,"some text");
fclose($myfile);
So no file is created in this case.
when I try to replace the file name "results/co".$a[$i].".txt" with its value : "results/co00112test.txt" :
$myfile = fopen( "results/co00112test.txt", "w") or die("Unable to open file!");
fwrite($myfile,"some text");
fclose($myfile);
it works just fine.
I also tried the following:
$name = "results/co".$a[$i].".txt";
$myfile = fopen( $name, "w") or die("Unable to open file!");
fwrite($myfile,"some text");
fclose($myfile);
yet with no hope.
What could be the reason for this error ?
If your code works fine when you're putting some static filename, it's obvious that your variable $a[$i] is wrong.
You can proceed that way to debug it :
$name = "results/co".$a[$i].".txt";
var_dump($name);
The name should show something weird, and will tell you what's happening to your file.
it might be all because of permissions. Your php user don't have permission to folder, where you want to create file or don't have permission to file, which you are trying to edit (if file is already there).
You can read full article about permissions here (it's about ubuntu, but it doesn't really matter which OS): https://help.ubuntu.com/community/FilePermissions
you can try permission 644 or if it's not working you can use 777. 644 is more safe, because only the owner of the file will be able to edit it, not any user of your OS.
you can change permissions to folder and all files/folders in it like this:
chmod -R 644 /path/to/folder/
I think 644 is standard for files and 755 for directories.
you can change owner of the file/folder like this:
chown name_of_user:name_of_group /path/to/folder
Your file name is starting with double zero char so it might be an issue.
this will not work :
$number = 112;
$file_name = "results/co".$number."test.txt";
this should work :
$number = 112;
$number_pad = str_pad($number, 5, '0', STR_PAD_LEFT);
$file_name = "results/co".$number_pad."test.txt";
I ran into a really bizarre problem. I am trying to perform writing to file using fopen().
This is what I tried in writetofile.php:
$fw = fopen('/test.txt', 'w');
fwrite($fw, 'hello world' . "\r\n");
fclose($fw);
This is the error I keep getting:
Warning: fopen(/test.txt):
failed to open stream: Permission denied in C:\inetpub\wwwroot\writetofile.php on line 41
Warning: fwrite() expects parameter 1 to be resource, boolean given...
I am 100% sure I have permissions to the server. I am the Administrator. Furthermore, I temporarily gave full permissions to everyone. I even tried running the php script locally, directly from the server using localhost. I am not using apache, I am using IIS. I tried restarting IIS after modifying permissions. I am not running php in safe mode.
Any idea on what might be causing this issue?
/test.txt would be a file in the ROOT directory of your filesystem, where user accounts generally do NOT have write privileges (unless you're running this code as root). This is especially true of PHP running under the webserver's user account.
You probably want just test.txt (no leading slash)` which will try to put the file into the script's "current working directory" - usually the same directory the script itself is in.
1- when you rollout website, delete all logs folder names
2- inside the code create folder name as below and create the logs insides
3- write at top of file. (during init the web)
$ClientUserName = gethostbyaddr($_SERVER['REMOTE_ADDR']);
function Data_Log($dataline)
{
global $ClientUserName;
$dir = 'UserInputLog' ;
$fileName = $ClientUserName. '_ServerWebLog.txt';
if(is_dir($dir) === false)
mkdir($dir);
$fileName = $dir. '\\'.$fileName;
$myfile = fopen($fileName, "a") or die("Unable to open file!");
fwrite($myfile, "$dataline\r\n");
fclose($myfile);
}
I want to HTTP POST data to a PHP file which will in-turn write the data into a file. The script I used is as follows,
<?php
#error_reporting(E_ERROR | E_PARSE);
$msglen=strlen($_POST["msgarea"]);
$msg=$_POST["msgarea"];
$fp = fopen("dinesh.txt", 'w');
fwrite($fp, $msg);
fclose($fp);
echo "Data Written -> $msg";
?>
I am hosting this script file in sourceforge.
I have already just created the empty file dinesh.txt and placed the file in the same directory as that of the script file. But unfortunately its not written in the file.
What is the reason ?
Thanks in advance
Check that $_POST["msgarea"] is not empty and the file is writeable for the user who tries to write it.
And check the logs for errors of course.
<?php
error_reporting(E_ALL);
var_dump($_POST["msgarea"]);
$msglen=strlen($_POST["msgarea"]);
$msg=$_POST["msgarea"];
$fp = fopen("dinesh.txt", 'w');
$result = fwrite($fp, $msg);
fclose($fp);
if ($result) {
echo "Data Written -> $result";
} else {
echo "Error";
}
I think you are writing in read-only webspace, check file permissions and path
From: http://sourceforge.net/apps/trac/sourceforge/ticket/2772
In generally it is not allowed to write to folders and files that reside in the project's web space. If you need to write to the file system you should use the folder named persistent that is on the same level as htdocs.
I use on my computer:
$ mkdir persistent
$ chmod 0777 persistent
$ scp -r persistent my_account#web.sourceforge.net:/home/project-web/my_project/
And set in PHP:
$fp = fopen("../persistent/dinesh.txt", 'w');
And it works!
Edit:
You can get access for SSH console for 4 hours (https://sourceforge.net/apps/trac/sourceforge/wiki/Shell%20service). And you can go to web directory of your project, make dirs, set privileges, remove files etc. Midnight Commander is available.
you can, check that folder permission, do they have 777 permission
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
fclose($fh);
I am trying to read a video file uploaded on server using fopen and fread in php but fopen returns "unable to open file".
//test.php
<?php
$file=fopen("abc.mov","r") or exit("Unable to open file!");
?>
abc.mov exists in the same folder where test.php is located on the server i.e, at the same hierarchy.
I don't why it isn't able to read the file.
Please help.
This probably isn't a real problem with PHP or your file. This is most likely a problem with the permissions of the file. There are three things you can try here(probably more I don't know of). One, do this somewhere before the fopen in your script:
chmod("abc.mov", 0777);
Then echo fileperms(), just to check(take out after debug):
echo fileperms("abc.mov");
And lastly, before calling fopen, make sure that is_readable and file_exists return true:
if(file_exists("abc.mov") and is_readable("abc.mov")) {
$file = fopen("abc.mov","r") or exit("Unable to open file!");
}
else die("File isn't readable, or maybe doesn't even exist!");
Note: I would be using file_get_contents() and file_put_contents() rather than fopen.
Hope this helps!
Check your file access permissions to make sure you've got access to the file from PHP.