March 25, 2012

codeIgniter -How to access a text file from a model

Question by user225269

I’m trying to access the mime.types file from a model in codeIgniter.

function get_mime_type($filename, $mimePath = '../../assets'){ 
        $fileext = substr(strrchr($filename, '.'), 1); 
        if (empty($fileext)) return (false); 
        $regex = "/^([w+-./]+)s+(w+s)*($fileexts)/i"; 
        $lines = file("$mimePath/mime.types"); 
        foreach($lines as $line){ 
            if (substr($line, 0, 1) == '#') continue; // skip comments 
            $line = rtrim($line) . " "; 
            if (!preg_match($regex, $line, $matches)) continue; // no match to the extension 
                return ($matches[1]); 
        } 
        return (false); // no match at all 
    } 

I’ve already tried the following when I call it:

$this->get_mime_type($filename, $mimePath = '../../assets');

$this->get_mime_type($filename, $mimePath = '/zenoir/assets');

$this->get_mime_type($filename, $mimePath = 'http://localhost:8080/zenoir/assets/mime.types');

But no luck. The mime.types file is in the assets folder and the model is inzenoir/application/models
enter image description here

The error was:

A PHP Error was encountered

Severity: Warning

Message: file(../../assets/mime.types) [function.file]: failed to open stream: No such file or directory

Filename: models/files.php

Line Number: 46

Answer by Starx

Why are you getting into so much trouble for the mime types, use mime_content_type() instead.

echo mime_content_type($mimePath.$filename);

And the problem with your code is the path issue. Use BASEPATH constant and traverse from there instead. You will omit all these sort of path issue.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!