Reading a text file from directory - php

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

Related

PHP searching for a string in multiple files within a directory

Im only a begginer in PHP so Im really sorry if it is just a stupid question.I have a directory full of .txt files and I have written a code to find a specific string inside those files and echo the whole line :
<?php
$search = $_POST['search'];
$dir = 'C:\xampp\htdocs\myfiles\dbl';
$files = scandir($dir,1);
foreach ($files as $lines){
foreach($lines as $line)
{
if(strpos($line, $search) !== false)
echo $line;
}
}
?>
However,I keep getting this error : Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\myfiles\search.php on line 19
This error caused by fact that you actually didn't open file within 1-st loop. You must open each file before looping throw lines.
You can do it with two ways:
1) Using file_get_contents() function
2) Using some functions for work with files (fopen(), fclose(), etc)
Go here
$search = 'test';
$dir = 'C:\xampp5.6\htdocs';
$files = scandir($dir,1);
foreach ($files as $lines){
if(strlen($lines) > 3 && strpos($lines, '.txt') !== false){
$readfile = fopen('C:\xampp5.6\htdocs/'.$lines, 'r');
while(!feof($readfile)) {
$contents = fgets($readfile);
if(strpos($contents, $search) !== false)
echo $lines.'<br>';
}
fclose($readfile);
}
}
Use fopen() to read each file and then search for the string

Getting Error on fopen in 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;
?>

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

PHP not writing to file from one source

I have an issue I can't seem to find the solution for. I am trying to write to a flat text file. I have echoed all variables out on the screen, verified permissions for the user (www-data) and just for grins set everything in the whole folder to 777 - all to no avail. Worst part is I can call on the same function from another file and it writes. I can't see to find the common thread here.....
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
if (!$Handle = fopen($File, 'w')) {
return "Cannot open file ($File)";
exit;
}/*
if(!flock($Handle, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain file lock';
exit(-1);
}*/
if (fwrite($Handle, $NewContents) === FALSE) {
return "Cannot write to file ($File)";
exit;
}else{
return $NewContents;
}
}else{
return "<p align=\"center\">There was an issue saving your settings. Please try again. If the issue persists contact your provider.</p>";
}
}
Try with...
$Handle = fopen($File, 'w');
if ($Handle === false) {
die("Cannot open file ($File)");
}
$written = fwrite($Handle, $NewContents);
if ($written === false) {
die("Invalid arguments - could not write to file ($File)");
}
if ((strlen($NewContents) > 0) && ($written < strlen($NewContents))) {
die("There was a problem writing to $File - $written chars written");
}
fclose($Handle);
echo "Wrote $written bytes to $File\n"; // or log to a file
return $NewContents;
and also check for any problems in the error log. There should be something, assuming you've enabled error logging.
You need to check for number of characters written since in PHP fwrite behaves like this:
After having problems with fwrite() returning 0 in cases where one
would fully expect a return value of false, I took a look at the
source code for php's fwrite() itself. The function will only return
false if you pass in invalid arguments. Any other error, just as a
broken pipe or closed connection, will result in a return value of
less than strlen($string), in most cases 0.
Also, note that you might be writing to a file, but to a different file that you're expecting to write. Absolute paths might help with tracking this.
The final solution I ended up using for this:
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
return $NewContents;
}else{
return "<p align=\"center\">There was an issue saving your settings.</p>";
}
}
function WriteNewConfigToFile($File2WriteName, $ContentsForFile){
file_put_contents($File2WriteName, $ContentsForFile, LOCK_EX);
}
I did end up using absolute file paths and had to check the permissions on the files. I had to make sure the www-data user in Apache was able to write to the files and was also the user running the script.

php print filecontent with php-content

After checking for both fread and fopen with the search-command "php fread php code" and php fopen php code" without success I'm now turning to asking the question myself. (Over 300 pages with questions were a bit to steep to dig around in.)
I have a page where I get the content from external files. I got the index.php with the links which sends requests through the url (?links=home, for example) that is read from another file that looks through an array and finds the right file. All that works! But here is the tricky part:
On of the files includes a few strings of php-codes that won't do it's job but just hangs around in the view-source. Yes, you can see the commands in the source:code, but it won't anything I request. Not a single echo.
Here is some code that might explain things even better.
The code that gets the url-command:
<?php
function load_pages() {
if ($_GET['link'] != NULL) {
$link = $_GET['link'];
$links = array("hem" => "hem.php", "about" => "about.php", "blogg" => "blogg.php", "kontakta" => "kontakta.php");
foreach ($links as $key => $value) {
if ($key == $link) {
$file = "links/" . $value;
$fh = fopen($file, "r") or exit("Unable to open the file.");
$fileContent = fread($fh, filesize($file));
fclose($fh);
echo $fileContent;
}
}
} else {
$file = "links/hem.php";
$fh = fopen($file, "r") or exit("Unable to open the file.");
$fileContent = fread($fh, filesize($file));
fclose($fh);
echo $fileContent;
}
}
?>
The file that gets the command for the page I want to load:
<?php
include ("../include/functions.php");
connect();
?>
<h1>Blogg</h1>
<?php
if ($_GET['id'] == NULL) {
blogg_content();
} else {
blogg_link();
}
?>
<div id="blogg_menu">
<?php blogg_menu(); ?>
</div>
What comes out is: Blogg
That just doesn't do the trick, so what might I change to make it give me the blog-content and such? (The page is on Swedish, just to disclaim any typos about "Blogg".)
If those files contain PHP code that you want to be executed you need to include or require them rather than echoing the raw data.
Please see PHP's documentation on how to include code files.
EDIT
Kind of hard to tell from your description but if at all, you would have to do something like:
...
if ($key == $link) {
$file = "links/" . $value;
include_once $file;
}
...

Categories