PHP で file_put_contents($file, ob_get_contents()) 関数を使用して、動的フォームによって生成されたファイルのスナップショットを作成し、ファイルの内容をサーバーに保存しています。それは非常にうまく機能していますが、同じ名前のファイルが既に存在する場合、上書きするかどうかをユーザーに尋ねたいと思います。AJAX では、非表示の入力フィールドを介してファイルの名前を渡すことができましたが、ファイルの内容を渡すことができませんでした。他にもっと簡単な代替手段があれば、AJAX は必要ありません。
$ fileは、フォームによって生成されるファイルの名前です。
if(file_exists($file))
{
echo '<div style="background:#000; padding:10px"><center style="color:#fff">File aready exists! ';
echo '<button type="button" onclick="loadXMLDoc()">Overwrite it!</button><div id="myDiv"></div></div><input type="hidden" id="hiddenfile" value="'.$file.'"></center>';
}
else{
file_put_contents($file, ob_get_contents());
echo '<div style="background:#000; padding:10px"><center><a href="'."/newslettercms/webversion/".$file.'" download style="color:#fff;">Click here to download the newsletter</a> • <a href="'."/newslettercms/webversion/".$file.'" target="_blank" style="color:#ddd">View web version</a></center></div>';
}
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
var hiddenfile=document.getElementById("hiddenfile").value;
xmlhttp.open("GET","inc/overwrite.php?hiddenfile="+hiddenfile,true);
xmlhttp.send();
}
</script>
Overwrite.php
<?php
$file=$_GET['hiddenfile'];
file_put_contents($file, ob_get_contents());
echo '<div style="background:#000; padding:10px"><center><a href="'."/newslettercms/webversion/".$file.'" download style="color:#fff;">Click here to download the newsletter</a> • <a href="'."/newslettercms/webversion/".$file.'" target="_blank" style="color:#ddd">View web version</a></center></div>';
echo "File overwritten success!";
?>