How to correctly use the PHP function 'fgets'? - 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);
}

Related

PHP Replace all values in the third column in a csv file

I am trying to replace some hyperlinks in a csv file, like this one:
[https://assets.suredone.com/683987/media-pics/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. Here is my code:][1]. Here is my code:
<?php
$in_file = 'gabriel-images-urls.csv';
$out_file = 'results.csv';
$fd = fopen($in_file, "r");
$new_array= array();
$toBoot= array();
while ($data = fgetcsv($fd)) {
echo '<pre>';
if (strpos($data[2],'media-pics') !== false) {
$data[2]=str_replace('media-pics','media-photos',$data[2]);
fputcsv($fd, $data);
// echo $output;
}
}
?>
The new link for example must look like this:[1]https://assets.suredone.com/683987/media-photos/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. The goal is he "media-pics" substring to be replaced with "media-photos". At this point nothing happens in the file. I think this is because the file is open only for reading but I am not sure.
Can you not simply do a string replacement on the whole file rather than attempting to load and process each line of the file using fgetcsv?
<?php
$srcfile='gabriel-images-urls.csv';
$outfile='results.csv';
$csvdata=file_get_contents( $srcfile );
$moddata=str_replace('media-pics','media-photos',$csvdata);
file_put_contents( $outfile, $moddata );
?>

fopen multiple files in php

I'm trying to make my PHP script open more than 1 text document and to read them.
My current script is as follows:
<?php
//$searchthis = "ignore this";
$matches = array();
$FileW = fopen('result.txt', 'w');
$handle = #fopen("textfile1.txt", "r");
ini_set('memory_limit', '-1');
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(stripos($buffer, $_POST["search"]) !== FALSE)
$matches[] = $buffer;
}
fwrite($FileW, print_r($matches, TRUE));
fclose($handle);
}
?>
I'm trying to fopen like a bunch of files, maybe like 8 of them or less.
How would I open, and read all these files?
Any help is GREATLY appreciated!
Program defensively, check the return's from functions to ensure you are not making incorrect assumptions about your code.
There is a function in PHP to read the file and buffer it:
enter link description here
I don't know why you would want to open a lot of files, it surely will use a lot of memory, anyway, you could use the file_get_contents function with a foreach:
$files = array("textfile1.txt", "textfile2.txt", "textfile3.txt");
$data = "";
foreach ($files as $file) {
$data .= #file_get_contents($file);
}
echo $data;
There is a function in php called file which reads entire file into an array.
<?php
// "file" function creates array with each line being 1 value to an array
$fileOne = file('fileOne.txt');
$fileTwo = file('fileTwo.txt');
// Print an array or do all array magic with $fileOne and $fileTwo
foreach($fileOne as $fo) {
echo $fo;
}
foreach($fileTwo as $ft) {
$echo $ft;
}
?>
Read more about : file function ion php

Write to file using SplFileObject()

I'm trying to edit a file by line using SplFileObject(). I can choose the line of the file I want to edit. But how do I then write a $string to that line?
Here is my code to get the line:
<?php
$file = new SplFileObject('myfile.txt');
$file->seek(9999); // Seek to line no. 10,000
echo $file->current(); // Print contents of that line
?>
How do I insert a string on that line?
Note, I don't want to overwrite the file, I simply want to insert a $string at a given line.
This isn't probably the best solution as it will read the whole file and store it in a string. But since there are no other answers you can use this as your last resource.
$ouput = '';
$file = new SplFileObject("your_file.xxx", 'r');
while (!$file->eof()) {
$line = $file->fgets();
if($line == 'your_condition'){
$line = 'replace this line';
}
$output .= $line;
}
$file = null;
$file = new SplFileObject("your_file.xxx", 'w+');
$file->fwrite($output);

Get only one line from a web page

Hi, I have this file test1.php and in the other file test.php I have this
php code running:
<?php
$file = "http://inviatapenet.gethost.ro/sop/test1.php";
$line = '0';
if($f = fopen($file, 'r')){
$line = fgets($f); // read until first newline
fclose($f);
}
echo $line;
?>
The idea is to get just the second line of the web page test1.php.
Second Line
I've tried to change the $line = '2'; but no affect, it just displays the first line.
I need Help.
You can use file which reads a file into an array, you can then grab whichever line you want by using the index you want.
For example:
data.txt:
line one
line two
line three
line four
PHP code:
$file = file('data.txt');
echo $file[1]; // echo line number 2, remember arrays start at 0!
Updated PHP code for new versions (5.4):
echo file('data.txt')[1];
This should work. Obviously, change only the value of $linetofetch:
<?php
// Write here the number of the line you want to fetch.
$linetofetch = 2;
$file = "http://inviatapenet.gethost.ro/sop/test1.php";
$currentline = 1;
if($f = fopen($file, 'r')){
while ($currentline <= $linetofetch) {
$line = fgets($f); // read until first newline
$currentline++;
}
fclose($f);
}
echo $line;
?>

PHP fgets() won't work unless it's implemented with a variable?

I'm writing some code that can read in from a .txt file a display it on a webpage.
I had problems in my initial code, in that it would read in any text and it would erase whatever was in the document.
My original code:
function readIn(){
$input = fopen("input.txt", "r"); //Open the file, save opened file in input
$line = fgets($input);
fclose($input);
return $line
}
It only started working once I put in a While loop to go through EVERY LINE
function readIn(){
$input = fopen("input.txt", "r"); //Open the file, save opened file in input
$fullText = ""; //Variable full text
while(!feof($input)){
$line = fgets($input);
$fullText = $fullText . $line;
}
fclose($input);
return $fullText;
}
echo readIn();
Use "file_get_contents" to read an entire file into a variable, and then output in whatever fashion you choose.

Categories