file_get_contents with empty file not working PHP - php

I try to use file_get_contents form PHP but it's not working.
There is my code :
$filename = "/opt/gemel/test.txt";
if($filecontent = file_get_contents($filename)){
$nom = fgets(STDIN);
file_put_contents($filename, $nom, FILE_APPEND);
}
else
echo "fail";
And my file test.txt is empty. (0 octets). He exists but he is empty.
When i write something into it, my code works perfectly but if he is empty my code echo "fails"
Why that, why he can't open the file text.txt ?

The function file_get_contents returns the string that's in the file. If the file contains no data, then file_get_contents returns an empty string. If you would try to var_dump('' == false); you would get true. So, even though the file can be read, the contents of the file evaluates to false.
If you would use this line, your code should work:
if($filecontent = file_get_contents($filename) !== false){
Edit; link to the documentation of the Comparison operators.

Related

PHP. How to read a file, if it is writing without a problem with "a+", but is not readable with "r"?

I have two scripts: one of them writes the value of a variable to a file. In another script, I try to read it. It is written without problems, but it is not readable.
Here I write to a file:
$peer_id=2000000001;
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"a+");
fwrite($file, $peer_id);
fclose($file);
Here I read the file:
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"r");
if(file_exists($fileLocation)){
// Result is TRUE
}
if(is_readable ($file)){
// Result is FALSE
}
// an empty variables, because the file is not readable
$peer_id = fread($file);
$peer_id = fileread($file);
$peer_id = file_get_contents($file);
fclose($file);
The code runs on "sprinthost" hosting, if that makes a difference. There are suspicions that this is because of that hosting.
file_get_contents in short runs the fopen, fread, and fclose. You don't use a pointer with it. You should just use:
$peer_id = file_get_contents($fileLocation);
That is the same for is_readable:
if(is_readable($fileLocation)){
// Result is FALSE
}
So full code should be something like:
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
if(file_exists($fileLocation) && is_readable($fileLocation)) {
$peer_id = file_get_contents($fileLocation);
} else {
echo 'Error message about file being inaccessible here';
}
The file_get_contents has an inverse function for writing; https://www.php.net/manual/en/function.file-put-contents.php. Use that with the append constant and you should have the same functionality your first code block had:
file_put_contents($fileLocation, $peer_id, FILE_APPEND | LOCK_EX);

My php script won't open files that aren't in its root directory

This is a php script for a user login system that I am developing.
I need it to read from, and write to, the /students/students.txt file, but it won't even read the content already contained in the file.
<?php
//other code
echo "...";
setcookie("Student", $SID, time()+43200, "/");
fopen("/students/students.txt", "r");
$content = fread("/students/students.txt", filesize("/students/students.txt"));
echo $content;
fclose("/students/students.txt");
fopen("/students/students.txt", "w");
fwrite("/students/students.txt", $content."\n".$SID);
fclose("/students/students.txt");
//other code
?>
You are not using fopen() properly. The function returns a handle that you then use to read or edit the file, for example:
//reading a file
if ($handle = fopen("/students/students.txt", "r"))
{
echo "info obtained:<br>";
while (($buffer = fgets($handle))!==false)
{ echo $buffer;}
fclose($handle);
}
//writing/overwriting a file
if ($handle = fopen("/students/students.txt", "w"))
{
fwrite($handle, "hello/n");
fclose($handle);
}
Let me know if that worked for you.
P.S.: Ty to the commentators for the constructive feedback.
There are many ways to read/write to file as others have demonstrated. I just want to illustrate the mistake in your particular approach.
fread takes a file handle as param, NOT a string that represents the path to the file.
So your line:
$content = fread("/students/students.txt", filesize("/students/students.txt")); is incorrect.
It should be:
$file_handle = fopen("/students/students.txt", "r");
$content = fread($file_handle, filesize("/students/students.txt"));
Same thing when you write contents to file using fwrite. Its reference to the file is a File Handle opened using fopen NOT the filepath. when opening a file using fopen() you can also check if the $file_handle returned is a valid resource or is false. If false, it means the fopen operation was not successful.
So your code:
fopen("/students/students.txt", "w");
fwrite("/students/students.txt", $content."\n".$SID);
fclose("/students/students.txt");
Needs to be re-written as:
$file_handle = fopen("/students/students.txt", "w");
fwrite($file_handle, $content."\n".$SID);
fclose($file_handle);
You can see that fclose operates on file handles as well.
File Handle (as per php.net):
A file system pointer resource that is typically created using fopen().
Here are a couple of diagnostic functions that allow you to validate that a file exists and is readable. If it is a permission issue, it gives you the name of the user that needs permission.
function PrintMessage($text, $success = true)
{
print "$text";
if ($success)
print " [<font color=\"green\">Success</font>]<br />\n";
else
print(" [<font color=\"red\">Failure</font>]<br />\n");
}
function CheckReadable($filename)
{
if (realpath($filename) != "")
$filename = realpath($filename);
if (!file_exists($filename))
{
PrintMessage("'$filename' is missing or inaccessible by '" . get_current_user() . "'", false);
return false;
}
elseif (!is_readable($filename))
{
PrintMessage("'$filename' found but is not readable by '" . get_current_user() . "'", false);
return false;
}
else
PrintMessage("'$filename' found and is readable by '" . get_current_user() . "'", true);
return true;
}
I've re-written your code with (IMO) a cleaner and more efficient code:
<?php
$SID = "SOMETHING MYSTERIOUS";
setcookie("Student", $SID, time()+43200, "/");
$file = "/students/students.txt"; //is the full path correct?
$content = file_get_contents($file); //$content now contains /students/students.txt
$size = filesize($file); //do you still need this ?
echo $content;
file_put_contents($file, "\n".$SID, FILE_APPEND); //do you have write permissions ?
file_get_contents
file_get_contents() is the preferred way to read the contents of a
file into a string. It will use memory mapping techniques if supported
by your OS to enhance performance.
file_put_contents
This function is identical to calling fopen(), fwrite() and
fclose() successively to write data to a file. If filename does not
exist, the file is created. Otherwise, the existing file is
overwritten, unless the FILE_APPEND flag is set.
Notes:
Make sure the full path /students/students.txt is
correct.
Check if you've read/write permissions on /students/students.txt
Learn more about linux file/folder permissions or, if you don't access to the shell, how to change file or directory permissions via ftp
Try to do this:
fopen("students/students.txt", "r");
And check to permissions read the file.

