I need a php script that will open an external php file (from the same server folder), go through it line by line, and then normally display the page in the browser, as it would by just opening the external php page directly.
I need to open the external file line by line, so I can do some processing on the content of the file before showing it.
My current code is:
<?php
$handle = fopen("test.php", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line here, and change if needed
echo "$line\n";
}
fclose($handle);
}
else {
// error opening the file.
}
?>
This works, and the page is displayed, but any php code in the original external file is not honored - it is written out as text, and not rendered by the browser.
I need the external file to fully display, just as it would if I opened the file (in this case "test.php") by itself.
Other questions I have seen on SO deal with opening or displaying a full file at once, but I need to loop through my file and do some processing on the contents first, so need to evaluate it line by line.
Any ideas would be appreciated.
Thanks
I would save the changes to a temporary file, and then include it.
<?php
$handle = fopen("test.php", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line here, and change if needed
$newCode .= "$line\n";
}
fclose($handle);
}
else {
// error opening the file.
}
// temporary file name
$temp_file = tempnam(sys_get_temp_dir(), 'myfile').".php";
// save modified code
file_put_contents($temp_file, $newCode);
// include modified code
include $temp_file;
// delete file
unlink($temp_file);
?>
Retrieve the content, process it, keep it in memory then eval() it:
<?php
$newCode = "";
$handle = fopen("test.php", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line here, and change if needed
//$line = myLineProcess($line);
$newCode .= "$line\n";
}
fclose($handle);
}
else {
// error opening the file.
}
//run the code
eval('?>'.$newCode.'<?php;');
?>
I have the following code to write data to a text file.
$somecontent = "data|data1|data2|data3";
$filename = 'test.txt';
// Let's make sure the file exists and is writable first.
IF (IS_WRITABLE($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
IF (!$handle = FOPEN($filename, 'a')) {
PRINT "Cannot open file ($filename)";
EXIT;
}
// Write $somecontent to our opened file.
IF (!FWRITE($handle, $somecontent)) {
PRINT "Cannot write to file ($filename)";
EXIT;
}
PRINT "Success, wrote ($somecontent) to file ($filename)";
FCLOSE($handle);
} ELSE {
PRINT "The file $filename is not writable";
}
Now I want this text file to only every have 10 lines of data and when a new line of data is added which is unique to the other lines then the last line of data is deleted and a new line of data is added.
From research I have found the following code however total no idea how to implement it on the above code.
check for duplicate value in text file/array with php
and also what is the easiest way to implement the following code?
<?
$inp = file('yourfile.name');
$out = fopen('yourfile.name','w');
for ($I=0;$i<count($inp)-1);$i++)
fwrite($out,$inp[$I]);
fclose($out)l
?>
Thanks for any help from a PHP newbie.
$file = fopen($filename, "r");
$names = array();
// Put the name part of each line in an array
while (!feof($file)) {
$line_data = explode("|", $fgets($file));
$names[] = $line_data[0]
}
$data_to_add = "name|image|price|link"
$data_name = "name" // I'm assuming you have this in a variable somewhere
// If the new data does not exist in the array
if(!in_array($data_name, $names)) {
unset($lines[9]); // delete the 10th line
array_unshift($lines, $data_to_add); // Put new data at the front of the array
// Write the new array to the file
file_put_contents($filename, implode("\n", $lines));
}
I am having some difficulty with reading info from a text file. Is it possible to use php and get one line at a time, and compare that line to a variable, one character at a time? Every time I add the character searching algorithm it messes up. or does the file reading only do full files/lines/character
ex:
$file=fopen("text/dialogue.txt","r") or exit("unable to open dialogue file");
if($file == true) {
echo "File is open";
fgets($file);
$c = "";
while(!feof($file)) {
$line = fgets($file)
while($temp = fgetc($line)) {
$c = $c . $temp;
//if statement and comparrison
}
}
} else {
echo "File not open";
}
fclose($file);
You may use php file function to read a file line by line
<?php
$lines = file("myfile.txt");
foreach($lines as $line){
## do whatever you like here
echo($line);
}
?>
Please check php manual
http://php.net/manual/en/function.file.php
I assume I'm using the fgets() wrong. I'm tring to open a PHP file and then try to match a line in that file with a variable I create. If the line does match then I want to write/insert PHP code to the file right below that line. Example:
function remove_admin(){
$findThis = '<tbody id="users" class="list:user user-list">';
$handle = #fopen("../../fns-control/users.php", "r"); // Open file form read.
if ($handle) {
while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 479); // Read a line.
if ($buffer == '<tbody id="users" class="list:user user-list">') // Check for string.
{
Now I want to write PHP code to the file, starting on line 480. How can I do that?
Useful information may be: IIS 6 and PHP 5.2.
Try this:
<?php
function remove_admin(){
$path = "../../fns-control/users.php";
$findThis = '<tbody id="users" class="list:user user-list">';
$phpCode = '<?php echo \'hello world\'; ?>';
#Import file to string
$f = file_get_contents($path);
#Add in the PHP code
$newfile = str_replace($findThis, $findThis . $phpCode, $f);
#Overwrite the existing file
$x = fopen($path, 'w');
fwrite($x, $newfile);
fclose($x);
}
I have a script which, each time is called, gets the first line of a file. Each line is known to be exactly of the same length (32 alphanumeric chars) and terminates with "\r\n".
After getting the first line, the script removes it.
This is done in this way:
$contents = file_get_contents($file));
$first_line = substr($contents, 0, 32);
file_put_contents($file, substr($contents, 32 + 2)); //+2 because we remove also the \r\n
Obviously it works, but I was wondering whether there is a smarter (or more efficient) way to do this?
In my simple solution I basically read and rewrite the entire file just to take and remove the first line.
I came up with this idea yesterday:
function read_and_delete_first_line($filename) {
$file = file($filename);
$output = $file[0];
unset($file[0]);
file_put_contents($filename, $file);
return $output;
}
There is no more efficient way to do this other than rewriting the file.
No need to create a second temporary file, nor put the whole file in memory:
if ($handle = fopen("file", "c+")) { // open the file in reading and editing mode
if (flock($handle, LOCK_EX)) { // lock the file, so no one can read or edit this file
while (($line = fgets($handle, 4096)) !== FALSE) {
if (!isset($write_position)) { // move the line to previous position, except the first line
$write_position = 0;
} else {
$read_position = ftell($handle); // get actual line
fseek($handle, $write_position); // move to previous position
fputs($handle, $line); // put actual line in previous position
fseek($handle, $read_position); // return to actual position
$write_position += strlen($line); // set write position to the next loop
}
}
fflush($handle); // write any pending change to file
ftruncate($handle, $write_position); // drop the repeated last line
flock($handle, LOCK_UN); // unlock the file
}
fclose($handle);
}
This will shift the first line of a file, you dont need to load the entire file in memory like you do using the 'file' function. Maybe for small files is a bit more slow than with 'file' (maybe but i bet is not) but is able to manage largest files without problems.
$firstline = false;
if($handle = fopen($logFile,'c+')){
if(!flock($handle,LOCK_EX)){fclose($handle);}
$offset = 0;
$len = filesize($logFile);
while(($line = fgets($handle,4096)) !== false){
if(!$firstline){$firstline = $line;$offset = strlen($firstline);continue;}
$pos = ftell($handle);
fseek($handle,$pos-strlen($line)-$offset);
fputs($handle,$line);
fseek($handle,$pos);
}
fflush($handle);
ftruncate($handle,($len-$offset));
flock($handle,LOCK_UN);
fclose($handle);
}
you can iterate the file , instead of putting them all in memory
$handle = fopen("file", "r");
$first = fgets($handle,2048); #get first line.
$outfile="temp";
$o = fopen($outfile,"w");
while (!feof($handle)) {
$buffer = fgets($handle,2048);
fwrite($o,$buffer);
}
fclose($handle);
fclose($o);
rename($outfile,$file);
I wouldn't usually recommend opening up a shell for this sort of thing, but if you're doing this infrequently on really large files, there's probably something to be said for:
$lines = `wc -l myfile` - 1;
`tail -n $lines myfile > newfile`;
It's simple, and it doesn't involve reading the whole file into memory.
I wouldn't recommend this for small files, or extremely frequent use though. The overhead's too high.
You could store positional info into the file itself. For example, the first 8 bytes of the file could store an integer. This integer is the byte offset of the first real line in the file.
So, you never delete lines anymore. Instead, deleting a line means altering the start position. fseek() to it and then read lines as normal.
The file will grow big eventually. You could periodically clean up the orphaned lines to reduce the file size.
But seriously, just use a database and don't do stuff like this.
Here's one way:
$contents = file($file, FILE_IGNORE_NEW_LINES);
$first_line = array_shift($contents);
file_put_contents($file, implode("\r\n", $contents));
There's countless other ways to do that also, but all the methods would involve separating the first line somehow and saving the rest. You cannot avoid rewriting the whole file. An alternative take:
list($first_line, $contents) = explode("\r\n", file_get_contents($file), 2);
file_put_contents($file, implode("\r\n", $contents));
My problem was large files. I just needed to edit, or remove the first line. This was a solution I used. Didn't require to load the complete file in a variable. Currently echos, but you could always save the contents.
$fh = fopen($local_file, 'rb');
echo "add\tfirst\tline\n"; // add your new first line.
fgets($fh); // moves the file pointer to the next line.
echo stream_get_contents($fh); // flushes the remaining file.
fclose($fh);
I think this is best for any file size
$myfile = fopen("yourfile.txt", "r") or die("Unable to open file!");
$ch=1;
while(!feof($myfile)) {
$dataline= fgets($myfile) . "<br>";
if($ch == 2){
echo str_replace(' ', ' ', $dataline)."\n";
}
$ch = 2;
}
fclose($myfile);
The solutions here didn't work performantly for me.
My solution grabs the last line (not the first line, in my case it was not relevant to get the first or last line) from the file and removes that from that file.
This is very quickly even with very large files (>150000000 lines).
function file_pop($file)
{
if ($fp = #fopen($file, "c+")) {
if (!flock($fp, LOCK_EX)) {
fclose($fp);
}
$pos = -1;
$found = 0;
while ($found < 2) {
if (fseek($fp, $pos--, SEEK_END) < 0) { // can not seek to position
rewind($fp); // rewind to the beginnung of the file
break;
};
if (ord(fgetc($fp)) == 10) { // newline
$found++;
}
}
$lastpos = ftell($fp); // get current position of file
$lastline = fgets($fp); // get current line
ftruncate($fp, $lastpos); // truncate file to last position
flock($fp, LOCK_UN); // unlock
fclose($fp); // close the file
return trim($lastline);
}
}
You could use file() method.
Gets the first line
$content = file('myfile.txt');
echo $content[0];