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

<?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 */

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.

Developing a text editor with PHP

I've started a small project trying to make an online text editor, it WAS going well until the system started overwriting files and adding spaces in unnecessarily. I have one file called editor.php where all the file loading, saving and editing is done.
So this is the opening/closing for the files:
<?php
if(isset($_POST['new'])){
$filer = substr(md5(microtime()),rand(0,26),6);
$file_create = $filer.".txt";
$handle = fopen("files/".$file_create,"w");
fclose($handle);
header("Location: editor.php?e=".$filer);
}
$file = $_GET['e'];
$file = basename($file);
$filename = "files/".$file.".txt";
$file_get = file_get_contents($filename);
if(isset($_POST['save'])){
file_put_contents($filename, $_POST['text']);
}
?>
further down the page I have this in a <textarea> tag:
<?php
echo $file_content;
?>
This uses the string from the file_get_contents();
But when I save, nothing happens, in fact it erases the file, when I load a file there are eight spaces but nothing else.
I know there is another way to do this with fopen() and if someone could give me a method to use that, it would be much appreciated.
You have to verify if the $_POST['text'] actually has a content in it.
if(isset($_GET['e'])){
$file = $_GET['e'];
$file = basename($file);
$filename = $_SERVER['DOCUMENT_ROOT']."/files/".$file.".txt";
$file_get = file_get_contents($filename);
if(isset($_POST['save'])){
if(!empty($_POST['text']) && isset($_POST['text']))
{
$length = strlen($_POST['text']);
if($length > 0)
file_put_contents($filename, trim($_POST['text']));
else
die("No content");
}
}
}
ALso check if the file exists and its writable. You can use chmod,mkdir and file_exists functions.
Have a look at PHP's file modes: http://php.net/manual/en/function.fopen.php
If you are opening all your files using fopen() in w mode then your files are being truncated as they are opened. This is how w mode operates. Try using a+ or c+ modes with fopen().
EDIT
Also, the file_put_contents() will also overwrite file contents unless you sett the FILE_APPEND flag, e.g. file_put_contents($file, $data, FILE_APPEND).

PHP fwrite writing empty file

I'm trying to make this save a file and it creates the file, but it's always empty. This is the code for it:
<?php
$code = htmlentities($_POST['code']);
$i = 0;
$path = 'files/';
$file_name = '';
while(true) {
if (file_exists($path . strval($i) . '.txt')) {
$i++;
} else {
$name = strval($i);
$file_name = $path . $name . '.txt';
break;
}
}
fopen($file_name, 'w');
fwrite($file_name, $code);
fclose($file_name);
header("location: index.php?file=$i");
?>
I echoed out $code to make sure it wasn't empty, and it wasn't. I also tried replacing
fwrite($file_name, $code);
with this:
fwrite($file_name, 'Test');
and it was still empty. I have written to files a couple of times before in PHP, but I'm still really new to PHP and I have no idea whats wrong. Could someone tell me what I'm doing wrong or how to fix this? Thanks
Reading/Writing to/from a file or stream requires a resource handle:
$resource = fopen($file_name, 'w');
fwrite($resource, $code);
fclose($resource);
The resource handle $resource is essentially a pointer to the open file/stream resource. You interact with the created resource handle, not the string representation of the file name.
This concept also exists with cURL as well. This is a common practice in PHP, especially since PHP didn't have support for OOP when these methods came to be.
Take a look of the samples on php.net

Manage several files in PHP

I'm testing php because I'm a freshman in this matter. I put my php code in a free server, they let me do my own index.php, manage some php variables (like register_globals, magic_quotes_gpc etc. I left them as default), but apparently I can handle not more than one file in a php code, for example:
<?php
//--------Updating Data-------------
$cdc = intval($_POST['cantidadDeCapitulos']);
$toWrite = array('ctot' => $cdc);
for($i=1;$i<$cdc+1;$i += 1){
$toWrite["cap".$i] = $_POST['numdeCap'.$i];
}//---------------------------------
$datos = file_get_contents("myfile.json.");
$toWrite = json_encode( $toWrite );
//Open a file in write mode
$fp = fopen("myfile2.json", "w");
if(fwrite($fp, "$toWrite")) {
echo "&verify=success&";
} else {
echo "&verify=fail&";
}
fclose($fp);
?>
If I comment out the line $datos = file_get_contents("myfile.json."); it's alright!, something is written in myfile2.json but if it is uncommented, the data is not updated. Both files have permission 666 and they are in the same directory i.e., /root.
$datos = file_get_contents("myfile.json.");
Seems like a typo has occurred. Take off the final dot from your file. I mean, change the line to:
$datos = file_get_contents("myfile.json");
try this:
<?php
$file = 'myfile.json';
// Open the file to get existing content
$current = file_get_contents($file);
// Write the contents back to the file
file_put_contents($file, $current);
?>

Categories