Search code examples
javascriptphphtmlserverserver-side

How do I create a new .html webpage onclick?


What I want to do is when the user clicks my html button I want to dynamically create a new webpage on the server. I need the url of the new webpage to have it's own url, that is, it should be different from each other.

In more detail: When the user clicks the button I want to upload a new .html file to the server. So for example if I have a website called www.check.com/index.html when the user clicks the button in the index.html I need to create a new .html that contains some html lines (but no CSS, nothing will be shown on the page). So when the user clicks the button I want a file to be upload to the server with a unique url like www.check/1.html, the second time it'll be check.com/2.html and so on.. I'm fine with it being 1.html, 2.html and so on.

Javascript code:

 function makePage(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
    alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = "<html><head></head><body><meta name=\"twitter:card\" content=\"summary_large_image\"><meta name=\"twitter:site\" content=\"@nytimes\"><meta name=\"twitter:creator\" content=\"@SarahMaslinNir\"><meta name=\"twitter:title\" content=\"Parade of Fans for Houston’s Funeral\"><meta name=\"twitter:description\" content=\"Blah Blah Blah content.\"><meta name=\"twitter:image\" content=\"\"><script>document.getElementById(\"imgTweet\").innerHTML.write(img);</script></body></html>";
xmlhttp.open("GET","makePage.php?content=" + content,true);
xmlhttp.send();}

'img' is a variable in a different page of mine. The webpage gets created by the code is not executed.


Solution

  • You must use AJAX to execute php. Creating new file in php is really simple with file_put_contents().

    here is an example:
    makePage.html:

        <html>
        <body>
        <button onclick="makePage()">click</button>
        <script src="makePage.js">
        </script>
        </body>
        </html>
    

    makePage.php:

    <?php
    $content = $_GET["content"];
    $file = uniqid() . ".html";
    file_put_contents($file, $content);
    echo $file;
    ?>
    

    makePage.js

    function makePage(){
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
            alert("webpage " + xmlhttp.responseText + " was successfully created!");
        }
        var content = "<html><head><meta charset=\"utf-8\" /> </head><body>new website<script>alert(\"test\")</script></body></html>";
        xmlhttp.open("GET","makePage.php?content=" + content,true);
        xmlhttp.send();
    }
    

    hope this will help