How to get text from txt file - php

I'm creating a html template with notification under nav bar , and admin can change that notification from the system the text of notification bar will be from notetxt file from the same location path where index.html is located i ave tried
<?php
foreach (glob("note.txt") as $filename) {
readfile($filename);
}
?>
and many other way but nothing happens it still stay blank

You are not echoing out the content of the textfile.
do it like this:
$myFile = "note.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
This will output your content of the file.

i'm using this code in pure html file
You can't use PHP functions in plain HTML file. MUST be written in a PHP file.
You have now in your code:
<span>
<!--?php
foreach (glob("note.txt") as $filename) {
$fileArr = file_get_contents($filename);
}
?-->
</span>
Try with the examples above in a proper PHP file... then must work.

you can use file_get_contents function,
try something like this :
<?php
foreach (glob("note.txt") as $filename) {
$fileArr = file_get_contents($filename);
}
?>

It's very simple use file_get_contents();
<?= file_exists('note.txt') ? file_get_contents("note.txt") : "file doesn't exists"; ?>
That is all what you need. file_get_contents() get the content of file and returns it. I've also checked if file exists because it may be your problem. Also make sure you have proper rights to read the file(CHMOD) and file is not empty.

Related

Problem in reading files with php fopen and in making file manager

I am trying to make a file manager with php , so when I open it in browser it would give a list of the current directory and the file would be clickable using the anchor tag in html (which I have done so far) , and when the file is clicked , it would open it in the text mode and shows whatever the source code inside the file is.
I am facing two problems which I couldn't figure out
Problem #1:
The first problem is that I want my file manager to read any source code weather its an image or pdf , just like the tinyfilemanager that I found here this master piece can read any file, even if you open an image with a notepad and insert some php code at the very end of the file it will read render that too, so here's my source code:
<?php
function list_all_files($directory){
//opening the dir
if($handle=opendir($directory.'/')){
echo "looking inside '$directory'"."<br>";
}
while($file=readdir($handle)){
//listing all the directories without ".." (dots)
if($file!='.'&&$file!='..') {
echo ''.$file.'<br>';
} //if ends here
} //while loop endds here
} //list_all_files ends here
function read_file($file)
{
$handle = fopen($file, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo($line);
}
fclose($handle);
} else {
echo "error opening the file";
}
}
//main function
if(!isset($_GET['dir'])) {
$dir='images';
}else{
$dir=$_GET['dir'];
}
list_all_files($dir);
if(isset($_GET['read'])){
$file1 = $_GET['read'];
read_file($file1);
}
?>
the above program I made can also read files code but when I click on any PHP file that contains an html code, it just displays it rather than giving its source code in text mode, image below:
and not only this, if I put some php code at the very end of the image file using a notepad it wouldn't display it. check this:
I did a lot of research on why my code isn't working while the tinyFilemanager is perfect with any of the above mention cases , and I found that the whenever I execute the page file via browser it by default uses this
header("Content-Type: text/html");
so If I wanted to do what I wanted , then I would have to use this:
header("Content-Type: text/x-php");
which covers both of the above cases, but leads to the 2nd problem.
Problem #2:
<?php
function list_all_files($directory){
//opening the dir
if($handle=opendir($directory.'/')){
echo "looking inside '$directory'"."<br>";
}
while($file=readdir($handle)){
//listing all the directories without ".." (dots)
if($file!='.'&&$file!='..') {
echo ''.$file.'<br>';
} //if ends here
} //while loop endds here
} //list_all_files ends here
function read_file($file)
{
$handle = fopen($file, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo($line);
}
fclose($handle);
} else {
echo "error opening the file";
}
}
//main function
if(!isset($_GET['dir'])) {
$dir=getcwd();
}else{
$dir=$_GET['dir'];
}
//listing all the directories and files in text/html format so that our anchor tag would be available.
ob_start();
header('Content-Type: text/html; charset=UTF-8');
list_all_files($dir);
ob_end_flush();
if(isset($_GET['read'])){
//changing the header to text/php-x so that the php code in any jpg file can be viewed clearly
ob_clean();
header('Content-Type: text/x-php; charset=UTF-8');
ob_start();
$file1 = $_GET['read'];
read_file($file1);
ob_end_flush();
}
?>
The above codes works perfectly fine, but there is this one problem. since its content-type is not text/html anymore, it wouldn't display the html content on the web page. which is good but bad at the same time because then I wouldn't get the list of directory in the anchor tag form, because I thought ob_start and ob_end_flush(). if I use these two, it would just solve the problem by creating a buffer for each of the function separately and executes it. so when it executes it the above function would be render with the content-type text/html and would show the directory listing with anchor tag, and the 2nd would just be in text/x-php which would solve the above two cases, but I was soooooo wrong.
With the grace and help of God , and suggestion from kikoSoftware in the Comments , the Problem is solved, there's a function name show_source(); ,which takes two arguement , the 2nd argument however is optional , hence we don't need to do filing or send a content-type response with the header() function , we can just use that function , source codes are below.
<?php
function list_all_files($directory){
//opening the dir
if($handle=opendir($directory.'/')){
echo "looking inside '$directory'"."<br>";
}
while($file=readdir($handle)){
//listing all the directories without ".." (dots)
if($file!='.'&&$file!='..') {
echo ''.$file.'<br>';
} //if ends here
} //while loop endds here
} //list_all_files ends here
function read_file($file)
{
$handle = fopen($file, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo($line);
}
fclose($handle);
} else {
echo "error opening the file";
}
}
//main function
if(!isset($_GET['dir'])) {
$dir=getcwd();
}else{
$dir=$_GET['dir'];
}
//listing all the directories and files in text/html format so that our anchor tag would be available.
list_all_files($dir);
if(isset($_GET['read'])){
//changing the header to text/php-x so that the php code in any jpg file can be viewed clearly
$file1 = $_GET['read'];
show_source($file1);
}
?>
appreciate ya guys for helping out ♥

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

