15

I would like to generate a static html page from a php file and save it from an other php script. That script runs a bunch of echo functions, which when viewed in a browser is a nice html page. But when I run file_get_contents it opens that file as a file on the filesystem, not as a file in an url.

Do I need to call file_get_contents in a localhost/site/categories.php way? How can I get this path? This is the wrong code:

<?php
$file = file_get_contents("categories.php");
file_put_contents("categories.html", $file);
?>

6 Answers 6

15

To get the finished output, you need to use the PHP url wrappers functionality and request it over the webserver. Then it's as easy as:

copy("http://localhost/site/categories.php", "categories.html");
Sign up to request clarification or add additional context in comments.

2 Comments

Works great! :) to clarify a bit further: the second parameter must be an absolute path for example: /home/user/public_html/html_at_root.html. Something that I didn't manage to do is to pass additional parameters such as session data so I just passed them with GET method in the first parameter. I wonder if there is a better way to do this...
I used this function, my file get locked and lock do not open
11

Yes - run file_get_contents in a localhost way - if your server is configured correctly, it will not trek off to the internet and will get your results in an efficient manner, even when hosted on your own domain name.

<?php
$file = file_get_contents("http://yourserver.com/site/categories.php");
file_put_contents("categories.html", $file);
?>

1 Comment

Works in my host's environment, whereas "copy()" approach does not, whether used with explicit domain or localhost.
2

I believe you can simply:

$file = file_get_contents("http://localhost/site/categories.php");

However, the fopen wrappers must be enabled for file_get_contents() to read URLs.

Comments

1

I wouldn't use php to accomplish for security reasons. A better approach would be to use ssh to copy the file to the desired remote server:

php script.php | ssh you@remotehost "cp - /path/to/static/file.html

Comments

0

I may be missing the point here, but it might also be an idea to include() the other PHP file and simply use it to create the output directly on demand instead of involving the webserver at all for that stage in the process.

Comments

0

For me its being used by a webhook to create another file thats API driven. Its used to reduce the number of API requests.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.