I have a static HTML site that I want to deploy through Cloudflare Pages.
I heard we can run PHP during build time in Cloudflare Pages and I don’t want to edit the headers/footers of all pages one by one so I made headers.php and footers.php and included them in index.php as below:
<?php
include 'header.php';
.
Other codes here
.
include 'footer.php';
?>
It is working well on my local server. But while I try to deploy it to Cloudflare pages - it isn’t working.
Can you please tell me how can I render the output to index.html? My index.php is as follows. I have HTML codes inside header.php, body-index.php and footer.php
<?php
include 'header.php';
include 'body-index.php';
include 'footer.php';
?>
I’m not really sure what the best way to do that in PHP would be, and if you don’t know, you probably should start with a static site generator that’s already written for you. The ones that are supported out of the box on Pages are listed here.
If you want to do the PHP yourself you would probably have to write a script to do it file-by-file and put the output into the build folder. This doesn’t sound fun, but there’s nothing Cloudflare-special about it so whatever you find about generating static HTML files from PHP should work.
I wrote this bash script to do what you want to achieve, if you or anyone finding this later still wants to use PHP as their templating engine for static site generation. It assumes you have your running PHP site in the /public folder, and will use the /release folder for generated output.
Paste the script below into a file in the root of your project, like build.sh (you might have to run chmod +x build.sh on that file after creating). Test it, and if it works, you can deploy.
To deploy, when configuring your Cloudflare Pages project, indicate that the build command is ./build.sh and that the build output directory is /release.
Here’s the script I use:
#!/bin/bash
rm -rf release
cp -r public/ release/
find release -type f -name '*.php' -delete
find public -type f -name '*.php' | while read file; do
release_file=$(echo "$file" | sed -e 's/public/release/' -e 's/\.php$/.html/')
currentdir=$(pwd)
mkdir -p "$(dirname "$release_file")" && \
(cd "$(dirname "$file")" && php -f "$(basename "$file")" > "$currentdir/$(dirname "$release_file")/$(basename "$release_file")")
done