we unable to split the string following code.please Help us.
<?php
$i=0;
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "no\t";
fwrite($fh, $stringData);
$stringData = "username \t";
fwrite($fh, $stringData);
$stringData ="password \t";
fwrite ($fh,$stringData);
$newline ="\r\n";
fwrite ($fh,$newline);
$stringData1 = "1\t";
fwrite($fh, $stringData1);
$stringData1 = "srinivas \t";
fwrite($fh, $stringData1);
$stringData1 ="malayappa \t";
fwrite ($fh,$stringData1);
fclose($fh);
?>
$fh = fopen("testFile.txt", "r");
$
while (!feof($fh)) {
$line = fgets($fh);
echo $line;
}
fclose($fh);
$Beatles = array('pmm','malayappa','sreenivas','PHP');
for($i=0;$i<count($Beatles);$i++)
{
if($i==2)
{
echo $Beatles[$i-1];
echo $Beatles[$i-2];
}
}
$pass_ar=array();
$fh = fopen("testFile.txt", "r");
while (!feof($fh)) {
$line = fgets($fh);
echo $line;
$t1=explode(" ",$line);
print_r($t1);
array_push($pass_ar,t1);
}
fclose($fh);
If i read the code correctly you are writing the string seperated by \t but try to explode with spaces, use:
explode("\t", $string);
You could use fgetcsv, since you're just doing a standard tab-delimited input file. Given your sample file of:
no [tab] username [tab] password
1 [tab] srinivas [tab] malayappa
then
$lines = array();
$fh = fopen('testfile.txt', 'rb') or die ("can't open testfile.txt");
while($lines[] = fgetcsv($fh, 0, "\t") { // no line length limit, tab delimiter)
...
}
will give you
$lines = Array(
0 => Array(
0 => 'no ',
1 => 'username ',
2 => 'password '
),
1 => Array(
0 => 1,
1 => 'srinivas ',
2 => 'malayappa'
)
);
You're exploding on whitespace. Unless there is whitespace in the string your exploding then no, it won't work.
Try using the code markup to make your code a little more readable in order to get better quality responses from people.
Related
Hello,
I am making my first PHP using website and I have some things that I am writing to a log.txt. Everytime someone visits my website something gets written like this:
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: '."".$dateTime ."\n\n");
fclose($fh);
Now I would like to know, how to set a max file size for my log.txt to stop it from getting too big. For example; it'll auto delete the oldest content "block" of let's say 6 lines long and replace it with the new one after the file has exceeded (for example) 500 lines.
I couldn't find this problem online so I am very curious to how I would do this.
If you have any questions please let me know and I hope you can help me with this problem!
Please try this code. I have tested it it works fine. I use \r\n for line break so that your text file is more readable.
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
now you check if the number of lines in the file exceed your limit, then remove the old lines from the top the the file and enter new line on the top, else just enter new line.
$block = 5; //block consist of 5 lines
$remove_blocks = 10; //remove the number of blocks
$remove = $block * $remove_blocks; //totle line to remove
$line_limit = 20;
$content = file_get_contents("log.txt");
$array = explode("\r\n", $content);
$count = count($array);
if ($count >= $line_limit) {
//Remove first few lines
$array = array_slice($array, $remove);
$new_data = implode("\r\n", $array);
$fh = fopen('log.txt', 'w');
fwrite($fh, $new_data . "\r\n");
fclose($fh);
} else {
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
}
Edit: put this code in a new test.php adn experiment with it
<?php
$block = 2; //block consist of 5 lines
$remove_blocks = 1; //remove the number of blocks
$remove = $block * $remove_blocks; //totle line to remove
$line_limit = 5;
$content = file_get_contents("log.txt");
$array = explode("\r\n", $content);
$array = array_slice($array, -1);
$count = count($array);
if ($count >= $line_limit) {
//Remove first few lines
$array = array_slice($array, $remove);
$new_data = implode("\r\n", $array);
$fh = fopen('log.txt', 'w');
fwrite($fh, $new_data . "\r\n");
fclose($fh);
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
} else {
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
}
?>
I suggest using "rotation log files" for this instead. Research on google about this. You will get some easy solutions for it.
For example How to configure logrotate with php logs
Here is an Example how to get Lines Count from File https://www.w3resource.com/php-exercises/php-basic-exercise-16.php
or you can try to get file Size:
if(filesize("log.txt") >= 5000){ echo "file to is large"; }
or
$content = file_get_contents("log.txt");
$array = explode("\n", $content);
$count = count($array);
if($count >= 500){
echo "file too large";
}
You can name the file with the date as a filename
So basically for each day you will have another file
$dateTime = date('Y/m/d G:i:s');
//The file will have the name log_2019-10-09.txt
$fh = fopen('log_'.date('Y-m-d').'.txt', 'a');
fwrite($fh, 'Date/Time: '."".$dateTime ."\n\n");
fclose($fh);
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;
}
I'm writing a basic android app that sends GPS data via HTTP POST to a PHP page. I want the data to just be the two values (latitude and longitude) separated by a comma.
<?php
$myFile = "requestslog.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, "\r\n");
fwrite($fh, file_get_contents('php://input'));
fclose($fh);
echo "<html><head /><body><iframe src=\"$myFile\" style=\"height:100%; width:100%;\"></iframe></body></html>"
?>
The text file shows the data like this:
lat=55.020383&lon=-7.1819687
lat=55.020383&lon=-7.1819687
lat=55.020383&lon=-7.1819687
lat=55.0203604&lon=-7.1819732
lat=55.0203604&lon=-7.1819732
lat=55.0203604&lon=-7.1819732
Is it possible for the PHP to replace the '&' with a ','? I'm lookg for the end result to be a csv with those 2 rows. I don't have an experience with PHP and any help would be great.
str_replace('&',',') should do the trick.
If you want to end with just values, you can do following on every line:
str_replace( array( 'lat=', '&long=' ), array( '', ',' ), $sLine );
where $sLine is line from your file.
Complete example:
<?php
$myFile = "requestslog.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, "\r\n");
fwrite($fh, str_replace( array( 'lat=', '&lon=' ), array( '', ',' ), file_get_contents('php://input')));
fclose($fh);
echo "<html><head /><body><iframe src=\"$myFile\" style=\"height:100%; width:100%;\"></iframe></body></html>"
?>
I have a txt file which contains domains and ips looks like this
aaa.bbb.com 8.8.8.8
bbb.com 2.2.2.2
...
...
..
How do I replace bbb.com to 3.3.3.3 but do not change aaa.bbb.com?
Here is part of my function, but not working at all.
First part I search for the match domain by reading it line by line from file
after I got the matched record ,delete it.
Second part I write a new line into it.
$filename = "record.txt";
$lines = file($filename);
foreach($lines as $line)
if(!strstr($line, "bbb.com") //I think here is the problem core
$out .= $line;
$f = fopen($filename, "w");
fwrite($f, $out);
fclose($f);
$myFile = "record.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "bbb.com\n 3.3.3.3\n";
fwrite($fh, $stringData);
fclose($fh);
after I execute my code, both aaa.bbb.com and bbb.com were deleted, how can I solve this issue?I've try "parse_url" but "parse_url" only parse url with "http://" prefix instead of a domain.
Well, sorry for the misunderstanding, this should work:
<?php
$file = "record.txt";
$search = "bbb.com";
$replace = "3.3.3.3";
$open = file_get_contents($file);
$lines = explode(PHP_EOL, $open);
$dump = "";
foreach($lines as $line){
$pos = strpos($line, $search);
if($pos === false){
echo "<b>$line</b>";
$dump .= $line.PHP_EOL;
}else{
if($pos !== 0){
$dump .= $line.PHP_EOL;
}else{
$dump .= $search." ".$replace.PHP_EOL;
}
}
}
$dump = substr($dump,0,-1);
file_put_contents($file, $dump);
?>
The easiest solution I can think of is to use substr($line,0,7) == 'bbb.com' instead of your strstr comparison.
I have a little issue while trying to kill time. I am writint to a text file the contents of the filled in form so it is easy to read. At the moment everything gets put int a single line, and therfore I can not tell where msgs begin or end. I wrote a php like this:
$from = $_POST[from];
$friend = $_POST[friend];
$carrier = $_POST[carrier];
$message = stripslashes($_POST[message]);
if ((empty($from)) || (empty($friend)) || (empty($message))) {
header ("Location: sms_error.php");
}
else if ($carrier == "orange_mobile_network") {
$formatted_number = $friend."#orange_mobile_network.co.uk";
mail("$formatted_number", "SMS", "$message");
header ("Location: sms_success.php");
}
Then the SMS/Text message will be sent. After this I wanted to write/store/append the message on a txt file. So I wrote:
$myFile = "sms_Numbers_Mgs.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
$stringData = $_POST[from];
fwrite($fh, $stringData);
$stringData = $_POST[friend];
fwrite($fh, $stringData);
$stringData = $_POST[message];
fwrite($fh, $stringData);
fclose($fh);
But like I said. Everything works. I just want to be able to read the file and put everything in a new line and possibly format it nicely for easy reading. I do not want to use a DB for storing the TXT as my host is going to charge me.
change this:
fwrite($fh, $stringData);
with this:
fwrite($fh, $stringData . PHP_EOL);
or:
fwrite($fh, $stringData . "\r\n");
You can append PHP_EOL when you write for a platform aware newline. I.e. $stringData = <string> . PHP_EOL;
If don't need it to be platform aware, going with the windows newline is a safe option.
define('CRLF', "\r\n");
$stringData = <string> . CRLF;
fwrite($fh, $stringData);
I do not know exactly Cause you're using. txt instead of a bank, but my tip for this specific case is to work with json format.
Example:
$myFile = "sms_Numbers_Mgs.txt";
$fh = fopen($myFile, 'a+') or die("can't open file");
//assembles a string of type json
$data = json_encode(array(
'from' => $_POST[from],
'friend' => $_POST[friend],
'message' => $_POST[message]
));
//Write in the file
fwrite($fh, $data);
fclose($fh);
//reads the file
$content = file_get_contents($myFile);
$object = json_decode($content);
var_dump($object);
good it is at least better organized.
a hug!