When you run the script through Apache, it will run as a different user ID than you are (presumably) using on the command line. Are you sure that the user ID that Apache uses has the proper access to that file. For instance on Ubuntu, Apache runs as user www-data: does user www-data have access to the file?