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
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);
I got this error and I dont know why. I tried to change the code but nothing happened.
Its on the line:
if ($system[1] == $filters[$f]){$files[] = $file;}
I tried to change the value to 0, and it show nothing.
Here is the code:
<?php
function directory($dir,$filters)
{
$handle=opendir($dir);
$files=array();
if ($filters == "all"){while(($file = readdir($handle))!==false){$files[] =
$file;}}
if ($filters != "all")
{
$filters=explode(",",$filters);
while (($file = readdir($handle))!==false)
{
for ($f=0;$f<sizeof($filters);$f++):
$system=explode(".",$file);
if ($system[1] == $filters[$f]){$files[] = $file;}
endfor;
}
}
closedir($handle);
return $files;
}
$folder = "photobooth/photobooth/Michelle_Illona_Alexander/animated/"; //folder tempat gambar disimpan
$handle = opendir($folder);
$i = 1;
while(false !== ($file = readdir($handle) )){
if($file != '.' && $file != '..'){
$file2=str_replace("_mp4.jpg","",$file);
$file3=substr($file,0);
$filenames= directory(".","jpg");
foreach ($filenames as $value)
{
echo '<li>'.
'<a href="photobooth/photobooth/Michelle_Illona_Alexander/animated/'.$file2.'.mp4">
<img src="photobooth/photobooth/Michelle_Illona_Alexander/animated/'.$file.'" width="300" title="" type="jpg"></a>'.
'<br/></li>';
if(($i % 4) == 0){
echo '<br/>';
echo '<br/>';
echo '<br/>';
echo '<br/>';
echo '<br/>';
echo '<br/>';
echo '<br/>';
echo '<br/>';
echo '<br/>';
}
$i++;
if($i==0)
break;
}
}
}
?>
I want to ask - How can I return/make array with-in a foreach loop?
Here is my code
function getAllUsers() {
$dir = "users/";
$fl = scandir($dir);
$cnt = 0;
foreach (scandir($dir) as $fl) {
if ($fl !== '.') {
if ($fl !== '..') {
if ($fl !== 'index.php') {
$pr = $fl;
$fl1 = scandir($dir . '/' . $fl);
$cnt++;
return $fl1[3]; //Here I want a array for file inside 'users\'.
}
}
}
}
}
Thanks for giving answer.
Basically: you can not.
upon using return, the current function returns the value and stops execution.
return is by definition the end of the function.
but you can save the data you want to return in an array and then return the whole thing:
function getAllUsers() {
$dir = "users/";
$fl = scandir($dir);
$cnt = 0;
$result = []; //initiating the array
foreach (scandir($dir) as $fl) {
if ($fl !== '.') {
if ($fl !== '..') {
if ($fl !== 'index.php') {
$pr = $fl;
$fl1 = scandir($dir . '/' . $fl);
$cnt++;
$result[] = $fl1[3]; //adding your value to the array
}
}
}
}
return $result;
}
Edit: If your PHP-Version mucks about the $result = []; you can use the "old" style $result = array(); instead
Generators: Solution for PHP >= 5.5.
If you want the function to return a value for each element in the loop back from the function use a generator:
/**
* #return Generator|Iterator
*/
function getAllUsers() {
$dir = "users/";
$fl = scandir($dir);
$cnt = 0;
foreach (scandir($dir) as $fl) {
if ($fl !== '.') {
if ($fl !== '..') {
if ($fl !== 'index.php') {
$pr = $fl;
$fl1 = scandir($dir . '/' . $fl);
$cnt++;
yield $fl1[3]; //Here I want a array for file inside 'users\'.
}
}
}
}
}
// Loop over
foreach (getAllUsers() as $file) {
}
// Or one at a time
$generator = getAllUsers();
$file1 = $generator->current();
The other solutions here are more feasible however, this solution is mostly useful for implementing the IteratorAggregate interface, or creating co-routines.
You can achieve this by using an array. like below..
function getAllUsers() {
$dir = "users/";
$fl = scandir($dir);
$cnt = 0;
$array = array();
foreach (scandir($dir) as $fl) {
if ($fl !== '.') {
if ($fl !== '..') {
if ($fl !== 'index.php') {
$pr = $fl;
$fl1 = scandir($dir . '/' . $fl);
$cnt++;
$array[$fl] = $fl1[3]; //Push values in array for each user.
}
}
}
}
return $array;
}
Hope this will help
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>";
}
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.