Save File with Ajax and PHP
Today, I am going to go over a simple example of saving content from a web page to your server. Imagine a textarea with a save button, which grabs the text from the user input and sends it to your server. There PHP grabs the data and writes it into a unique file. Our php script will respond to the Ajax request with the file name in a link so that the end user can retrieve it directly through another web request.
Lets start with the front-end, which is just a simple page that has a textarea, a button, and an Ajax request that drops the response into a regular div element on the page. Here is our index.html page:
Notice that I am adding a “Content-type” request header to the XMLHttpRequest request. Without it, the PHP script was not picking up the POST data parameter. I did not need to add this manually with a jQuery Ajax request so it’s important to remember this “application/x-www-form-urlencoded” content type header with XHR.
Now, to setup the backend, we need to create a new directory (mkdir files) and give it writable and readable permissions (chmod 777 files). Next, we need to create a new php script (save.php) that will read the data coming from our Ajax request. If the request to the PHP file has data, we create a unique filename in PHP with a combination of uniqid() and getmypid().
tempnam is a good alternative but it does not support custom extensions. We will save our file with a txt extension for plain text and I used the fopen and fwrite PHP functions to write the file to the filesystem. Finally, we print the filename as the Ajax response and here you can see the full php save script:
Check out a demo of this code here
Update: If you are using a database to store a record that links to the file, it makes sense to use an auto incremented ID for uniqueness and short unique URLs via hashids. Also, if you are uploading files and not string it makes sense to use php $_FILES and send the Ajax request with proper FormData which has a blob.