Getting Error on fopen in PHP - php

I'm writing a simple text editor for a template, and I've gotten the opening, displaying, and editing part handled. Every time I try to save it though, it keeps giving me an error on the fopen() function.
I'm getting the files with this:
$dir = "./uploads/post-templates";
$files = scandir($dir);
while($files[0] == "." || $files[0] == "..") {
array_shift($files);
}
Then a simple loop handles displaying filenames in a select menu:
<?php foreach($files as $f) { echo "<option name='file' value=" . $f . " class='file'>" . $f . "</option>";}; ?>
Lastly it is all appended into the textarea using a short jQuery function. Alas, when it comes to executing the script to save the file, I get an error every single time. I've tried using relatives, absolutes, and http for the directory, and the filename and path are echoing properly each time.
///different file!!!!
$f = $_POST['file'];
$c = $_POST['content'];
$dir = "./uploads/post-templates/";
$file = $dir . $f;
echo $file;
$fo = fopen($file, "w") or die("opening error");
fwrite($fo, $c) or die("writing error");
fclose($f);

NOTE: For testing purposes only.
I wrote a test script and it was successful.
With the values that you have Mike, try using my script below with your present incoming values.
Plus this line gave me an error from your original code: fclose($f);
Error: when using fclose($f);
Warning: fclose() expects parameter 1 to be resource, string given in...
It should read as fclose($fo);
TEST CODE:
<?php
$f = "thefile.txt";
$c = "the content";
$dir = "./test/";
$file = $dir . "/" . $f;
echo $file; // echos the file name at this point
$fo = fopen($file, "w") or die("opening error");
fwrite($fo, $c) or die("writing error");
fclose($fo);
// shows the contents of the written file on screen
$contents = file_get_contents($file);
echo $contents;
?>

Related

Reading a text file from directory

I'm beginner in html and php. I trying to create a script that will open the directory, display all text files, open each of them for editing and save the changes to a file (all the script operation will be transferred to the html form). Unfortunately, after opening the directory and viewing the files, I have trouble reading their contents. Could someone tell me what I doing wrong ?
Thank for help
<?php
$path = "books/";
$books = opendir($path);
while (($book = readdir($books)) !== false)
{
echo $book;
foreach (glob("*.txt") as $readfile)
{
$readFile = fopen($book, "r") or die("Permission error");
echo fread($readFile, filesize($book));
fclose($readFile);
}
}
closedir();
?>
Server response:
...Atlas_chmur.txtDiuna.txt
I used the loop so that only .txt files were opened. Currently I have this:
<?php
$path = "books/";
$books = opendir($path);
while (($book = readdir($books)) !== false)
{
echo $book;
$readFile = fopen($book, "r") or die("Permission error");
echo fread($readFile, filesize($book));
fclose($readFile);
}
closedir();
?>
Now I'm getting an error when trying to read the files.
Server response:
. Warning: fopen (.): Failed to open stream: Permission denied in C: \ xampp \ htdocs \ BooksEditorForm \ index.php on line 9 Permission error
Try this code
$path = "blog/";
$books = opendir($path);
while (($book = readdir($books)) !== false)
{
if( substr($book, -4) === ".txt" )
{
$filePath = $path.$book;
$readFile = fopen($filePath, "r") or die("Permission error");
echo fread($readFile, filesize($filePath));
fclose($readFile);
}
}
closedir();
Let me explain it...
First, occasions where you need loop inside a loop are quite rare so if your code has them, analyze it because there's a big possibility that problem can be solved differently and more efficient.
Code: value of $book is string that contains filename so simple use of substr() function to check last 4 characters will tell us is it of "*.txt" format.
Other thing that is changed is filepath; $book contains it's name but your script is looking for a file from its own perspective so file path should be containing folder + filename.
And there's no need for closing PHP tags at the end unless you have something else following it that is not PHP (like HTML).
I have used the below code. It's working well.try this code
$files = scandir('books/');
if(count($files) > 0) {
foreach ($files as $key => $value) {
echo '<pre>'; print_r($value); echo '</pre>';
// to read files data
$readFileVar = fopen ($value, "r");
while ($filedata = fgets($readFileVar)) {
print_r($filedata);
}
}
}

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

php zip file not created despite no erros, no permission problems, no empty folders, no

