简体   繁体   中英

Issue saving file with PHP script

I'm making a PHP script for a JavaScipt site I've made.

The goal is to save the contents of a string as an HTML file when I click a button.

I'm using jQuery to make a Post request.

I'm using an Ubuntu OS with an Apache 2 server. The folder I'm writing to has permissions 777 (for testing only, will repeal this).

A requirement is the PHP must live in another file.

The issue is whenever I make the request, the file saves blank.

A requirement is each filename must be a timestamp. The file has the correct file name, but not contents.

So far, here is my code:

<?php

$fileName = $_GET['fileNameData'];
$htmlImport = $_GET['htmlToSaveData'];

$htmlToSave = (string)$htmlImport;

$myFile = fopen($fileName, "w") or die('You do not have write permissions');

//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave); 
fclose($myFile);

?>

I've tried the frwite function that I've commented out, same effect.

I have tested this in terminal by passing in arguments ($argv[1] and $argv[2]). That works fine.

The JS I've made to run my site looks like:

var newURL = 'saveHTML.php/?fileNameData=' + fileName + '&htmlToSaveData=' + htmlToSave
$.post(newURL)
    .done(function(){
        alert('Your file saved as ...' + htmlToSave)
    })

I've also tried this code, with the same result:

$.post('saveHTML.php/', {
    fileNameData : fileName,
    htmlToSaveData : htmlToSave
})

Both the fileName and htmlToSave are strings, although htmlToSave is rather long and is actually html text that I've converted to a string.

Does anyone have ideas about what's going on here? I'm not a PHP developer at all.

I'm using a callback so I can be sure I've collected all my html before I pass the string to PHP.

I've read and tested the recommendations on this question here and this has been fruitless.

EDIT Don't be alarmed about the code, I realise it's a security issue but this is a learning project and this will not be in production.

I can see right off the bat that you have

$myFile = fopen($fileName, "w") or die('You do not have write permissions');

//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave); 
fclose($myFile);

file_put_contents takes a file name, not a handle. So you would only need

file_put_contents($fileName, $htmlToSave);

Edit: I also feel like I should point out that you should not allow your users to name your files. They could potentially do some nasty stuff to your machine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM