I want to keep just an exact number of line from this, it takes a file reverse it and echo it, but the file might get to long and want to limit it to a number of lines.
$file = file("update.log");
$file = array_reverse($file);
foreach($file as $f){
if (stripos($f, "Sale") !== false) {
$class = "sales";
} else{
$class = "row";
}
echo "<div class='".$class." scale'>".$f."</div>";
}
Use a counter and when it hits the max_lines number break out of the foreach loop.
$file = file("update.log");
$file = array_reverse($file);
$count = 0;
$max_lines = 100;
foreach($file as $f){
if ($count >= $max_lines){
break;
}
if (stripos($f, "Sale") !== false) {
$class = "sales";
} else{
$class = "row";
}
$count++;
echo "<div class='".$class." scale'>".$f."</div>";
}
$file = file("update.log");
$file = array_reverse($file);
$lineLimit = 25;
$lineCounter = 0;
foreach($file as $f){
if (stripos($f, "Sale") !== false) {
$class = "sales";
} else{
$class = "row";
}
echo "<div class='".$class." scale'>".$f."</div>";
$lineCounter++;
if($lineCounter > $lineLimit)
break; //Will exit the loop
}
I think this is faster and more flexible in avoiding memory problems. You don't have to read every line of the file so you could use something like this:
function viewLastLines($logfile,$maxlines=25) {
$handle = fopen($logfile, "r");
fseek($handle, -($maxlines),SEEK_END);
while (($line = fgets($handle)) !== false)
$outputlines[]=$line;
fclose($handle);
return $outputlines;
}
Use it like this in your case:
$file = array_reverse(viewLastLines("update.log",100));
foreach($file as $f){
if (stripos($f, "Sale") !== false) $class = "sales";
else $class = "row";
echo "<div class='".$class." scale'>".$f."</div>";
}
Related
I do not have much experience with php. I have one good script. It searches files in a folder by the name of the file, example pdf file. It works, but I need to limit the number of results because when I search for pdf for example it shows me all pdf files, I do not have a limit on the results. I need to limit this to only 15 results.
And another question: is it possible to add the message "file not found" to the results if nothing was found?
<?php
$dir = 'data';
$exclude = array('.','..','.htaccess');
$q = (isset($_GET['q']))? strtolower($_GET['q']) : '';
$res = opendir($dir);
while(false!== ($file = readdir($res))) {
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) {
echo "<a href='$dir/$file'>$file</a>";
echo "<br>";
}
}
closedir($res);
?>
You might just want to add a counter either before the if or inside the if statement, however you wish, and your problem may be solved:
Counter Before if
$dir = 'data';
$exclude = array('.', '..', '.htaccess');
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$res = opendir($dir);
$c = 0; // counter
while (false !== ($file = readdir($res))) {
$c++; // add 1
if (strpos(strtolower($file), $q) !== false && !in_array($file, $exclude)) {
echo "<a href='$dir/$file'>$file</a>";
echo "<br>";
}
if ($c > 15) {break;} // break
}
closedir($res);
Counter Inside if
$dir = 'data';
$exclude = array('.', '..', '.htaccess');
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$res = opendir($dir);
$c = 0; // counter
while (false !== ($file = readdir($res))) {
if (strpos(strtolower($file), $q) !== false && !in_array($file, $exclude)) {
$c++; // add 1
echo "<a href='$dir/$file'>$file</a>";
echo "<br>";
if ($c > 15) {break;} // break
}
}
closedir($res);
$find = '.5010.';
$directory_with_files = './'.date('m-d-Y');
$dh = opendir($directory_with_files);
$files = array();
while (false !== ($filename = readdir($dh)))
{
if(in_array($filename, array('.', '..')) || is_dir($filename))
continue;
$files[] = $filename;}
foreach($files as $file){
//find only 5010 files
if(stripos($file, $find) !== false){
// open the 5010 file
$handle = fopen(date('m-d-Y').'/'.$file, "r");
$file_content = file_get_contents(date('m-d-Y').'/'.$file);
$handle2 = fopen(date('m-d-Y').'/'.$file, "r");
$file_content2 = file_get_contents(date('m-d-Y').'/'.$file);
if ($handle) {
$header = '';
$name = '';
$footer = '';
$payor_blocks = array();
// determine if file has more than one payor
$payor_count = substr_count($file_content, 'N1*PR*');
//if the file has more than one payor
if($payor_count > 1) {
//read the file line by line
$header_end = false;
$block_start = false;
$count = 1;
if($handle2){
$line_number = 0;
$line_stop= array();
while (($line1 = fgets($handle2)) !== false) {
$line_number++;
if(strpos($line1, 'CAS') !==false){
$line_stop[] = $line_number;}}
$footer_line = count($line_stop)-2;
$footer_line = $line_stop[$footer_line];
$line_number = 0; }
//look for occurances of CAS and what line each on is on
while (($line = fgets($handle)) !== false) {
$line_number++;
//look for the first payor block
if(strpos($line, 'N1*PR*') !== false || $block_start) {
$header_end = true; $block_start = true;
if(strpos($line, 'N1*PR*') !== false) {
$count++;
}
//see if the block finished
if($line_number == $footer_line) {
$block_start = false;
$payor_blocks[$count] .= $line;
$count++; }
$payor_blocks[$count] .= $line;}
else {
if($header_end) {
$footer .= $line."\n"; }
else {
$header .= $line."\n";}}
$refid = 'REF*2U*';
if(stripos($line, $refid) !== false)
{
$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
$refnumber = trim($refnumber);
if($refnumber != '')
{
$refnumber = '_'.$refnumber.'_';
$filerenamed = str_replace($find, $refnumber,$file);
copy('./'.date('m-d-Y').'/'.$file, './'.date('m-d-Y').'/'. $filerenamed);
}
echo $refnumber . "\n";
}
}
//get payor blocks and create a file foreach payor
$new_files = array();
foreach($payor_blocks as $block) {
$filename = date('m-d-Y').'/'.$file . "_" . $count;
$count++;
$new_files[] = array(
'name' => $filename,
'content' => $header."\n".$block."\n".$footer
);
}
foreach($new_files as $new_file) {
$myfile = fopen($new_file['name'], "w");
fwrite($myfile, $new_file['content']);
fclose($myfile);
}
}
else{
while (($line = fgets($handle)) !== false)
{
$refid = 'REF*2U*';
if(stripos($line, $refid) !== false)
{
$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
$refnumber = trim($refnumber);
if($refnumber != '')
{
$refnumber = '_'.$refnumber.'_';
$filerenamed = str_replace($find, $refnumber,$file);
copy('./'.date('m-d-Y').'/'.$file, './'.date('m-d-Y').'/'. $filerenamed);
}
echo $refnumber . "\n";
}
}
}
}
}
// DONE - close the file
fclose($handle);
}
foreach($files as $fiftyfile){
if(stripos($fiftyfile, $find) !== false){
$handle3 = fopen(date('m-d-Y').'/'.$fiftyfile, "r");
$file_content3 = file_get_contents(date('m-d-Y').'/'.$fiftyfile);
if ($handle3) {
if(unlink('./'.date('m-d-Y').'/'.$fiftyfile))
{
echo "file named $fiftyfile has been deleted successfully";
}
else
{
echo "file is not deleted";
}
}
}
}
I have a few files in my directory with filenames that contain "3256.5010.548674.23a" In this code it opens the file and searches if there is more than one "N1*PR*" and if there is to split them into separate files. Lastly to change ".5010." to the REF number which is something like "8743" . Then it deletes all the files with ".5010." And combines the rest in one document. It works fine however, when I first run it it splits and renames, but only deletes the first files not all the ".5010." (not the ones that were split), which then when I run it again after that, it deletes everything but renames the old ones, since it goes through the "else statement" that also does the renaming. How could I solve the issue with the delete?
All i want is to open a rsyslog file with fopen() take the first 3 lines set a variable with the last of this 3 lines. Then take the other 3 lines e.t.c.
$path_file = variable_get('$path');
$file = fopen($path_file, 'r');
for($i=0;$i<3;$i++) {
$line = fgets($file);
$line = variable_set($line);
}
fclose($file);
Use file() instead (reads everything in as an array)
Try this:
$file = file('$path');
for($x = 0; $x < count($file); $x = $x + 3)
{
if(isset($file[$x]) && isset($file[$x +1]) && isset($file[$x + 2])
{
//do something with the values.
}
}
function readFileStartingAtLineNumber($x)
{
$file = file('$path');
if(isset($file[$x]) && isset($file[$x +1]) && isset($file[$x + 2])
{
//do something with the values.
}
}
function getLog($path, $numberOfLines, $lastIndex) {
$file = fopen($path, 'r');
if (!$file) {
print 'error opening file';
}
else {
$data = '';
$i = -1;
while(($line = fgets($file)) !== FALSE) {
if(++$i < $lastIndex) continue;
if($numberOfLines-- == 0) break;
$data .= $line;
}
fclose($file);
if ($data === '') {
print 'EOF reached without getting data';
}
}
return $i;
}
The goal is to have the results of a foreach loop display an array's content in the form page. I'm have been able to display error messages, but not more than one when several exist. Currently the code returns collection array with many lines but my purpose is to generate line by line via respective condition.
index.php
<tbody>
<?php
include './function/check.php';
foreach ($urls as $url) {
?>
<tr>
<td> <?php print_r($url[2]); ?></td>
<td><?php print_r($url[1]); ?></td>
<td>
<?php
var_dump($output);
?>
</td>
</tr>
<?php
}
}
?>
</tbody>
check.php
<?php
include 'checkfunction.php';
if (isset($_POST['sourceDir'])) {
$sourceDir = $_POST['sourceDir'];
$urls = array();
$linecount = 1;
$output = array();
$errmsg = '';
if (is_dir($sourceDir)) {
if ($dh = opendir($sourceDir)) {
while (false !== ($filename = readdir($dh))) {
if ($filename != "." && $filename != ".." && strtolower(substr($filename, strrpos($filename, '.') + 1)) == 'php') {
$absolute_path = str_replace('\\', '/', $sourceDir) . '/';
$readfile = fopen($absolute_path . $filename, 'r');
if ($readfile) {
while (FALSE !== ($line = fgets($readfile))) {
$ary = check($line, $linecount, $filename);
if ($ary != null) {
array_push($urls, $ary);
$errmsg = array($errmsg);
$out1 = '';
foreach ($errmsg as $k => $v) {
$out1 = $v;
$output[] = $out1;
}
var_dump($output);
}
$linecount++;
}
fclose($readfile);
}
$linecount = 1;
}
}
closedir($dh);
}
}
}
?>
checkfunction.php
<?php
function check($line, $linecount, $filename) {
global $errmsg;
$urls = array($line, $linecount, $filename);
if (preg_match("/\=/", $line)) {
if (preg_match("/\\s\=\\s/i", $line) || preg_match("/\\s\==\\s/", $line) || preg_match("/\\s\===\\s/", $line)) {
} else {
$errmsg = "There should be space before and after of equal";
return $urls;
}
} elseif (strpos($line, 'if') !== false) {
if (preg_match("/\!\\\$[a-zA-z0-9]/i", $line)) {
$errmsg = "•If you want to use ifcondition, don't use !.Use false === ";
return $urls;
}
}
}
Just add ini_set('display_errors',1); after the opening in the first page.
It's the equivalent to enabling error_reporting in php.ini
//I hope thats, what you're looking for..
to do that you need to use a foreach loop, try this :
$errors = array(); //consider this is the array where ur storing all the errors, im doing this to make it more logical
//for each item in the array store it in a new variable named $error, and then we echo it :
foreach($errors as $error){
//you can also style all the errors, or make them a part of a <ul> like this
echo '<ul>
<li>'.$error.'</li>
</ul>';
}
this should display all the error messages you have
I have a CSV upload that I am struggling to get to skip the first line of the CSV document. I am uploading a single CSV document and the first line contains a cell that contains one bit of text which is throwing out the array. I am not sure which count to edit?
$fields_firstrow = true;
$i = 0;
$a = 0;
$fields = array();
$content = array();
$allowedExts = array("csv");
$extension = end(explode(".", $_FILES["file"]["name"]));
if (($_FILES["file"]["size"] < 2000000)&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
if (file_exists($_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],$_FILES["file"]["name"]);
}
}
}
else
{
echo "Invalid file";
}
$file = $_FILES["file"]["name"];
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
if($fields_firstrow == true && $i<1) {
foreach($data as $d) {
$fields[] = strtolower(str_replace(" ", "_", $d));
}
$i++;
continue;
}
$c = 0;
foreach($data as $d) {
if($fields_firstrow == true) {
$content[$a][$fields[$c]] = $d;
} else {
$content[$a][$c] = $d;
}
$c++;
}
$a++;
}
} else {
echo "Could not open file";
die();
}
Any help would be greatly appreciated.
Just add an extra line of code before the line from where the while loop starts as shown below :
....
.....
fgetcsv($handle);//Adding this line will skip the reading of th first line from the csv file and the reading process will begin from the second line onwards
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
.......
.......
It is just as simple........ !!!
$i=0;
if($fields_firstrow == true) {
foreach($data as $d) {
if ($i == 0){continue;}
$i++;
$fields[] = strtolower(str_replace(" ", "_", $d));
}
}
You are not changing the value for variable $fields_firstrow. For all loop iteration it will still be true.
In my opinion and per my understand of your code, you should change it to false before the first continue.
...
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
if($fields_firstrow == true && $i<1) {
foreach($data as $d) {
$fields[] = strtolower(str_replace(" ", "_", $d));
}
$i++;
$fields_firstrow = false;
continue;
}
$c = 0;
foreach($data as $d) {
if($fields_firstrow == true) {
$content[$a][$fields[$c]] = $d;
} else {
...
Maybe you do not need the $i variable after that.
Here is an example from http://php.net/fgets modified a bit:
<?php
$handle = #fopen("/tmp/inputfile.txt", "r");
$firstLine = true;
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
if(firstLine) {
$firstLine = false;
continue;
}
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
I assume you see the point, and can modify your script accordingly.