PHP fopen and is_dir issue - php

I have a small page to check if a network share is up. To do so, the user can had a share in a txt file (easier than touching the code itself) and then the page will read the text file and check if its online or not.
But the probleme is, it doesn't work has expected. looks like it work only when I have 1 line in the text file
<?php
$handle = fopen("share.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
if (is_dir($line)) {echo $line ."is up";}
else {echo $line ."is down";}
}
fclose($handle);
} else {
echo "No text file has been found";}
?>
and my share.txt contain
\\server1\folder
\\server2\folder
\\server3\folder
In that case, the page return only the last share as up and not all 3.
Any idea?
Thank you

It looks as if the line endings are not correctly recognised by PHP. In this case it should help to activate the
ini_set("auto_detect_line_endings", true);
so that PHP will also deal correctly with the "\r" line ending for example.
See this comment for more information.

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 ♥

PHP - echo and fgets weird characters

I'm trying to display the content of a text file on my website using PHP's fgets, but when I echo the lines in combination with something else (<br>, \n, ...) I get pretty weird characters.
Here's my code :
<?php
header('Content-Type: text/plain;charset=utf-8');
$handle = #fopen("test.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer."<br>";
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
Here is the content of test.txt :
1
2
3
4
5
... (6 - 18)
19
20
And here's what I get :
Result with <br>
If I use \n instead of <br>, I don't even get Chinese characters :
Result with \n
I think the issue comes from fgets(), because when I print only one line (without the loop) I get the same issue, but if replace $buffer by "1" (echo "1"."<br>";) I get the expected result.
EDIT
As suggested I modified the code to add header('Content-Type: text/plain;charset=utf-8'); at the beginning of the php file, and modified the output as well.
I found that the issue must be somewhere in the text file : I created a new one and the issue was gone.
I don't know the original encryption of the file because a friend gave it to me.
I'll update this answer if I find out exactly what was going on.
EDIT
I made a copy via TextEdit and when saving it the default encoding format was UTF-16, I guess that was the problem.
Working DEMO: http://phpfiddle.org/main/code/xrsk-a0uv
Text File:: http://m.uploadedit.com/ba3s/1500405331493.txt
Problem: at the Time of create text file it's select the encoding format is UTF-16. !! UTF-8 by default for nodepad,nodepad++,sublime etc.. !!
<?php
header('Content-Type: text/plain;charset=utf-8');
$handle = #fopen("http://m.uploadedit.com/ba3s/1500405331493.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer."</br>";
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
NOTE: Add header for charset-utf-8
header('Content-Type: text/plain;charset=utf-8');
OUTPUT Using With "\n"
OUTPUT Using With "</br>"

PHP - open external php file and display in browser

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

PEAR Crypt_Blowfish Error Encrypting MP3 File

So, call me crazy (I know you will) but this is only for learning purposes. I'm doing some exploring with php and using PEAR Crypt_Blowfish on a line-by-line read of an mp3 file. It's very server intensive and I'm seeing strange output. I was wondering if anyone had insight as to why:
<?php
include_once '/home/.../php/Crypt/Blowfish.php';
$bf = new Crypt_Blowfish('super');
$handle = #fopen("Judith_full.mp3", "r");
if ($handle) {
while (($buffer = fgets($handle, 1024)) !== false) {
echo $buffer;
echo '<br><br>ENCRYPTED: <br>';
echo $bf->encrypt($buffer).'<br><br>';
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
It's simply showing me the line, then the line encrypted... but part way through the page load I see text that is underlined:
....juMbLEDteXt_thenStartsUnderlinedJuMbLEDteXt_... // can not paste, cause it's encrypted garbage.
The page never full loads, just hangs. Also after the underlining it starts to ignore the <br>'s that are in there.
Thanks to anyone that takes the time.

Can I read a .TXT file with 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);
}

Categories