You will need to make sure that the directory you are writing to allows for www-data to write to it. Typically, you will want to put that directory in a place that is away from other files etc…
sudo chown www-data:www-data <DIRNAME>
sudo chmod -R g+w <DIRNAME>
For changing owner :
sudo chown -R <owner name > <dir name>
For globally set write permission fro www-data user :
sudo chown -R www-data:www-data /var/www
sudo chmod -R g+rw /var/www