Jump to content

Reading Text file.


manalnor

Recommended Posts

Hello friends,

 

i've an problem.

 

if i've an text file (hi.txt)

and want to open it within php file , i've write that code.

 

<textarea>
<?
$fn = "hi.txt"; // path name of text file
print htmlspecialchars(implode("",file($fn)));
?>
</textarea>

 

it will show the content of (hi.txt)

Now the problem  :confused: if i deleted the text file (hi.txt)

it will shows me stupid error

 

so can someone kindly rewrite that code to be more improved so that it act as following :-

 

if hi.txt is exist in the same path then it will show its content

if hi.txt is not exist or 0 byte .. then it won't show the textarea and give me for example an message

 

" THERE IS NO FILE "

 

thanks.

Link to comment
https://forums.phpfreaks.com/topic/207266-reading-text-file/
Share on other sites

thank you for your try but it won't work..here is another try from me.

 

<?
if () {
echo "<center> NO FILE </center>";
} else {
echo "<textarea rows='5' name='txt_content' cols='40'>";
$fn = "hi.txt";
print htmlspecialchars(implode("",file($fn)));
echo "</textarea>";
}
?>

 

the missing part here is (if) lol if what ?

it should be if hi.txt not exist ... how to write it in php  :shrug:

 

 

Link to comment
https://forums.phpfreaks.com/topic/207266-reading-text-file/#findComment-1083685
Share on other sites

I'm not really sure why you're using the file() function within the implode() function to pull the contents of a file and put it into a string.

 

The function file_get_contents() does this already.

 

<?php
$filename = '/path/to/hi.txt';

// Check to make sure the file exists
// If it does, then continue, otherwise produce an error
if (file_exists($filename)) {
  // Get the entire contents of the file as a string
  $contents = file_get_contents($filename);
  
  // Populate the text area with the contents of the file
  echo '<textarea>' . htmlspecialchars($contents) . '</textarea>'; // Is htmlspecialchars() strictly necessary?!
}
else {
  echo 'The file <strong>' . $filename . '</strong> does not exist.';
}
?>

Link to comment
https://forums.phpfreaks.com/topic/207266-reading-text-file/#findComment-1083701
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.