Search code examples
phpfile-upload

Uploading and writting files to Ubuntu EC2 Instance


I am new to AWS and now I have an issue. I am developing a mobile app that uses PHP files as web services to query a MySQL database. PHP files and MySQL are hosted on a AWS EC2 instance. I have no problem accessing the PHP files from my mobile app. The issue I have now is that I need to upload a file from the app to the server.

Here you have the PHP file that is used to receive and save the file to the server:

<?php
  $image = $_POST['image'];
  $name = $_POST['name'];
  $realImage = base64_decode($image);
  
  file_put_contents($name,$realImage);
  echo "OK";
?>

In the app I am receiving the response "OK" , but the file is not saved to the server folder. I guess this is a matter of permissions. I can access the server through FTP. I gave the permissions to the ubuntu instance user as follows:

sudo chown -R ubuntu:ubuntu /var/www/html
sudo chmod -R 755 /var/www/html

But I don´t know what should I do to let me upload files from the app to the server without issues.


Solution

  • First, and very important, the question doesn't have anything to do with AWS. You have Ubuntu server that runs web server and PHP and you can't upload a file in your application.

    Second, you are tinkering with permissions in /var/www/html. That is not where the file is uploaded. The location is controlled by upload_tmp_dir in your php.ini. By default the location is system temp directory. Uploading user files into web root is a very bad security practice. What prevents a mailicious user to upload some script, and then access it from the browser and execute it?!

    Finally, if your upload_tmp_dir is pointing to some non-default location, it needs to be writeable by web server. Is your web server running as ubuntu? It's usually apache or nginx, depending what web server you are running

    Take a look at this example that combines client and server-side code