PHP file-writing problems - php

I have a file called "number.txt"(there is a number inside, e.g.: 0 )
And I want to read the number inside the number.txt and use fwrite to write the number plus 1
(number+1), so that each time anyone visit this webpage, the number will add 1.
but when i test it, it only works at first time(now number.txt is 1).
Then i try another time, the fread function read 0 but not 1.
<?php
$fgc = file_get_contents('number.txt');
settype($cont, "integer");
$cont = $cont + 1;
settype($cont, "string");
file_put_contents('number.txt', $cont);
$str = settype($cont, "string");
$fp = fopen( $str ,'w+');
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
if($fp==false) {
$str = $str + 1;
$fp = fopen( $str ,'w+');
}
$da = $_GET['data'];
fwrite($fp, $da);
fclose($fp);
?>

And why not to do simple like this:
file_put_contents('numbers.txt', is_writeable('numbers.txt')?((int)file_get_contents('numbers.txt'))+1:exit('Failed to open file'));

Borrowing on Eugene's great one-liner, came up with the following solution.
(Credit goes to go Eugene)
The following code will create the file if it does not exist, and increment by +1 each time it is reloaded.
(Tested)
<?php
$filename = "number.txt";
$filename = fopen($filename, 'a') or die("can't open file");
file_put_contents('number.txt', ((int)file_get_contents('number.txt'))+1);
// To show (echo) the contents of the file, you can use one of the following
// include("number.txt");
// echo file_get_contents('number.txt');
?>

It is because you are setting the write data to the old GET var and not the new set var.
fwrite($fp, $da);
Try using
fwrite($fp, $str);
And also you only need to fopen() once.

$filename = 'number.txt';
$content = (int) file_get_contents($filename);
$content++;
var_dump($content);
file_put_contents($filename, $content);
You have to create that file number.txt and insert there 0 as file content, then your script should work every time.

You are reading the contents into the variable $fgc, but you're trying to use $cont to represent that value, which is uninitialized. So your settype call is going to cast that to 0. Instead, try:
$fgc = file_get_contents('number.txt');
settype($fgc, "integer");

Related

php set lines in a text file to an array value

Im looking to do something like the following
$file = ('file.txt');
$fopen($file);
then read each line from the file individually and set it as a specific array
like so
read $file get $line1 set as $array[0]
read $file get $line2 set as $array[1]
read $file get $line3 set as $array[2]
I would like to use these arrays created from the lines on the text file IN PLAIN TEXT like this:
$urlout = file_get_contents("http://myurl.com/?=$line1");
echo $urlout;
$urlout2 = file_get_contents("http://myurl.com/?=$line2");
echo $urlout2;
$urlout3 = file_get_contents("http://myurl.com/?=$line3");
echo $urlout3;
So if the array were 123.22.11.22 the link would look like this:
$line1 = array[0] (123.22.11.22)
$urlout = file_get_contents("http://myurl.com/?=$line1");
echo $urlout;
and the result would be
Info for 123.22.11.22
more info
some more
Modified answer as per the change indicated by the user :
Reading 2 lines on each loop..
$lines = file("file.txt");
for($i=0 ; $i<count($lines); $i=($i+2) )
{
echo file_get_contents("http://myurl.com/?=".$lines[$i]);
echo file_get_contents("http://myurl.com/?=".$lines[($i + 1)]);
}
Imp Note : A URL can be used as a filename with file_get_contents() function, only if the fopen wrappers have been enabled.
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo file_get_contents("http://myurl.com/?=$line");
}
fclose($handle);
}
The answer was to insert a "\n" separator upon inserting into the text file, then removing it after the first result was called
$lines = file("geo.txt");
for($i=0 ; $i<count($lines); $i=($i+2) )
{
echo file_get_contents("https://test.com/api/GEO.php?info=".$lines[$i]);
$lolz = file_get_contents("https://test.com/api/GEO.php?info=".$lines[($i + 1)]);
$lolz = str_replace(" \n", '', $lolz);
echo "<br>".$lolz;
}

How can I add multiple strings to one text file, and read the all?

