PHP - Match A Line In .txt File
Hi
I need to read a file and if a line match then proceed, file have content like this file.txt Code: [Select] this is line one this line two and this line three my code: $content = file_get_contents("file.txt"); if (strstr("this line two", $content)) { echo 'matched'; } else { echo 'not matched'; } but this always give not matched. any help please Similar TutorialsI have a script that reads a .gz file into an array and prints the name of each record but will not work on larger files. Is there a way to read 1 line at a time? Here is the code I have so far. Code: [Select] <?php if ($handle = opendir('.')) { print "<ol>"; while (false !== ($file = readdir($handle))) { if($file != '..' && $file!="." && $file!="start_update.php" && $file!="sharons_dbinfo.inc.php" && $file!="root.php" && $file!="read_directory.php" && $file!="read_dir.php" && $file!="new_category.php" && $file!="index.php" && $file!="file_count.php" && $file!="dir_loop2.php" && $file!="dir_loop1.php" && $file!=".htaccess" && $file!="Answer.txt" && $file!="Crucial_Technology-Crucial_US_Product_Catalog_Data_Feed.txt"){ $filename = $file; $go = filesize($filename); if($go >= 1){ $filename2 = explode("-", $filename); $filename2 = $filename2[0]; echo str_replace("_"," ",$filename2) . ' | Filesize is: ' . filesize($filename) . ' bytes<br>'; $gz = gzopen($filename, 'r'); $lines = gzfile($filename,10000); foreach ($lines as $line) { $line2 = explode(",", $line); $line2 = str_replace("," , "-" , $line2); echo "<li>".str_replace("," , "-" , $line2[4])."</li><br>"; } } } } closedir($handle); } ?> </ol> hi, im using the following code to read the content of a file, and then add a line to the end of the file. Code: [Select] $file = dirname(dirname(dirname(__FILE__))).'/includes/settings.php'; $read = fopen($file, 'r')or die('Opening Error'); $content = fread($read, filesize($file)); fclose($read)or die('Close Error'); if(isset($_POST['cat_bg'])) { $write = fopen($file, 'w')or die('Opening Error'); $cat_bg = $_POST['cat_bg']; $new_content = $content.'$color[\'cat_header\'][\'background\'] = '.$cat_bg.';'; fwrite($write, $new_content)or die('Write Error'); fclose($write); } however i would like to delete a line from the file before the content in inserted as the new line i am inserting is a duplicate variable with a different value. Can anyone help? So I'm basically done an assignment, however I'm having the biggest brainfart at the moment. For the life of me I cannot remember how to "jump line" in a file and have to put "end" at the end of my txt files. Also I have to put a break in my code which messes up my formatting:
$coursedata = explode(' ', rtrim($coursedata)); $studentdata = explode(' ', rtrim($studentdata)); fwrite($fp, $number.'||'.$_POST['course'].' '.$content);Here is the main code below for the script: <html> <head> <?php $success = 0; $number_of_registered = 0; $course_array = getdatafile('courses.txt'); $registered_array = getdatafile('register.txt'); #______________global variables____________________ function getdatafile($file) { # code... $coursedata = file_get_contents($file); $coursedata = explode(' ', rtrim($coursedata)); unset($coursedata[count($coursedata) - 1]); $course_array = array(); foreach($coursedata as $row) { $course_array[] = explode('||', $row); } return $course_array; } #_____________functions_______________________ if (isset ($_POST['name']) and isset ($_POST['number']) and isset ($_POST['course'])) { #________________test if the post exists $name = $_POST['name']; $number = $_POST['number']; $found = 0; $findregistered = 0; for ($i = 0; $i < sizeof($registered_array); $i++) { if ($registered_array[$i][0] == $_POST['number'] && $registered_array[$i][1] == $_POST['course']) { # ___________test if the student is enrolled in this course $findregistered = 1; } if($registered_array[$i][1] == $_POST['course']) { #________counter of the number registered in this course $number_of_registered++; } } for ($i = 0; $i < sizeof($course_array); $i++) { if ($course_array[$i][1] == $_POST['course']) { # ______________this test if the number of registered is the max $course_name = $course_array[$i][0]; $findcourse = 1; if($number_of_registered < $course_array[$i][2]) { $number_max = 0; } else { $number_max = 1; } } } $studentdata = file_get_contents('students.txt'); $studentdata = explode(' ', rtrim($studentdata)); for ($i = 0; $i < sizeof($studentdata); $i++) { list($studentname, $studentnumber) = explode("||", rtrim($studentdata[$i])); if (strtoupper($name) == strtoupper($studentname) && strtoupper($number) == strtoupper($studentnumber)) { $found = 1; if ($findcourse == 1 && $findregistered == 0 && $number_max == 0) { # _____________________do all the tests to record the student in the course("register.txt") and do it if all the test are checked $success = 1; $content = file_get_contents('register.txt'); $fp = fopen('register.txt', 'w'); fwrite($fp, $number.'||'.$_POST['course'].' '.$content); fclose($fp); echo "<title>".strtoupper($name).",".strtoupper($studentname)."</title>"; } } } } ?> <style> body, p{padding: 0;margin: 0;} </style> </head> <body> <form action="index.php" method="POST"> <?php if (isset ($_POST['course'])) { $course = htmlentities ($_POST['course']); # ___________________print the information of rgester in the screen for if ($success == 1) { echo "You have successfully enrolled in $course_name, $course!"; } if($found == 0) { echo 'The credentials you have entered are incorrect, please try again.'; } else { if($findregistered == 1) { echo 'You have already enrolled in this course.'; } else { if($number_max == 1) { echo "Sorry $course_name, $course is full, please select another course."; } } } } ?> <p>Courses</p> <p><input name = "name" placeholder = "Student Name" type = "text"></p> <p><input name = "number" placeholder = "Student Number" type = "text"></p> <p><select name = "course" size = "1"> <option id = "select">-- Select Course --</option> <?php for ($i = 0; $i <sizeof($course_array); $i++) { $number_of_registered1 = 0; for ($j = 0; $j < sizeof($registered_array); $j++) { if($registered_array[$j][1] == $course_array[$i][1]) { $number_of_registered1++; } } $a = '<option value = "'.$course_array[$i][1].'">'.$course_array[$i][0].' registered:'.$number_of_registered1.'</option>'; echo $a; } ?> </select></p> <p><input type = "submit" value = "Send"><input type = "reset" value = "Clear"></p> </form> </body> </html>Attached Files courses.txt 94bytes 0 downloads register.txt 3bytes 0 downloads students.txt 103bytes 0 downloads index.php 4.19KB 0 downloads Hello, I'm trying to read the first line of some large files by PHP, which means, the ideal solution does not work: Quote $content = file($file_import); $fields = explode(",", $content[0]); Quote Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 110 bytes) in C:\wamp\www\exchange\admin\import.php on line 55 Is there any other way to read only the first line without opening the whole file? Thanks!! Hello everybody! Keep in mind I'm new to PHP but get the basics I'm trying to collect email addresses from a web-form that gets filled out on a website into a simple txt file on the server. The problem is the emails get appended one right after the other with no spaces so it looks like "user@server.comuser2@server.comuser3@server.com" and so on. What I'm trying to do is either separate them by a comma, or put them on a new line but whatever I try, it will not accept it. Anyway, here is the code that I have: Code: [Select] $fp = fopen("/home/fullertr/public_html/email_collector.txt","a"); fwrite($fp,$_POST['visitormail' . "\n"]); fclose($fp); unset($_POST); Thanks for any help! i am trying to pull a .txt file for a class assignment and it is pulling everything except for line 1 any suggestions would be great html: <html> <head> <title>Weekly Report</title> <link rel ="stylesheet" type="text/css" href="sample.css" /> </head> <body> <h1>Weekly Report</h1> <p> <form action = "weeklyReport1Boles.php" method = "post" > <p> <input type = "submit" value = "Display the Report" /> </p> </form> </body> </html> txt.file 1 236.00 2 284.00 3 148.00 4 128.00 5 0.00 6 110.00 7 0.00 8 php file: <?php $total = $_POST['total']; $avgDailyIncome = $_POST['avgDailyIncome']; $badDays = $_POST ['badDays']; $paintFile = $_POST ['paintfile']; $nextDay = $_POST['nextDay']; $paintFile = fopen("weeklyDataBoles.txt","r"); $week = fgets($paintFile); $total = 0; for ($count = 1; $count <=8; $count = $count +1) { $nextDay = fgets($paintFile); $total = $total + $nextDay; } $avgDailyIncome = $total/7; print("<p>TOTAL INCOME FROM PAINT CONTRACTS: "); print("$".number_format($total, 2)."</p>"); print("<p>AVG DAILY INCOME FROM PAINT CONTRACTS: "); print("$".number_format($avgDailyIncome, 2)."</p>"); print("<p>NUMBER OF DAYS with NO INCOME: $badDays.</p>"); ?> </body> </html> Hi guys. im using this line to log any users that log into my site. It writes to the log correctly however it doesn't leave a new a line. Can anyone see what ive done wrong with my code. thanks. Code: [Select] fwrite($fh, $_SESSION['username'] . ' at ' . strftime('%c') . "\n"); Hi everyone. Well, i need help how to check a file line by line, (each line contains 1 ip address) and compare it with a variable. I have written some code but it doesn't work. Please help!! Code: [Select] $refile=''; while(!feof($file)) { $refile=fgets($file); if (strcmp($refile,"YES") == 0) echo $refile ."OK". "<br />"; else echo $refile . "NO OK ". "<br />"; } fclose($file); ?> Hi guys, I have script which scraps content from web and writes it down in a text file, now everything seems to be okay. Its scraps and writes well but the problem is when i open that text file one weird character keeps coming after some words which i don't know about. I have attached the text file, will you guys please look at it and tell me how to replace that square looking character into new line in text file. Hi to everyone. So, I have a little php code that reads line by line from a txt file, specifically i have 1 IP address for each line, and compares it with the current user's IP. It's like a little blacklist code. But it doesn't work. Can anyone see what i am doing wrong? Code: [Select] $file = fopen("ipblacklist.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached $ipblacklist=''; $refile=''; while(!feof($file)) { if (fgets($file)== $_SERVER['REMOTE_ADDR']) $ipblacklist='error'; $refile=fgets($file); } fclose($file); Thank you in advance Hi, Have a text file that is being read. I want to print the contents however I want each line of the text file to appear on a new line in the browser. So far $str = file_get_contents('records.txt'); $lines = explode("\n", $str); echo $lines[0]; Help appreciated The title says it all,..well as all u can see, there are many methods to accomplish this done but not before undergoing through a heavy tasking process. For instance, 1. Open the file 2. Reads the content of the file into array. 3. Find out the desire line of text that we want to replace. 4. Make that line of text as variable and assigns with the new data(that we want to replace) as its values. 5.open another file. 6.Write the whole contents to the file opened in 5. 7. Put the contents back to the file of original. Can anyone contributes a better way to get this done? Like replace/delete a specific line without affecting other characters or anything therein? Thanx. P.S reading and using str_replace to make the alteration always ends up in giving some kind of result beyond desired after the first round of code execution. This is a section of my code that goes and gets videos from any video site. What I’m having issues with is having it post a random title, that are all in a text file called titles.txt. What I’m wanting to accomplish is have my script go pull the video embed code, the duration, the tags, etc. Which all works fine until I get to the title part where it pulls locally from the server from the text file. I'm not an advance programmer so not sure if I am even approaching this correct way. Here is the code I have that is responsible for putting the title in. I appreciate your help. $video = array( ‘user_id’ => $this->user_id, ‘status’ => $this->status, ‘site’ => ‘my site’, ‘id’ => ‘’, ‘embeddable’ => true, ‘url’ => ‘’, ‘titles’ => ‘’, ‘title’ => ‘’, ‘description’ => ‘’, ‘tags’ => ‘’, ‘category’ => ‘’, ‘thumbs’ => array(), ‘duration’ => 0, ‘embed’ => ‘’ ); function random_title () { $titles = file (“titles.txt”, FILE_IGNORE_NEW_LINES); $num = rand (0, intval (count ($titles) / 3)) * 3; return ucwords($titles[$num]); } //Title if(preg_match(’/title="(.*?)"/’, $match, $matches_title)) { $video[‘title’] = random_title(). ’ - My site name’; } else { $this->errors[] = ‘Failed to get video title for ‘.$video[‘url’].’!’; if (!$this->debug) continue; else $debug_e[] = ‘TITLE’; }
Here's what I'm trying to do, and I am having trouble getting started with this. It's a very simple process, but I didn't want to spend the next 6 hours in frustration, so some help getting started would be great. Here's the purpose of the script: 1. Allow user to add a text file to a form. 2. Take the text file, add HTML code to the beginning and end of each paragraph (a single line of text, usually paragraphs would be separated by a line return) 3. Send the user an email with the HTML file attached and thank them or whatever. 4. Allow the system to throttle itself (one-at-a-time) so that many people using the site won't bog it down. These files will probably be anywhere from 100 KB to 1,000 KB in size, usually hitting in the 300-500KB range. Here's what I can do very easily: 1. Allow user to add a text file - very simple and straightforward. 2. Take the text file, add HTML... - this is what I need a little help figuring out. Each paragraph needs to have <p> at the beginning and </p> at the end, and the script will also search for keywords on certain lines (section headers) and add a <align="center"> tag to that, and so forth. I can handle the formatting rules, but making sure the loop runs correctly could be a problem. 3. Send the user an email... - very easy, I can do that myself. 4. Allow the system to throttle itself... - this could be tricky. I was thinking a database with a TINYINT field, 0 for not processed yet, 1 for processing, 2 for processed. Cron job checks the next one on the list to see if it needs to send it to the processor, if the file is already being processed, or can be sent to a different database (completed entries) and removed from the current queue. The cron job would also be responsible for triggering the "Your file is converted!" email and the attachment. Any/all help would be greatly appreciated on this. I am going to work on the parts that I can do myself, and I'll be checking back for the discussion - in between Mountain Dew runs. I'm ok with PHP but probably not half as good as some of you guys on here. I am basically trying to find a way to grab a line from a huge and I mean huge text file.... its basically a list of keywords I want to call by line number but without preferably going through them all before I get to that line.....otherwise couldmcrash my server obviously. At the moment im using this Code: [Select] $lines = file('http://www.mysite.com/keywords.txt'); // Loop through our array, show HTML source as HTML source; and line numbers too. foreach ($lines as $line_num => $line) { echo "$line_num"; } This works but im sure theres gotta be a better way of doing to save on usuage because this is putting the whole file into the memory and if I can simply say to php give me line number 97, would umm RULE.... Hope you guys can come up with a solution as your much smarter than me ty I have a PHP file that is executed via batch file very frequently for live updating. This is a sort of "sync" file for reading/writing to a MySQL database. I am able to get it functioning absolutely fine when executed manually via a web browser (and my echo debug lines output the expected information), yet when I run the same PHP file via the command line, it seems to just not be capable of opening any file for reading, so the equivalent variables that are correct when executed on a web browser are blank when echoed through the command line. Is there a different way of handling reading of files when running a php script via the command line, or should it function exactly the same as when run via a browser? For instance: $k = "0"; $line = file("examplefile.log")[$k]; echo $line; Hi, I want to remove all extra spaces and line breaks that I have in my PHP, HTML, CSS and JavaScript files, to reduce the file size, I do not want to go through 100+ files and do this manually. Is there a PHP script that would do this? Any suggestions where I should start looking? Thanks |