Okay. Every file exists, is readable, and is writable. ZIP produces no errors, and outputs: "numfiles: 140 status:0".
the code reads a log, checks for specific text, then imports a number of images into a zip folder. everything runs great except the zip folder is always empty. I've read a lot of threads about this, and they all were resolved by changing permissions, modifying paths and checking for read/write/exist/errors. but... nothing has worked. whats up?
<?php
$file = fopen("log.log", "r") or exit("Unable to open file!");
$zip = new ZipArchive();
$filename = "E:/Web Sites/whatever/order_stream/images.zip";
$try_file = $zip->open($filename,ZIPARCHIVE::OVERWRITE);
if ($try_file !== true) {
exit("cannot open <$filename>\n");
}
while(!feof($file)) {
$line = fgets($file);
$results = explode(": ", $line);
if ($results[0] == "Copying" || $results[0] == "File already exists, overwriting") {
$file_name = substr($results[1],19);
$to_zip = "E:/Web Sites/whatever/catalog/pictures/".$file_name;
$to_zip = trim($to_zip);
if (file_exists($to_zip)) {
$zip->addFile($to_zip);
}
}
}
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
fclose($file);
?>
The ZipArchive::addFile() method accepts the path to the file as its first parameter, but not all paths are created equal. addFile() method silently rejects (bug?) the file and you never know what went wrong. An alternative approach would be:
// $zip->addFile($file);
$content = file_get_contents($file);
$zip->addFromString(pathinfo ( $file, PATHINFO_BASENAME), $content);
In addition to getting the code working, file_get_contents() also generates decent error messages if you made an error in the path. In this example
$file = $full_directory_path_ending_with_slash.$filename;
Since in the above question, you have the parts in your fingers, the code could simply become:
$content = file_get_contents($to_zip);
$zip->addFromString($filename, $content);

Parsing and Writing Files in PHP

I'm attempting to open a directory full of text files, and then read each file line-by-line, writing the information in each line to a new file. Within each text file in the directory I'm trying to iterate, the information is formed like:
JunkInfo/UserName_ID_Date_Location.Type
So I want to open every one of those text files and write a line to my new file in the form of:
UserName,ID,Date,Location,Type
Here's the code I've come up with so far:
<?php
$my_file = 'info.txt';
$writeFile = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file
$files = scandir('/../DirectoryToScan');
foreach($files as $file)
{
$handle = #fopen($file, "r");
if ($handle)
{
while (($buffer = fgets($handle, 4096)) !== false)
{
$data = explode("_", $buffer);
$username = explode("/", $data[0])[1];
$location = explode(".", $data[3])[0];
$type = explode(".", $data[3])[1];
$stringToWrite = $username . "," . $data[1] . "," . $data[2] . "," . $location . "," . $type;
fwrite($writeFile, $stringToWrite);
}
if (!feof($handle))
{
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
}
fclose($writeFile);
?>
So my problem is, this doesn't seem to work. I just never get anything happening -- the output file is never written and I'm not sure why.
There is one potential issue with the scandir() line:
$files = scandir('/../DirectoryToScan');
The path begins with a /, which means that it is looking in the root of the server. So, the directory it's trying to read is /DirectoryToScan. To fix it, you can just remove the leading /. Of course, this could be a sample path for this example and may not actually apply to reality, or maybe you really do have a directory in the root of your system named that - in these cases, feel free to ignore this bit =P.
The next thing is when you're using fopen() on the files you're iterating through. scandir() returns the name of the file, not the full path. You'll need to concat the directory name and the file each time:
$dir = '../DirectoryToScan/';
$files = scandir($dir);
foreach($files as $file) {
$handle = #fopen($dir . $file, "r");
I'm currently running an older version of PHP, so directly-accessing array indexes from return-functions, such as with explode("/", $data[0])[1], doesn't work for me (it was added in PHP 5.4).
Other than that, the rest of your code looks like it should work fine (minus any potential logic/data errors that I may have overlooked).

How to correctly use the PHP function 'fgets'?

I assume I'm using the fgets() wrong. I'm tring to open a PHP file and then try to match a line in that file with a variable I create. If the line does match then I want to write/insert PHP code to the file right below that line. Example:
function remove_admin(){
$findThis = '<tbody id="users" class="list:user user-list">';
$handle = #fopen("../../fns-control/users.php", "r"); // Open file form read.
if ($handle) {
while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 479); // Read a line.
if ($buffer == '<tbody id="users" class="list:user user-list">') // Check for string.
{
Now I want to write PHP code to the file, starting on line 480. How can I do that?
Useful information may be: IIS 6 and PHP 5.2.
Try this:
<?php
function remove_admin(){
$path = "../../fns-control/users.php";
$findThis = '<tbody id="users" class="list:user user-list">';
$phpCode = '<?php echo \'hello world\'; ?>';
#Import file to string
$f = file_get_contents($path);
#Add in the PHP code
$newfile = str_replace($findThis, $findThis . $phpCode, $f);
#Overwrite the existing file
$x = fopen($path, 'w');
fwrite($x, $newfile);
fclose($x);
}

Categories