Most likely you have file owner/permission problems. When you execute script in browser it is exectuted as user www-data (or whatever your user is). When you run from command line you run it as yourself, which is another user.
Either change file permissions or run your script from web user, for example
sudo -u www-data php yourscriptname.php