I'm a bit stuck with the following code which correctly opens a csv file (list.csv) and detects whether there is a match in one of the lines that matches what is in the variable $match. Just to clarify, the script works correctly. When I call the script via a browser there are no errors shown (I have them enabled), but when I run it in CLI it get's into a loop with the following errors:
Warning: in_array() expects parameter 2 to be array, null given in /var/www/html/script.php on line 169
Exclusion not found<br>
Warning: fgetcsv() expects parameter 1 to be resource, boolean given in /var/www/html/script.php on line 165
and just repeats itself...
Line 169 is if( in_array( $match ,$line ) )
Line 165 is while (($line = fgetcsv($file)) !== FALSE) {
if ($check_list == "1") {
$file = fopen('list.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
print_r($line);
if( in_array( $match ,$line ) )
{
echo "match found";
$name = $line[0];
$address = $line[1];
$phone = $line[2];
echo "name : " . $name;
echo "address : " . $address;
echo "phone : " . $phone;
}
else {
echo "Not found in file.";
}
}
fclose($file);
}
I'm a bit stuck as to why it is behaving this way via CLI, but not via browser (that I can see).
Thanks in advance.
There are many differences in environment when you run the script through web browser compared to the cli.
When you use relative path in your script and run the script through cli, php will consider the file you are searching is relative to your current working directory. For example, if your current working directory is
/home/
and your script and file resides in the scripts directory
/var/www/html/script.php
/var/www/html/list.csv
When you run
php -f /var/www/html/script.php
or
php -f ..var/www/html/script.php
PHP will be searching the file relative to your working directory as
/home/list.csv
which doesn't exist. I first encountered such issue when I was trying to run PHP scripts from crontab which caused all relative path to break. So, it is either you change your working directory to /var/www/html/
or just use absolute path, in your case
$file = fopen('/var/www/html/list.csv', 'r');