Search code examples
phpfopenfreebsdlighttpd

PHP fopen() returns NULL, always


I'm attempting to open a file for parsing (a binary file), however no matter what fopen() is always returning NULL.

I've ruled out nearly everything to the point where I have a test script with simply:

<?php
$idx = fopen('/usr/home/username/web/appname/dev/www/debug/18194001.idx','r');
trigger_error(var_export($idx,true));
exit();

The output from trigger_error(var_export()); is:

[31-Mar-2013 16:30:34 UTC] PHP Notice:  NULL in /usr/home/username/web/appname/dev/www/debug/ajax.idx.php on line 3

No matter what flags I specify for the second fopen() option, I get the same result.

Now, the obvious question is whether or not the file exists, and do I have permissions to read it? The answer to both of those is yes. I've used the relative path and absolute path, both read the file correct. file_get_contents() also reads the file with no issues.

is_readable() and file_exists() both return true

The output of ls -lah for that file is:

-rwxrwxrwx   1 username  username  2.0K Mar 30 15:02 18194001.idx

Where 'username' matches the username the web server process and PHP (lighttpd and php-fpm) are running under. The parent directory also has read/read/read rights for user/group/all.

I've tried other files, and I've noticed pretty much anything I throw at fopen is returning a NULL value.

Help?

PHP info:

PHP 5.4.6 (cli) (built: Oct 10 2012 10:43:19)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
    with XCache v2.0.1, Copyright (c) 2005-2012, by mOo

Lighttpd info:

lighttpd/1.4.31 (ssl) - a light and fast webserver
Build-Date: Sep  7 2012 15:38:20

OS:

FreeBSD hostname.hostname.hostname 8.2-RELEASE FreeBSD 8.2-RELEASE #0: Thu Feb 17 02:41:51 UTC 2011     [email protected]:/usr/obj/usr/src/sys/GENERIC  amd64

Solution

  • You cannot meaningfully var_export a fopened resource, you can however var_dump it:

    $ php -r 'var_export(fopen("/tmp/a","w+"));'
    NULL
    $ php -r 'var_dump(fopen("/tmp/a","w+"));'
    resource(5) of type (stream)
    

    ... because var_export() is meant to 'restore' a variable in PHP script, and resources require more setup then possible in instantiating a simple variable. If you want to know whether the fopen succeeded, just check it is not false.

    $ php -r 'var_export(fopen("/this/does/not/exist","w+"));'
    ... some errors...
    false
    

    In other words, the fact you get NULL from a var_export means the fopen actually was successful.