invalid arguments foreach in php in commandline - php

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("\n", 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("\n", fread($fp1, filesize($filename1)));
}
$num = 1;
foreach($array1 as $val1)
{
foreach($array as $val)
{
if(strstr($val1, $val))
{
print_r('\n'); //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?

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.

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.

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("\n", 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.

Related

fopen is duplicating the same line

I have a file that looks like this:
1||Allan||34||male||USA||||55.789.980
2||Georg||32||male||USA||||55.756.180
3||Rocky||21||male||USA||[100][200]||55.183.567
I made a function that when executed adds a given number or removes it if already present, which is $added and equals 100 for this example. This is my code:
$added = $_GET['added']; //100 for this example
$f = fopen($file, "w");
$list = file($file);
foreach ($list as $line) {
$details = explode("||", $line);
if (preg_match("~\b$details[0]\b~", 3)) {
foreach ($details as $key => $value) {
if ($key == 5) {
$newline .= str_replace("[" . $added . "]", "", $value);
} else {
$newline .= $value . "||";
}
}
$line = $newline . "\n";
}
fputs($f, $line);
}
fclose($f);
}
this code is supposed to remove the [100] from the Rocky line since its already present which it kinda does. However, upon further execution instead of adding it back it duplicates the Rocky line and messes it up so the file looks like this:
1||Allan||34||male||USA||||55.789.980
2||Georg||32||male||USA||||55.756.180
3||Rocky||21||male||USA||[100][200]55.183.567
3||Rocky||21||male||USA||[100][200]55.183.567
||
||
why is it doing this? I cant make any sense out of it...
Thank you.
First, you should read the file before you open it for output, because opening with the w mode truncates the file.
Second, you don't need to loop over the fields in $details if you just want to change one of them. Just access and assign it by index.
Then you can put the line back together with implode().
$list = file($file);
$f = fopen($file, "w");
foreach ($list as $line) {
$details = explode("||", $line);
if (preg_match("~\b$details[0]\b~", 3)) {
if (strpos("[$added]", $details[5]) === false) {
$details[5] = "[$added]" . $details[5];
} else {
$details[5] = str_replace("[$added]", "", $details[5]);
}
$line = implode('||', $details)
}
fputs($f, $line);
}
fclose($f);

How to get last 1000 lines from a large file then remove them?

Solved on 2 steps:
Get the lines: https://stackoverflow.com/a/51350572/8524395
Remove the lines after getting them: https://stackoverflow.com/a/51377052/8524395
I have a large file, I want to take 1000 lines from the end of this file, then remove them.
I am currently using this:
function deleteLineInFile($file,$string)
{
$i=0;
$array=array();
$read = fopen($file, "r") or die("can't open the file");
while(!feof($read)) {
$array[$i] = fgets($read);
++$i;
}
fclose($read);
$write = fopen($file, "w") or die("can't open the file");
foreach($array as $a) {
if(!strstr($a,$string)) fwrite($write,$a);
}
fclose($write);
}
$goods = '';
$file = file("../products/".$PidFileName);
for ($i = max(0, count($file)-1001); $i < count($file); $i++) {
$goods = $goods.$file[$i] . '<br />';
deleteLineInFile("../products/".$PidFileName, $file[$i]);
}
I want to save the lines which I got in $goods
However, it times out because of the file size.
If you want to get N lines from EOF, you can use SPLFileObject (added in PHP 5.1):
$num_to_cut = 1000; // must be an integer and not a string
$new_file = new SplFileObject("limited_test.txt", "w");
$old_file = new SplFileObject('test.txt');
// here we get count of lines: go to EOF and get line number
$old_file->seek($old_file->getSize());
$linesTotal = $old_file->key()+1;
// and write data to new file
foreach( new LimitIterator($old_file, $linesTotal-$num_to_cut) as $line) {
$new_file->fwrite($line);
}
To remove the lines after getting them from a LARGE file:
The best way to do that is to use sed | But if you don't have access to use the exec() function then this is a function that you can use.
function replace_file($path, $string, $replace)
{
set_time_limit(0);
if (is_file($path) === true)
{
$file = fopen($path, 'r');
$temp = tempnam('./', 'tmp');
if (is_resource($file) === true)
{
while (feof($file) === false)
{
file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
}
fclose($file);
}
unlink($path);
}
return rename($temp, $path);
}
Source of the function: https://stackoverflow.com/a/2159135/8524395
To remove the line use it like that:
replace_file('myfile.txt', 'RemoveThisPlease', '');
If you used MrSmile's answer to get the lines, then replace "RemoveThisPlease" with $line

How to update files in PHP

I have some PHP function that requires the line number of a CSV file used as database. Once it has line, it navigates to the specific value that needs to be changed, changes it and rewrites the whole files. Here is my code:
<?php
function update($file, $id, $field, $value)
{
//$id is the line number
$contents = explode("\n", file_get_contents($file));
$fh = fopen($file, "w");
$lines = array();
foreach($contents as $line)
{
if($line == "")
continue;
$fields = explode("|", $line);
if($fields[0] == $id)
{
$line = null;
for($i = 0; $i<count($fields); $i++)
{
if($i == $field)
$fields[$i] = $value;
if($i != count($fields)-1)
$line .= $fields[$i]."|";
else
$line .= $fields[$i];
}
}
$line .= "\n";
fwrite($fh, $line);
}
fclose($fh);
$contents = null;
return true;
}
$id = $_SESSION['id'];
$uid = $_GET['p'];
$myfile = "myfile.txt";
if(update($myfile, 12, 14, "somevalue"))
echo "updated!";
?>
I am unable to find the problem because whenever I run the code, it outputs "updated!" just as it should but when check the file, I find it has not been updated. I do not know why, but it always remains the same! Thanks.
Check that fwrite() is not failing.
Do something like this:
...
$writeSuccess = (fwrite($fh, $line) !== false);
}
fclose($fh);
$contents = null;
return $writeSuccess;
}
...
If it is failing, check that your filesystem permissions are correctly set. The Apache user needs to have write access to whatever file/folder you are writing the file to.
I found out what the problem was.
$id = $_SESSION['id'];
$uid = $_GET['p'];
$myfile = "myfile.txt";
if(update($myfile, 12, 14, "somevalue"))
The line number pointed to the previous line, which made it impossible to update the first line of the file. So all I had to do was
$line ++;

PHP program will run and echo out nothing

I made a script that reads data from a .xls file and converts it into a .csv, then I have a script that takes the .csv and puts it in an array, and then I have a script with a foreach loop and at the end should echo out the end variable, but it echos out nothing, just a blank page. The file writes okay, and that's for sure, but I don't know if the script read the csv, because if I put an echo after it reads, it just returns blank.
Here my code:
<?php
ini_set('memory_limit', '300M');
$username = 'test';
function convert($in) {
require_once 'Excel/reader.php';
$excel = new Spreadsheet_Excel_Reader();
$excel->setOutputEncoding('CP1251');
$excel->read($in);
$x=1;
$sep = ",";
ob_start();
while($x<=$excel->sheets[0]['numRows']) {
$y=1;
$row="";
while($y<=$excel->sheets[0]['numCols']) {
$cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
$row.=($row=="")?"\"".$cell."\"":"".$sep."\"".$cell."\"";
$y++;
}
echo $row."\n";
$x++;
}
return ob_get_contents();
ob_end_clean();
}
$csv = convert('usage.xls');
$file = $username . '.csv';
$fh = fopen($file, 'w') or die("Can't open the file");
$stringData = $csv;
fwrite($fh, $stringData);
fclose($fh);
$maxlinelength = 1000;
$fh = fopen($file);
$firstline = fgetcsv($fh, $maxlinelength);
$cols = count($firstline);
$row = 0;
$inventory = array();
while (($nextline = fgetcsv($fh, $maxlinelength)) !== FALSE )
{
for ( $i = 0; $i < $cols; ++$i )
{
$inventory[$firstline[$i]][$row] = $nextline[$i];
}
++$row;
}
fclose($fh);
$arr = $inventory['Category'];
$texts = 0;
$num2 = 0;
foreach($inventory['Category'] as $key => $value) {
$val = $value;
if (is_object($value)) { echo 'true'; }
if ($value == 'Messages ') {
$texts++;
}
}
echo 'You have used ' . $texts . ' text messages';
?>
Once you return. you cannot do anything else in the function:
return ob_get_contents();
ob_end_clean();//THIS NEVER HAPPENS
Therefore the ob what never flushed and won't have any output.
I see a lot of repetitive useless operations there. Why not simply build an array with the data you're pulling out of the Excel file? You can then write out that array with fputcsv(), instead of building the CSV string yourself.
You then write the csv out to a file, then read the file back in and process it back into an array. Which begs the question... why? You've already got the raw individual bits of data at the moment you read from the excel file, so why all the fancy-ish giftwrapping only to tear it all apart again?

PHP : POST-- How to replace defined KEY from ARRAY in a file

I'm a bit lost for I'm "green" in PHP.
Please, may you teach me how to fix this:
on 'POST' --> Replace a specified array key from a file:
(WRONG:)
<?php
$newData = $_POST["sendData"];
if(isset($_POST['sendData'])){
$file = fopen('fileToOpen.php', 'a');
foreach($file as $key => $val)
{
$data[$key] = explode("|", $val);
}
for($k = 0; $k < sizeof($file); $k++)
{
unset($data[$k][3]);
}
$data[$k][3] = "$newData";
fwrite($file, $data[$k][3]);
fclose ($file);
}
?>
That's wrong as it continues to write:
data1|data2|data3|oldDatanewData
instead of rewrite:
data1|data2|data3|newData
Is there any other technique to achieve something similar? Perhaps with file_put_contents? Am I missing implode?
Thanks!
Dunno what are you asking for but perhaps you only need to serialize and unserialize the array.
$data_array = unserialize(file_get_contents('fileToOpen.php'));
$data_array[$key_you_want_to_change] = $new_data;
file_put_contents('fileToOpen.php', serialize($data_array));
$newData = $_POST['sendData'];
if(isset($_POST['sendData'])){
$file = "fileToOpen.php";
$oldData = file_get_contents($file);
$oldData = eregi_replace("\n","",$oldData);
$FullDataArray = explode("?",$oldData);
$oldDataArray = explode("|",$FullDataArray[1]);
$oldDataArray[3] = $newData;
$newDataString .= "
foreach($oldDataArray as $key=>$val) {
$newDataString .= $val;
if($key!="3") {
$newDataString .= "|";
}
}
$fh = fopen($file, 'w');
fwrite($fh,$newDataString);
fclose($fh);
}
?>

Categories