Jump to content

Recommended Posts

I very new to php and all I am simply trying to do is read the contents of a text file and echo it out on the screen.

I have tried many things to see what I am doing wrong but it just simply isnt working for me. I know the server I am using has php enabled as well because I have tried a simple echo and it works fine.

 

This is the code I am currently using.

 

<?php

$file = fopen(file.txt", 'r');

$read = fread($file, '6')

echo $read;

?>

 

also, I have tried this.

 

<?php

$file = file_get_contents('file.txt');

echo $file;

?>

 

I have a file.txt on the server I am using in the same directory as index.php, I feel like this should be working but I get no result!

Alls I have in the text file is a statement that says "hello world".

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

<?php
$my_file = "file.txt";
if (file_exists($my_file)) {
$data = file($my_file);
$total = count($data);
echo "<br />Total lines: $total<br />";
foreach ($data as $line) {
echo "$line<br />";
}
} else {
echo "No file to display";
}
?>

Link to comment
https://forums.phpfreaks.com/topic/223097-readwrite-text-file/#findComment-1153427
Share on other sites

Really should read up some tutorials on read and write to text files, but as for a simple example to add a new line can do this.

 

If you keep visiting the new php file you made you will see it adding the new lines every refresh.

 

<?php
//read a file
$my_file = "file.txt";
if (file_exists($my_file)) {
$data = file($my_file);
$total = count($data);
echo "<br />Total lines: $total<br />";
foreach ($data as $line) {
echo "$line<br />";
}

//the a+ is add
$write = fopen($my_file, 'a+');
$message = "I just added this line\r\n";
fputs($write, $message);
fclose($write);

/*note the w, this will overwrite the entire contents
$write = fopen($my_file, 'w');
$message = "I just added this line\r\n";
fputs($write, $message);
fclose($write);
*/

} else {
echo "No file to display";
}
?>

Link to comment
https://forums.phpfreaks.com/topic/223097-readwrite-text-file/#findComment-1153436
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.