Jump to content

Single or several lines from txt file


Mindaugas

Recommended Posts

And assuming the file will always fit into memory, try this simple solution -

 

<?php
$the_file = 'text.dat'; // what file to read
$lines = file($the_file); // read the file into an array

// example 1
$find_these = array(1); // the line(s) you want
foreach($find_these as $key){
$index = $key -1; // adjust to match actual index values (start at zero)
echo "Line: $key, $lines[$index]<br />";
}

// example 2
$find_these = array(1,2,3); // the line(s) you want
foreach($find_these as $key){
$index = $key -1; // adjust to match actual index values (start at zero)
echo "Line: $key, $lines[$index]<br />";
}
?>

And assuming the file will always fit into memory, try this simple solution -

 

<?php
$the_file = 'text.dat'; // what file to read
$lines = file($the_file); // read the file into an array

// example 1
$find_these = array(1); // the line(s) you want
foreach($find_these as $key){
$index = $key -1; // adjust to match actual index values (start at zero)
echo "Line: $key, $lines[$index]<br />";
}

// example 2
$find_these = array(1,2,3); // the line(s) you want
foreach($find_these as $key){
$index = $key -1; // adjust to match actual index values (start at zero)
echo "Line: $key, $lines[$index]<br />";
}
?>

 

Thx it`s working perfectly :)

why txt file is .dat not .txt ?

For example , simple chat and every message saves in file.txt, and i dont want that ppl could see it directly www.name.com/file.txt , just want when ppl come to chat they see only first 5 lines, it will be 5 newest messages.

I see. Well personally I keep any files that I don't want people to have access to outside of the document root folder, so that they aren't accessible via any uri other than internally on the server. I suppose you could use a .htaccess file to block certain file extensions from being access too

I added .htaccess file in my server, added :

<Files ~ "\.(txt)$">
  order allow,deny
  deny from all
</Files>

And now noone can view this file :)

 

 

p.s. sorry for two posts, maybe this info will be usefull for someone.

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.