0

I am developping an online photo database (with php and mysql), and I have a download function and an upload function. The download function works like a charm, it's also not hard at al to download a file from a server.

I was just wondering if it is possible (in php) to recieve a file, but not with the usual html form where you select a file.

E.G. If I want to upload the file "Photo.png", the software converts the image to a base64 string, and than sends it to the php script save.php?base=[BASE64]&&filename=[FILENAME]

How would I make the script reconvert that string into an Photo.png and then save it into the folder /img/?

Thank you in advance, Caspar.

questionman
  • 119
  • 2
  • 9
  • "but not with the usual html form where you select a file" So how _are_ you selecting the file to upload? – Patrick Q Dec 17 '18 at 17:54
  • @Patrick Q You don't, You've already converted the file you want to send to the server to a base64 string, and you're passing that string to the server. – questionman Dec 17 '18 at 17:58

2 Answers2

1

It would be as simple as

$data = base64_decode($_GET['base']);
file_put_contents($_GET['filename'], $data)

before you can check if these keys exist and they aren't empty and also you don't need double & in the url

Robert
  • 19,800
  • 5
  • 55
  • 85
1

Some info to help you out:

  1. Yes, you can indeed receive data in any form and do with it what you will. In your example, you can send a photo base64-encoded in a query string and use base64_decode($_REQUEST['base']) or base64_decode($_GET['base']) to get at it.

CAVEAT: In the past, a lot of web servers place limits on the size of the query string it will process - not sure it's as much of a concern these days though. Check the web server you'll be using to confirm it's ok. You may want to consider sending the file via POST, in which case you may not necessarily even need to encode it in base64.

  1. I noticed you're sending along the filename as part of the query string. If you use this, BE VERY CAREFUL TO SANITIZE IT FIRST. Check to make sure it doesn't have forward slashes or other special characters so that someone can't arbitrarily save a binary file anywhere on your server. Many PHP frameworks can handle this for you out of the box, or check out this one for more straight-PHP filtering options you could use: string sanitizer for filename
steglasi
  • 11
  • 1
  • That's a great caveat. Might be good to include a reference, like [this answer](https://stackoverflow.com/a/2659995/1072112) which describes an 8KB limit in some web servers. In addition to clients and servers, middleware like HAProxy may be part of an environment that enforces limits without developers even knowing. – ghoti Dec 17 '18 at 21:37
  • Thank you for your comment. It was very usefull information and I'll be sure to sanitize the input. – questionman Dec 18 '18 at 11:33
  • you should always do that with any kind of input, filter, validate and sanitise – Robert Dec 18 '18 at 11:58