Display remote text file on php page

I'm using this code now to display a text file on a php/html page.
<?php
foreach (glob("example.txt") as $filename) {
echo nl2br(file_get_contents($filename));
echo "<br></br>";
}
?>
I'm looking for a way to display the example.txt file from another server with URI.
Something like this: http://address.com/dir/example.txt
Is there a simple way to do this?
(I would use an iframe but it's not possible to style the text without Java or JQuery).
You could just use
file_get_contents('http://address.com/dir/example.txt');
You code is totally wrong
foreach (glob("example.txt") as $filename) {
^------------------------- searching for a file
They can only one example.txt file in a folder at a time except you want to get all text files should should be like this in the first place
foreach (glob("*.txt") as $filename) {
If that is not the case the code would work for both remote and local file
error_reporting(E_ALL);
ini_set("display_errors", "on");
$fileName = "example.txt" ; // or http://oursite.com/example.txt
echo nl2br(file_get_contents($fileName));
echo "<br></br>";
You will have to use CURL to fetch the content of the file first and then display it.
Another option is to use iframes and set the target of iframe to the desired text file.
Yet another option is to use ajax to fetch the content from client end as suggested in comment.
Check fopen() / fread() and your available transport wrappers.
For normal length text file you can use:
<?PHP
$file = fopen("http://www.xyz.com/textfile.txt", "rb");
$output = fread($file, 8192);
fclose($file);
echo($output);
echo "<br>";
?>
For longer files:
<?PHP
$file = fopen("http://www.xyz.com/textfile.txt", "rb");
$output = '';
while (!feof($file)) {
$output .= fread($file, 8192);
}
fclose($file);
echo($output);
echo "<br>";
?>
It will prevent packet exceed issues in longer files by concatenating the file together in several groupings using while loop

Why code stops working after this function?

I have some other functions and a html page call after this simple function, but they dont run after this.
function page($name){
$content =<<<eol
<?php
PAGE CONTENT
?>
eol;
$file = "./search/$name.php";
$open = fopen($file, "w");
fwrite($open, $content);
fclose($open);
}
function works itself, but causes exiting code.
<?php
function page($name){
$content = '<?php PAGE CONTENT ?>';
$file = "./search/$name.php";
$open = fopen($file, "w");
fwrite($open, $content);
fclose($open);
}
page('file1.txt');
?>
Just see if that works, It could be something to do with your HEREDOC syntax (maybe the space before the eol;).
I disagree with Chief17
The only right thing is writing to file.
This code
<?php
PAGE CONTENT
?>
what supposed to do?
Did you mix up ???
may be it should be like this
?>
PAGE CONTENT
<?php
editing after your edit
You break the php like this why you need this anyway?

Save website sourecode to file via php

Hi I wan to save the sourecode of http://stats.pingdom.com/w984f0uw0rey to some directory in my website
<?php
if(!copy("http://stats.pingdom.com/w984f0uw0rey", "stats.html"))
{
echo("failed to copy file");
}
;
?>
but this does not work either for me:
<?php
$homepage = file_get_contents('http://stats.pingdom.com/w984f0uw0rey');
echo $homepage;
?>
But I cannot figure how to do it!
thanks
use
<?
file_put_contents('w984f0uw0rey.html', file_get_contents('http://stats.pingdom.com/w984f0uw0rey'));
?>
be sure that the script has write privileges to the current directory
Use file_get_contents().
The best variant you can do in PHP is to use stream_copy_to_stream:
$url = 'http://www.example.com/file.zip';
$file = "/downloads/stats.html";
$src = fopen($url, 'r');
$dest = fopen($file, 'w');
echo stream_copy_to_stream($src, $dest) . " bytes copied.\n";
If you need to add HTTP options like headers, use context options with the fopen call. See as well this similar answer which shows how. It's likely you need to set a user-agent and things so that the other website's server believes you're a browser.

Categories