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;
}
...
Related
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 ♥
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);
}
}
}
I'm trying to make my PHP script open more than 1 text document and to read them.
My current script is as follows:
<?php
//$searchthis = "ignore this";
$matches = array();
$FileW = fopen('result.txt', 'w');
$handle = #fopen("textfile1.txt", "r");
ini_set('memory_limit', '-1');
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(stripos($buffer, $_POST["search"]) !== FALSE)
$matches[] = $buffer;
}
fwrite($FileW, print_r($matches, TRUE));
fclose($handle);
}
?>
I'm trying to fopen like a bunch of files, maybe like 8 of them or less.
How would I open, and read all these files?
Any help is GREATLY appreciated!
Program defensively, check the return's from functions to ensure you are not making incorrect assumptions about your code.
There is a function in PHP to read the file and buffer it:
enter link description here
I don't know why you would want to open a lot of files, it surely will use a lot of memory, anyway, you could use the file_get_contents function with a foreach:
$files = array("textfile1.txt", "textfile2.txt", "textfile3.txt");
$data = "";
foreach ($files as $file) {
$data .= #file_get_contents($file);
}
echo $data;
There is a function in php called file which reads entire file into an array.
<?php
// "file" function creates array with each line being 1 value to an array
$fileOne = file('fileOne.txt');
$fileTwo = file('fileTwo.txt');
// Print an array or do all array magic with $fileOne and $fileTwo
foreach($fileOne as $fo) {
echo $fo;
}
foreach($fileTwo as $ft) {
$echo $ft;
}
?>
Read more about : file function ion php
I need a php script that will open an external php file (from the same server folder), go through it line by line, and then normally display the page in the browser, as it would by just opening the external php page directly.
I need to open the external file line by line, so I can do some processing on the content of the file before showing it.
My current code is:
<?php
$handle = fopen("test.php", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line here, and change if needed
echo "$line\n";
}
fclose($handle);
}
else {
// error opening the file.
}
?>
This works, and the page is displayed, but any php code in the original external file is not honored - it is written out as text, and not rendered by the browser.
I need the external file to fully display, just as it would if I opened the file (in this case "test.php") by itself.
Other questions I have seen on SO deal with opening or displaying a full file at once, but I need to loop through my file and do some processing on the contents first, so need to evaluate it line by line.
Any ideas would be appreciated.
Thanks
I would save the changes to a temporary file, and then include it.
<?php
$handle = fopen("test.php", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line here, and change if needed
$newCode .= "$line\n";
}
fclose($handle);
}
else {
// error opening the file.
}
// temporary file name
$temp_file = tempnam(sys_get_temp_dir(), 'myfile').".php";
// save modified code
file_put_contents($temp_file, $newCode);
// include modified code
include $temp_file;
// delete file
unlink($temp_file);
?>
Retrieve the content, process it, keep it in memory then eval() it:
<?php
$newCode = "";
$handle = fopen("test.php", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line here, and change if needed
//$line = myLineProcess($line);
$newCode .= "$line\n";
}
fclose($handle);
}
else {
// error opening the file.
}
//run the code
eval('?>'.$newCode.'<?php;');
?>
As I start the process of writing my site in PHP and MySQL, one of the first PHP scripts I've written is a script to initialize my database. Drop/create the database. Drop/create each of the tables. Then load the tables from literals in the script.
That's all working fine! Whoohoo :-)
But I would prefer to read the data from files rather than hard-code them in the PHP script.
I have a couple of books on PHP, but they're all oriented toward web development using MySQL. I can't find anything about reading and writing to ordinary files.
Yes, I know there's a gazillion questions here on stackoverflow about reading TXT files, but when I look at each one, they're for C or C# or VB or Perl. I'm beginning to think that PHP just can't read files :-(
All I need is a brief PHP example of how to open a TXT file on the server, read it sequentially, display the data on the screen, and close the file, as in this pseudo-code:
program readfile;
handle = open('myfile.txt');
data = read (handle);
while (not eof (handle)) begin
display data;
data = read (handle);
end;
close (handle);
end;
I will also need to write files on the server when I get to the part of my site where people upload avatars, and save them as JPG or GIF files. But that's for later.
Thanks!
From the PHP manual for fread():
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
EDIT
per the comment, you can read a file line by line with fgets()
<?php
$handle = #fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
All I need is a brief PHP example of how to open a TXT file on the server, read it sequentially, display the data on the screen, and close the file, as in this pseudo-code:
echo file_get_contents('/path/to/file.txt');
Yes that brief, see file_get_contents, you normally don't need a loop:
$file = new SPLFileObject('/path/to/file.txt');
foreach($file as $line) {
echo $line;
}
Well, since you're asking about resources on the subject, there's a whole book on it in the PHP.net docs.
A basic example:
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
Why you not read php documentation about fopen
$file = fopen("source/file.txt","r");
if(!file)
{
echo("ERROR:cant open file");
}
else
{
$buff = fread ($file,filesize("source/file.txt"));
print $buff;
}
file_get_contents does all that for you and returns the text file in a string :)
You want to read line by line? Use fgets.
$handle = #fopen("myfile.txt", "r");
if ($handle) {
while (($content = fgets($handle, 4096)) !== false) {
//echo $content;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}