Search code examples
phpdisk

how to open a file while inside a foreach(glob....PHP


I have a small number of image files and text files. They have the same file name with different extensions. I need to read the image files and for each image I need to read some (tool top) text from the corresponding text file. The problem is the file open inside the "foreach( glob("inserts/*.png")" loop fails. I have output the filename and the fopen works fine. I thought it may be you are unable to open two file concurrently in PHP but I could find nothing about it when I googled

foreach( glob("inserts/*.png" ) as $filename ) {
   $path="public/xml/iweb/".$filename;
   $insertpath=substr($filename, 0, -3)."txt";
   $myfile = fopen($insertpath, "r");
   $rec=fread($myfile,filesize($insertpath));
   fclose($myfile);
   $name=getInnerSubstring($rec,"-");
   $HTML5.="<img class='insertimage' src='".$path."' title='".$name."' onclick='insertcomponent(\"".$insertpath."\")'>";
}

One day I hope I know enough to answer questions instead of just asking them. :(


Solution

  • There's no reason why you shouldn't be able to open multiple files and no reason the foreach should break anything that works. My hunch is that the path you're trying to open is wrong. I suggest either debugging the code to see the variables or add an echo to see their content. You should also check if fopen() and fread() don't return some false because they failed. Good luck :)