I’ve got a really bizarre problem here. I’m using the code below to upload a txt file to my server via php.
<form enctype="multipart/form-data" action="index.php" method="POST">
<input type="file" name="uploadfile">
<button>Submit</button>
</form>
After uploading the file (which works fine) I convert the contents into an array via the following code:
$fp = @fopen($file, 'r');
if ($fp) {
$domains = explode("\n", fread($fp, filesize($file)));
}
Then I run a preg_match to filter down the array:
$list = preg_grep('/^[a-z]+\.com$/', $domains);
I confirmed that $domains is getting populated with the data in the txt file, however when I run print_r($list) it’s only returning “array( )”
When I upload the same exact text file with FTP and run print_r($list) it works fine.
I also noticed when I upload the same text file with my FTP client the filesize of “domains.txt” is smaller than when I upload it using my html form. Any idea what’s going on here?
This may have to do with line endings being automatically changed between UNIX and Windows by your FTP client.
To resolve this, just use
trimto cleanse every line before usingpreg_grep. Something like:The problem would be because your regular expression has explicit start-of-line and end-of-line anchors.
BTW you could load up the whole file into an array of lines in one statement by just using the
filefunction.