The issue is the permissions on your machine where the PHP script is running from.
You have to first determine which user the script is running from (it is from apache, the command line, by user apache, by user www-data, by vhost user…)
Then you need to make sure the directory where the script is running from has the correct file permissions and ownership.
As an example, you may find that you set the system up and therefore the directory and files are owned by you, or root. When apache runs, it is running ad user www-data, which had no permission to create the file in the directory tree.
Providing more information that you did will help others help you.