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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.