I wrote a script in php which reads two files and takes all the strings from one file and searches them in other file. This is working fine in web browser. But when I try to run it through command line, it says 'invalid arguments supplied for foreach() at line....' am I missing anything?
<?php
$filename = 'search_items.txt';
$fp = @fopen($filename, 'r');
if ($fp) {
$array = explode(",", fread($fp, filesize($filename)));
}
$filename1 = 'file1.log';
$fp1 = @fopen($filename1, 'r');
if ($fp1) {
$array1 = explode("
", fread($fp1, filesize($filename1)));
}
$num = 1;
foreach($array1 as $val1){
foreach($array as $val){
if(strstr($val1, $val)){
echo 'line : '.$num.'->'.$val1.'<br>';
}
}
++$num;
}
?>
<?php
$filename = 'search_items.txt';
$fp = fopen($filename, 'r');
if ($fp) {
$array = explode(",", fread($fp, filesize($filename)));
}
$filename1 = 'file1.log';
$fp1 = fopen($filename1, 'r');
if ($fp1) {
$array1 = explode("
", fread($fp1, filesize($filename1)));
}
$num = 1;
foreach($array1 as $val1)
{
foreach($array as $val)
{
if(strstr($val1, $val))
{
print_r('
'); //2
}
}
++$num;
print_r($val1); // 1
}
Ok, the script is running now, but with something funny going on. if I remove the print in comment 1 and place it in comment 2 place, the results I am getting is the last result , i.e just one last result. not the full searches. Can anyone tell me why?
Probably your file paths are off, so $array and $array1 are never created. Relative paths will be from where you call the script, not the location of the script.
Your fopen
calls are not finding their file, I imagine. First, remove the '@' from '@fopen', so you can see it fail. Then, do this:
$filename = dirname(__FILE__).'/search_items.txt';
//...
$filename1 = dirname(__FILE__).'/file1.log';
That will keep your file locations straight.
Maybe variables are empty or not exist?
$array = $array1 = array();
//...
foreach((array)$array1 as $val1)
{
foreach((array)$array as $val)
{
if(strstr($val1, $val))
{
echo 'line : '.$num.'->'.$val1.'<br>';
}
}
$num++;
}
To be on the safe side you should add a check if the file pointers are valid before running the foreach loops, or throw some errors if you fail to open a file.
<?php
$filename = 'search_items.txt';
$fp = @fopen($filename, 'r');
if ($fp) {
$array = explode(",", fread($fp, filesize($filename)));
}
$filename1 = 'file1.log';
$fp1 = @fopen($filename1, 'r');
if ($fp1) {
$array1 = explode("
", fread($fp1, filesize($filename1)));
}
$num = 1;
if($fp && $fp1)
{
foreach($array1 as $val1)
{
foreach($array as $val)
{
if(strstr($val1, $val))
{
echo 'line : '.$num.'->'.$val1.'<br>';
}
}
++$num;
}
}
?>
Keep in mind that when running a script from CLI, the current directory is the directory from which the script was started. When running trough Apache, the current directory is the directory of the script. This bit me a couple of times.