I have the below php file. When i try to run this file, nothing is getting displayed
<html>
<body>
<?php
$myfile = fopen("1.txt", "a+") or die("Unable to open file!");
echo fgetss($myfile,149,"<td>,</td>");
fclose($myfile);
?>
</body>
The 149th line of my 1. txt file is
<td>Mfg of Textile Readymade Garments</td>
According to documentation, fgetss will read length bytes for the current line. So fgetss($myfile,149,"<td>,</td>") will read 149 bytes on the first line.
You could try (quick and dirty):
<?php
$myfile = fopen("1.txt", "r") or die("Unable to open file!");
for ($i = 0; $i < 149; $i++) fgets($myfile);
echo fgetss($myfile, 4096, "<td>,</td>");
fclose($myfile);
?>
Side note, you want to read file, so replace a+ with r in your fopen call
The function fgetss() the second parameter informs the amount of bytes that will be returned in the line and not the specific line that you want to pick up.
One way to get a specific line from a file, is by using a function:
<?php
function get_line($arq,$linha)
{
$arquivo = file($arq);
$y = $linha - 1;
$x = print $arquivo[$y];
return $x;
}
get_line("1.txt",149);
?>
Related
I'm creating a code to display the name of a server with enterprise rules, So for don't use Mysql i try a new things (for me) use php to read and rewrite files, that work perfectly for one part of my code and work perfectly but for the second he only read one time, and when i do a f5 the code don't increment.
He rewrite correctly because my file was at 000 and become 001
I try to use file() but he is disable since 7.0, try to use SplFileObject but it don't want to display anything and i don't like it because i understand nothing when i use it so i come back to fopen(),fread() and fwrite() and that don't work. I'm inPHP 7.3.1
The code that works :
<?php
if ( isset($_POST) AND !empty($_POST) ) {
$nom = "./config.txt";
$filez = fopen($nom, "r") or die("Unable to open file!");
$i = fread($filez,filesize($nom));
$year = getdate();
$idy = substr($year[year], 2);
$fichier = fopen("./resultsrv.txt", "w") or die("Unable to write file!");
for ($z; $z<$_POST['nbr']+1 ; $z++) {
$id = sprintf("%04d", $i+$z);
$nome = $_POST['type'].$_POST['OS'].$idy.$id."<br>" ;
echo $nome;
$nomewout = str_replace("<br>", ";", $nome);
fwrite($fichier,$nomewout);
}
$handle = fopen("./config.txt", "w") or die("Unable to write file!");
fwrite($handle,$id);
fclose($fichier);
fclose($handle);
}
?>
and the one that doesn't work because he doesn't increment :
<?php
if ( isset($_POST) AND !empty($_POST) ) {
$fileName = 'confchass.txt';
$read = fopen($fileName,"r");
$fn = fopen($fileName,"w+");
$i = fread($read,filesize($fileName));
$id = sprintf("%03d", $i+1);
echo "<div align='center'><h1>Le Chassis</h1>";
echo $_POST['Marque'].$_POST['DC'].$id;
echo "</div>";
fwrite($fn,$id);
fclose($read);
fclose($fn);
}
?>
I want he output a thing like XXXXXX001 and when i refresh or do a new POST from my forms he output XXXXXX002 and XXXXXX003 .... But he actualy output only XXXXXX001
The problem is that you open the file for reading and then for writing. But from the manual...
'w+' Open for reading and writing; place the file pointer at the
beginning of the file and truncate the file to zero length. If the
file does not exist, attempt to create it.
So this will blank out the file before you read the value from it.
To fix this (using your current method, you should read the value, then open it for writing and write the new value...
$read = fopen($fileName,"r");
$i = fread($read,filesize($fileName));
fclose($read);
$id = sprintf("%03d", $i+1);
echo "<div align='center'><h1>Le Chassis</h1>";
echo $id;
echo "</div>";
$fn = fopen($fileName,"w+");
fwrite($fn,$id);
fclose($fn);
You could shorten this by using file_get_contents() and file_put_contents().
I want to save a web page to a text file automatically or at least every second. So I wrote a PHP file like that :
<?php
$homepage = file_get_contents('www.example.com');
echo $homepage;
$myfile = fopen("file.txt", "w") or die("Unable to open file!");
while(true) {
fwrite($myfile, $homepage);
}
fclose($myfile);
?>
But it did not work
The file will not be written until the while loop will stop.
Can someone help me with that ? I need the PHP to run all the time or at least for a few minute. How can I do that ?
I'd go for something like this (not tested though)
<?php
header("Refresh:30"); // The page will be refreshed every 30 seconds
// To avoid max_execution_time errors
$myfile = "file.txt";
for ($i=0; $i < 30; $i++) {
$homepage = file_get_contents("http://www.example.com");
echo $homepage;
file_put_contents($myfile, $homepage);
sleep(1); // Do it every second
}
If a second is too much time, you could use usleep instead
That's because you don't close the file in the loop. And you should add some delay too. Change it to this:
<?php
$homepage = file_get_contents('www.example.com');
echo $homepage;
while(true) {
$myfile = fopen("file.txt", "w") or die("Unable to open file!");
fwrite($myfile, $homepage);
fclose($myfile);
sleep(1);
}
?>
Note that if you're running this on a webserver, it will exceed the time limit.
First off, maybe you should consider using sleep inside your loop to minimise performance impact. After every write you should invoke flush to persist data onto disk. There is also a risk of overloading target site in a form of DOS attack, so you should be mindful of the consequences.
This is not tested but should word... But honestly your better of using Ajax with a timer to do this.
header("Refresh:60");
function writeToPage($page,$file){
$content = file_get_contents($page);
file_put_contents($file,$content);
}
$page = "www.example.com";
$file = "file.txt";
$write = true;
while( $write === true ) {
sleep(5);
writeToPage($page,$file);
}
<?php
$seatsArray = array();
$myFile = fopen("seats.txt", "w") or die("Unable to Open File!");
if(filesize("seats.txt") == 0) {
for($x = 0; $x < 10; $x++) {
fwrite($myFile, "0\n");
}
}
$seatsArray = file("seats.txt", FILE_IGNORE_NEW_LINES);
fclose($myFile);
?>
var array = [<?php echo '"'.implode('","', $seatsArray ).'"' ?>];
This PHP code is at the top of my script section in head. The seats.txt file is full of zeroes initially to represent vacant seats on a flight and through other functions, the seats will fill up (represented by 1s). I can get the 1s to write to the file but as soon as I reload the page, the if-statement seems to execute regardless of its condition being false and resets everything back to zero.
The reason is due to this w mode
w- (Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist)
So every time your file gets blank
Use a or a+ if you want to append at the right of file or r+ if you want to right from starting
I am not sure whether I understand you correctly, but I think you only want to write the file if it does not exist:
<?php
$seatsArray = array();
if(!file_exists("seats.txt") || filesize("seats.txt") == 0) {
$myFile = fopen("seats.txt", "w") or die("Unable to Open File!");
for($x = 0; $x < 10; $x++) {
fwrite($myFile, "0\n");
}
fclose($myFile);
}
$seatsArray = file("seats.txt", FILE_IGNORE_NEW_LINES);
?>
var array = [<?php echo '"'.implode('","', $seatsArray ).'"' ?>];
Additionally, I would recommend putting the filename into a constant, which reduces the risk of typos (so PHP will complain, if it encounters an undefined constant in case of a typo).
I'm trying to read a specific line from a text file using php.
Here's the text file:
foo
foo2
How would I get the content of the second line using php?
This returns the first line:
<?php
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
..but I need the second.
Any help would be greatly appreciated
$myFile = "4-24-11.txt";
$lines = file($myFile);//file in to an array
echo $lines[1]; //line 2
file — Reads entire file into an array
omg I'm lacking 7 rep to make comments. This is #Raptor's & #Tomm's comment, since this question still shows up way high in google serps.
He's exactly right. For small files file($file); is perfectly fine. For large files it's total overkill b/c php arrays eat memory like crazy.
I just ran a tiny test with a *.csv with a file size of ~67mb (1,000,000 lines):
$t = -microtime(1);
$file = '../data/1000k.csv';
$lines = file($file);
echo $lines[999999]
."\n".(memory_get_peak_usage(1)/1024/1024)
."\n".($t+microtime(1));
//227.5
//0.22701287269592
//Process finished with exit code 0
And since noone mentioned it yet, I gave the SplFileObject a try, which I actually just recently discovered for myself.
$t = -microtime(1);
$file = '../data/1000k.csv';
$spl = new SplFileObject($file);
$spl->seek(999999);
echo $spl->current()
."\n".(memory_get_peak_usage(1)/1024/1024)
."\n".($t+microtime(1));
//0.5
//0.11500692367554
//Process finished with exit code 0
This was on my Win7 desktop so it's not representative for production environment, but still ... quite the difference.
If you wanted to do it that way...
$line = 0;
while (($buffer = fgets($fh)) !== FALSE) {
if ($line == 1) {
// This is the second line.
break;
}
$line++;
}
Alternatively, open it with file() and subscript the line with [1].
I would use the SplFileObject class...
$file = new SplFileObject("filename");
if (!$file->eof()) {
$file->seek($lineNumber);
$contents = $file->current(); // $contents would hold the data from line x
}
you can use the following to get all the lines in the file
$handle = #fopen('test.txt', "r");
if ($handle) {
while (!feof($handle)) {
$lines[] = fgets($handle, 4096);
}
fclose($handle);
}
print_r($lines);
and $lines[1] for your second line
$myFile = "4-21-11.txt";
$fh = fopen($myFile, 'r');
while(!feof($fh))
{
$data[] = fgets($fh);
//Do whatever you want with the data in here
//This feeds the file into an array line by line
}
fclose($fh);
This question is quite old by now, but for anyone dealing with very large files, here is a solution that does not involve reading every preceding line. This was also the only solution that worked in my case for a file with ~160 million lines.
<?php
function rand_line($fileName) {
do{
$fileSize=filesize($fileName);
$fp = fopen($fileName, 'r');
fseek($fp, rand(0, $fileSize));
$data = fread($fp, 4096); // assumes lines are < 4096 characters
fclose($fp);
$a = explode("\n",$data);
}while(count($a)<2);
return $a[1];
}
echo rand_line("file.txt"); // change file name
?>
It works by opening the file without reading anything, then moving the pointer instantly to a random position, reading up to 4096 characters from that point, then grabbing the first complete line from that data.
If you use PHP on Linux, you may try the following to read text for example between 74th and 159th lines:
$text = shell_exec("sed -n '74,159p' path/to/file.log");
This solution is good if your file is large.
You have to loop the file till end of file.
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
Use stream_get_line: stream_get_line — Gets line from stream resource up to a given delimiter
Source: http://php.net/manual/en/function.stream-get-line.php
You could try looping until the line you want, not the EOF, and resetting the variable to the line each time (not adding to it). In your case, the 2nd line is the EOF. (A for loop is probably more appropriate in my code below).
This way the entire file is not in the memory; the drawback is it takes time to go through the file up to the point you want.
<?php
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$i = 0;
while ($i < 2)
{
$theData = fgets($fh);
$i++
}
fclose($fh);
echo $theData;
?>
I like daggett answer but there is another solution you can get try if your file is not big enough.
$file = __FILE__; // Let's take the current file just as an example.
$start_line = __LINE__ -1; // The same with the line what we look for. Take the line number where $line variable is declared as the start.
$lines_to_display = 5; // The number of lines to display. Displays only the $start_line if set to 1. If $lines_to_display argument is omitted displays all lines starting from the $start_line.
echo implode('', array_slice(file($file), $start_line, lines_to_display));
I searched for a one line solution to read specific line from a file.
Here my solution:
echo file('dayInt.txt')[1]
I have:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
but it overwrites the beginning of the file. How do I make it insert?
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?
To insert text without over-writing the beginning of the file, you'll have to open it for appending (a+ rather than r+)
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
If you're trying to write to the start of the file, you'll have to read in the file contents (see file_get_contents) first, then write your new string followed by file contents to the output file.
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
The above approach will work with small files, but you may run into memory limits trying to read a large file in using file_get_conents. In this case, consider using rewind($file), which sets the file position indicator for handle to the beginning of the file stream.
Note when using rewind(), not to open the file with the a (or a+) options, as:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
A working example for inserting in the middle of a file stream without overwriting, and without having to load the whole thing into a variable/memory:
function finsert($handle, $string, $bufferSize = 16384) {
$insertionPoint = ftell($handle);
// Create a temp file to stream into
$tempPath = tempnam(sys_get_temp_dir(), "file-chainer");
$lastPartHandle = fopen($tempPath, "w+");
// Read in everything from the insertion point and forward
while (!feof($handle)) {
fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);
}
// Rewind to the insertion point
fseek($handle, $insertionPoint);
// Rewind the temporary stream
rewind($lastPartHandle);
// Write back everything starting with the string to insert
fwrite($handle, $string);
while (!feof($lastPartHandle)) {
fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);
}
// Close the last part handle and delete it
fclose($lastPartHandle);
unlink($tempPath);
// Re-set pointer
fseek($handle, $insertionPoint + strlen($string));
}
$handle = fopen("file.txt", "w+");
fwrite($handle, "foobar");
rewind($handle);
finsert($handle, "baz");
// File stream is now: bazfoobar
Composer lib for it can be found here
You get the same opening the file for appending
<?php
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
If you want to put your text at the beginning of the file, you'd have to read the file contents first like:
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
$existingText = file_get_contents($file);
fwrite($file, $existingText . $_POST["lastname"]."\n");
}
fclose($file);
?>