file_get_contents returns false on existing readable file

Well, I'm starting to hate PHP. I have a file, which is perfectly readable (is_readable returns true), has 777 permission, is normally opened by fopen, but file_get_contents is returning false.
The code is following:
<?php
error_reporting(-1);
$handle = fopen("tres.txt","w+");
try{
$cnt = file_get_contents("/var/www/tres.txt");
}
catch(Exception $err){ echo $err->getMessage(); }
if ($handle) echo "Allright!", "<br />";
if ($cnt) echo "Good";
if(is_readable("/var/www/tres.txt")) echo " Is";
?>
And even though I turned on all error reporting options I knew, no errors are catched, and that drives me mad. Changing file path to "./tres.txt" of "tres.txt" has no effect either.
Where the problem may lie?
P.S. It's run on PHP5 and apache2.
fopen("tres.txt","w+"); truncates the file. Reading it right after that makes no sense.
$cnt is most likely not false but the empty string '' which is considered false in a boolean context.
if ($cnt !== false) echo "Good"; would probably output "Good".
You don't have to use fopen when using file_get_contents. Remove fopen.

What am I doing wrong? PHP script with nothing visibly wrong

<?php
$file = fopen("configuration.conf","w+");
$settings['LogEnabled'] = "true";
$settings['Pass'] = "pass";
$settings['ShowWarning'] = "true";
fwrite($file,serialize($settings));
$path = "configuration.conf";
$file2 = file_get_contents($path);
$settings2=unserialize($file2);
echo($settings2['LogsEnabled']);
?>
It ought to show "true" when run. Whats wrong?
I tried fread and fopen for $file2, but neither work.
EDIT: It does not throw an error.
The file has permissions 0740
Not sure if it matters, but you have 'LogEnabled' in the serialize section and 'LogsEnabled' in the unserialize section.
Could that 's' be throwing you off?
Flush (and preferably close the file), before reading its contents.
/* Write stuff to $file */
fflush($file);
fclose($file);
/* Read stuff from file */

file_get_contents with query string

i am trying to send email from php
i have one php file with all values & other php template file.
(both files are on same server)
i am using file_get_contents to get contents of php template file for example
$url="emil_form.php";
$a="uname";
if(($Content = file_get_contents($url. "?uname=".$a)) === false) {
$Content = "";
}
...... EMAIL Sending Code ..........
and here is code for emil_form.php (email template file)
Your Name is : <?php $_GET['uname']; ?>
so once i got data in $Content i can send it by email.
but i am getting error unable to open file....
what i want is pass data from original php file to template php file and what will be output of template stored in variable so i can send it by email.
how can do this ?
Thanks
The real problem would be that you try to read a local file with a http query string behind it. The file system don't understand this and looks for a file called "emil_form.php?uname=uname".
$_GET / $_POST / etc only works over a http connection.
Try to put a placeholder like "%%NAME%%" in your template and replace this after reading the template.
<?php
$url = "emil_form.php";
$a = "uname";
if(($Content = file_get_contents($url)) === false) {
$Content = "";
}
$Content = str_replace('%%NAME%%', $a, $Content);
// sending mail....
Template will look like this:
Your Name is: %%NAME%%
Here's an alternative solution...
Use the relative path or absolute path as suggested by "cballou" to read file.
But insted of wirting a php file use a simple text file put you message template in it replace <?php $_GET['uname']; ?> with something unique like %uname% (replacement keys).
Read the file content into a variable and replace the replacement keys with your variable like so,
$url = "/usr/local/path/to/email_form.txt";
$a = "uname";
if(($Content = file_get_contents($url)) === false) {
$Content = "";
}else{
$content = str_replace('%uname%', $a, $content);
}
$url = sprintf("%s://%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME']);
$content = file_get_contents($url."/file.php?test=".$test);
echo $content;
Please note that you had a filename error in $url which wss trying to load emil_form.php.
A secondary issue seems to be the path you are using for your call to $url. Try making it an full URL in order to properly parse the file, avoiding any templating you may otherwise have to do. The RTT would be slower but you wouldnt have to change any code. This would look like:
$url = 'http://www.mysite.com/email_form.php';
$a = "uname";
if(($Content = file_get_contents($url. "?uname=".$a)) === false) {
$Content = "";
}

Categories