I am trying to make a program where I can add things to a list, read things, and clear the list. I have the clear function working perfectly, however I can't seem to add or read more than 1 line at a time. I am using fwrite($handle, $MyString); but that replaces everything in the entire file with $MyString. To get the information from the file I am using $list = fgets($handle); and then using echo to print it. This reads the first line in the file only.
Any help?
Thanks!
Getlist code:
<?php
$myFile = "needlist.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
Add to the list code:
<?php
$neededlist = "needlist.txt";
$fh = fopen($neededlist, 'w');
$user_message = $_REQUEST['txtweb-message'];
$needed .= $user_message;
$needed .= "\n";
fwrite($fh, $needed);
fclose($fh);
echo "You have successfully added ", $user_message;
?>
When you write to the file are you opening your filehandle with the "a" mode option? Opening with "w" or "x" truncates it so you start with a clean file (http://php.net/fopen)
fgets(); reads only until the end of the line ( http://php.net/fgets ). To get the whole file you can try:
var $list = "";
var $line = "";
while ($line = fgets($handle)) {
$list = $list . "\n" . $line;
}
echo $list;
You want to add the "\n" because fread doesn't read the linefeeds IIRC. There're also a couple functions that might be more appropriate in this situation like file_get_contents and fread.
Fgets returns only one string. You should use it in cycle like that:
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}

How to replace one line in php?

I have test.txt file, like this,
AA=1
BB=2
CC=3
Now I wanna find "BB=" and replace it as BB=5, like this,
AA=1
BB=5
CC=3
How do I do this?
Thanks.
<?php
$file = "data.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, 1024);
// You have the data in $data, you can write replace logic
Replace Logic function
$data will store the final value
// Write back the data to the same file
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
echo "$data <br>";
}
fclose($fp);
?>
The above peace of code will give you data from the file and helps you to write the data back to the file.
Assuming that your file is structured like an INI file (i.e. key=value), you could use parse_ini_file and do something like this:
<?php
$filename = 'file.txt';
// Parse the file assuming it's structured as an INI file.
// http://php.net/manual/en/function.parse-ini-file.php
$data = parse_ini_file($filename);
// Array of values to replace.
$replace_with = array(
'BB' => 5
);
// Open the file for writing.
$fh = fopen($filename, 'w');
// Loop through the data.
foreach ( $data as $key => $value )
{
// If a value exists that should replace the current one, use it.
if ( ! empty($replace_with[$key]) )
$value = $replace_with[$key];
// Write to the file.
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
// Close the file handle.
fclose($fh);
The simplest way (if you are talking about a small file as above), would be something like:
// Read the file in as an array of lines
$fileData = file('test.txt');
$newArray = array();
foreach($fileData as $line) {
// find the line that starts with BB= and change it to BB=5
if (substr($line, 0, 3) == 'BB=')) {
$line = 'BB=5';
}
$newArray[] = $line;
}
// Overwrite test.txt
$fp = fopen('test.txt', 'w');
fwrite($fp, implode("\n",$newArray));
fclose($fp);
(something like that)
You can use Pear package for find & replace text in a file .
For more information read
http://www.codediesel.com/php/search-replace-in-files-using-php/

Write to specific line in PHP

I'm writing some code and I need to write a number to a specific line. Here's what I have so far:
<?php
$statsloc = getcwd() . "/stats/stats.txt";
$handle = fopen($statsloc, 'r+');
for($linei = 0; $linei < $zone; $linei++) $line = fgets($handle);
$line = trim($line);
echo $line;
$line++;
echo $line;
I don't know where to continue after this. I need to write $line to that line, while maintaining all the other lines.
you can use file to get the file as an array of lines, then change the line you need, and rewrite the whole lot back to the file.
<?php
$filename = getcwd() . "/stats/stats.txt";
$line_i_am_looking_for = 123;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$lines[$line_i_am_looking_for] = 'my modified line';
file_put_contents( $filename , implode( "\n", $lines ) );
This should work. It will get rather inefficient if the file is too large though, so it depends on your situation if this is a good answer or not.
$stats = file('/path/to/stats', FILE_IGNORE_NEW_LINES); // read file into array
$line = $stats[$offset]; // read line
array_splice($stats, $offset, 0, $newline); // insert $newline at $offset
file_put_contents('/path/to/stats', join("\n", $stats)); // write to file
I encountered this today and wanted to solve using the 2 answers posted but that didn't work. I had to change it to this:
<?php
$filepathname = "./stats.txt";
$target = "1234";
$newline = "after 1234";
$stats = file($filepathname, FILE_IGNORE_NEW_LINES);
$offset = array_search($target,$stats) +1;
array_splice($stats, $offset, 0, $newline);
file_put_contents($filepathname, join("\n", $stats));
?>
Because these lines don't work since the arg of the array is not an index:
$line = $stats[$offset];
$lines[$line_i_am_looking_for] = 'my modified line';
Had to add that +1 to have the new line under the searched text.

Find and edit text files via PHP

Let say a text file contain
Hello everyone, My name is Alice, i stay in Canada.
How do i use php to find "Alice" and replace it with "John".
$filename = "C:\intro.txt";
$fp = fopen($filename, 'w');
//fwrite($fp, $string);
fclose($fp);
$contents = file_get_contents($filename);
$new_contents = str_replace('Alice', 'John', $contents);
file_put_contents($filename, $new_contents);
Read the file into memory using fread(). Use str_replace() and write it back.
If its a big file, use iteration instead of reading all into memory
$f = fopen("file","r");
if($f){
while( !feof($f) ){
$line = fgets($f,4096);
if ( (stripos($line,"Alice")!==FALSE) ){
$line=preg_replace("/Alice/","John",$line);
}
print $line;
}
fclose($f);
}

Categories