phpmongodb

Regex MongoDB PHP Query


I'm looking to perform a REGEX on a MongoDB find query that only finds anything with image in the string, what its searching is a filetype header so it would generally looked like image/png or text/html.

I am running this code for the regex:

array('fileType'=>array('$regex'=>'^image'))

And this code alltogether:

foreach ($this->grid->find(array('fileType'=>array('$regex'=>'^image'))) as $file) {
                        $id = (string) $file->file['_id'];
                        $filename = htmlspecialchars($file->file["filename"]);
                        $filetype = isset($file->file["filetype"]) ? $file->file["filetype"] : 'application/octet-stream';

                        if($filetype == 'image/'.$chosenfile.''){
                            $links[] = sprintf('<img src="lib/download.php?id=%s" height="200px" width="200px">', $id);
                        }elseif($chosenfile == ''){
                             $links[] = sprintf('<img src="lib/download.php?id=%s" height="200px" width="200px">', $id);
                        }
                    }

Solution

  • This is your problem:

    array('$regex'=>'^image')
    

    It should be using the MongoRegex object:

    array('fileType' => new MongoRegex('/^image/i'))
    

    The documentation is defined here: http://www.php.net/manual/en/class.mongoregex.php

    Does it work now?