PHP Examples
This guide explains, in a simple step-by-step manner, how to implement GridlessBuilder.js in PHP to create a simple CMS application.
Example file: example1.php
We will start by creating a simple PHP page for displaying content from MySQL database.. First, we create a table called pages to store our web pages’ content. The table consists of the following fields:
Then, we insert a few sample records:
id | filename | title |
1 | index | Home |
2 | about | About |
Now we can display our page by running a query based on a given filename. For example, to get About page:
$filename = 'about'; $sql = 'SELECT * FROM pages where filename= :filename'; $s = $pdo->prepare($sql); $s->bindValue(':filename', $filename); $s->execute(); if($row = $s->fetch()) { $id = $row['id']; $title = $row['title']; $description = $row['description']; $content = $row['content']; $css = $row['css']; $js = $row['js']; }
To display a web page with the data ($title, $description, $content, $css, $js) we use a simple HTML structure below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $title; ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="<?php echo $description; ?>">
<!-- Gridless CSS framework -->
<link href="assets/gridless/gridless.css" rel="stylesheet" type="text/css" />
<!-- Stylesheet -->
<style id="_content_css">
<?php echo $css; ?>
</style>
</head>
<body style="touch-action: pan-y">
<!-- Content -->
<div class="is-wrapper">
<?php echo $content; ?>
</div>
<!-- Gridless CSS framework -->
<script src="assets/gridless/gridless.js"></script>
<!-- JavaScript -->
<script id="_content_js">
<?php echo $js; ?>
</script>
</body>
</html>
As our content will be created using GridlessBuilder.js, we also need to include Gridless CSS framework. As seen, we include two files: gridless.css and gridless.js.
For complete code and to try the example, please open in your browser: example1.php.
Example file: example2.php.
To use GridlessBuilder.js, include the following css in the <head> section:
<link href="dist/gridlessbuilder.css" rel="stylesheet" type="text/css" />
And include the following scripts before the end of the <body> tag.
<script src="assets/lang/en.js"></script> <!-- optional language file --> <script src="dist/gridlessbuilder.min.js"></script>
gridless.css
gridlessbuilder.css
gridlessbuilder.js
gridless.css
gridless.js
Important: when using GridlessBuilder.js for editing, we don’t need to include grildless.js. It is used only for viewing content (in production).
In our CMS, we will use AJAX to submit the edited content for saving, but for now, let’s see how to use a simple HTML form to submit the content.
<form id="frmContent" method="post" enctype="multipart/form-data"> <input id="hidId" name="hidId" type="hidden" value="<?php echo $id; ?>" /> <input id="hidContent" name="hidContent" type="hidden" /> <input id="hidCss" name="hidCss" type="hidden" /> <input id="hidJs" name="hidJs" type="hidden" /> </form>
This form has 4 hidden fields for storing the page id, contentn css and js. We already have the id for our page(see step 1).
Now we initialize GridlessBuilder.js for editing content inside <div class=”is-wrapper”>.
<script> var obj = new GridlessBuilder({ wrapper: '.is-wrapper', onSave: function() { var html = obj.html(); var css = obj.styles(); var js = obj.js(); document.querySelector('#hidContent').value = html; document.querySelector('#hidCss').value = css; document.querySelector('#hidJs').value = js; document.querySelector('#frmContent').submit(); } }); </script>
Inside the onSave function, we get the edited content, css and js using html(), css() and js() method. Then we set our form fields with the values and submit the form.
On the server side, an sql update is performed using the submitted data.
<?php ... $id = $_POST['hidId']; $content = $_POST['hidContent']; $css = $_POST['hidCss']; $js = $_POST['hidJs']; $sql = 'UPDATE pages set content= :content, css= :css, js= :js where id= :id'; $s = $pdo->prepare($sql); $s->bindValue(':content', $content); $s->bindValue(':css', $css); $s->bindValue(':js', $js); $s->bindValue(':id', $id); $s->execute(); ... ?>
Example file: example3.php.
After editing, we should be able to see the result and leave the editing mode, so we need to have both viewing and editing mode. For this, we will use the same page with viewing mode as the default and use a querystring ?edit=y to enter the editing mode.
To read the querystring, add:
$edit = $_GET['edit'];
Then we check if $edit=’y’, we include GridlessBuilder.js script for editing. If not, we just need to include Gridless CSS framework for viewing (see the comparison between scripts required for viewing and editing in the previous step). Here we implement the checking:
<?php if($edit=='y'){ ?> <link href="dist/gridlessbuilder.css" rel="stylesheet" type="text/css" /> <?php } ?>
<?php if($edit=='y'){ ?> <script src="assets/lang/en.js"></script> <script src="dist/gridlessbuilder.min.js"></script> ... <?php } ?>
For complete code and to try the example, please open in your browser: example3.php.
Example file: example4.php, login.php, logout.php
We need to prevent our page being edited without authorization. In this step, we prepare a login page that performs a user checking. You can try the example by opening login.php from your browser. The login page is querying a table called users to check if a user exists. If exists, two session variables will be set:
Please note that, actually you can use single $_SESSION[‘authorized’] variable, but for flexibility for future improvement, we also store user id in the session.
We will not show the login.php code here. It basically use a simple login form and an sql query for checking.
Now we can check the user session on our page to see if a user has logged in.
session_start(); $authorized = false; if(empty($_SESSION['userid'])==false) { $authorized = $_SESSION['authorized']; }
We then modify a bit our previous code by adding $authorized variable in the checking before entering editing mode:
<?php if($authorized && $edit=='y'){ ?> <link href="dist/gridlessbuilder.css" rel="stylesheet" type="text/css" /> <?php } ?>
<?php if($authorized && $edit=='y'){ ?> <script src="assets/lang/en.js"></script> <script src="dist/gridlessbuilder.min.js"></script> ... <?php } ?>
Example file: example5.php
In this step we will change our previous FORM method for submitting content with AJAX post. This allows you to save content without reloading the page.
For more info on AJAX, you may want to check: https://www.w3schools.com/xml/ajax_intro.asp
AJAX post will send our page’s data to the server using XMLHttpRequest:
let xhr = new XMLHttpRequest(); xhr.open("POST", url); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;'); xhr.send(postData);
To simplify our code, we created a ready to use script so that you can call AJAX post with a single line. To use the script, include these css & js files:
<link href="assets/cms/cms.css" rel="stylesheet" type="text/css" /> <script src="assets/cms/cms.js"></script>
Then we initialize a UI object that has ajaxPost() method.
var data = {}; data.post_id = <!--?php echo $id; ?-->; data.post_content = obj.html(); data.post_styles = obj.styles(); data.post_js = obj.js(); var ui = new UI(); ui.ajaxPost(data, 'savepage.php');
We need to construct the data first and also prepare another page called savepage.php for saving our page’s data. Our previous sql update (see step 2) is moved to this page.
Our UI object also has a method for showing info on the screen that can be useful for displaying the ‘Saving..’ status.
ui.showInfo('Saving..');
To hide the info, use:
ui.hideInfo();
To show the info and auto hide it after 2 seconds:
ui.showInfo('Your message', 2000);
We use these methods in our example to inform user the status of the saving process. For complete code and to try the example, please open in your browser example5.php.
Example file: example6.php
It is important that we are able to save a page as a draft and when we finish working with the page, we can publish it online for viewing. Next time when you re-editing the page, visitors will see the online version, not your currently working version.
For this purpose, we will make our existing pages table as a draft storage. And we create another table named pages_published as published pages storage.
The table pages_published will have the following fields:
Every time we publish the page, a new record is inserted into pages_published table. The previous published page records will set to archive (archived=1). So there will be only one published record for a page with archived=0. Visitors will see the data from this record.
Now we can perform a checking. If user is authorized for editing, we select data from pages table. If user is a visitor, we select data from pages_published table.
if($authorized){ $sql = 'SELECT * FROM pages where filename=:filename'; $s = $pdo->prepare($sql); $s->bindValue(':filename', $filename); $s->execute(); if($row = $s->fetch()) { $id = $row['id']; $title = $row['title']; $description = $row['description']; $content = $row['content']; $css = $row['css']; $js = $row['js']; } } else { $sql = 'SELECT * FROM pages_published WHERE filename=:filename AND archived=false'; $s = $pdo->prepare($sql); $s->bindValue(':filename', $filename); $s->execute(); if($row = $s->fetch()) { $id = $row['pageid']; $title = $row['title']; $description = $row['description']; $content = $row['content']; $css = $row['css']; $js = $row['js']; } }
To publish a page, we modify a bit our GridlessBuilder.js initialization.
var obj = new GridlessBuilder({ wrapper: '.is-wrapper', onSave: function() { savePage(); }, onSaveAndFinish: function() { savePage(true); // publish=true } });
Here we use onSaveAndFinish event to do the publishing process. In the onSaveAndFinish function, we call our savePage() method, but this time we pass a true value to the function to indicate that it is for publishing.
We modify our savePage() method as follows:
function savePage(publish) { ui.showInfo('Saving..'); var data = {}; data.post_id = <?php echo $id; ?>; data.post_content = obj.html(); data.post_styles = obj.styles(); data.post_js = obj.js(); if(publish) data.post_publish = 1; // publish else data.post_publish = 0; // save draft ... }
The savePage method now has a publish parameter. If publish is true, data.post_publish value is set 1. This will tell our server side code to not just saving the content, but also inserting a new record into our pages_published table.
Here is our PHP code for publishing the page:
// Archive current online version $sql = 'UPDATE pages_published SET archived=true WHERE pageid=:pageid'; $s = $pdo->prepare($sql); $s->bindValue(':pageid', $id); $s->execute(); // Insert new online version $sql = 'INSERT INTO pages_published (pageid,filename,title,description,content,css,js,archived,dateupdated) VALUES (:pageid,:filename,:title,:description,:content,:css,:js,false,:dateupdated)'; $s = $pdo->prepare($sql); $s->bindValue(':pageid', $id); $s->bindValue(':filename', $filename); $s->bindValue(':title', $title); $s->bindValue(':description', $description); $s->bindValue(':content', $content); $s->bindValue(':css', $css); $s->bindValue(':js', $js); $s->bindValue(':dateupdated', $dateupdated->format('Y-m-d H:i:s')); $s->execute();
Example file: example7.php
GridlessBuilder.js allows you to browse local image and video files and embed them into your content. This feature requires server side handling for saving image or video on the server. For this purpose, in GridlessBuilder.js package, there is uploadimage.php and uploadvideo.php that will do the file upload. You need to specify the uploadImageHandler and uploadVideoHandler parameters with these files:
var obj = new GridlessBuilder({ wrapper: '.is-wrapper', ... uploadImageHandler: 'uploadimage.php', uploadVideoHandler: 'uploadvideo.php' });
By default, all files will be uploaded in uploads/ folder. To view the files, we created a simple viewer/manager page named uploads.php. This page can also act as image or video picker. You just need to specify the imageSelect and videoSelect parameters with this page following with a querystring type=image or type=video.
var obj = new GridlessBuilder({ wrapper: '.is-wrapper', ... uploadImageHandler: 'uploadimage.php', uploadVideoHandler: 'uploadvideo.php', imageSelect: 'uploads.php?type=image', videoSelect: 'uploads.php?type=video' });
Example file: example8.php.
At this point, we almost complete with the important features for our simple CMS. In this step, we will add Icons feature so that you can insert icons into your content, slider feature to allow you to add slider block and an optional scroll animation feature.
Note that not all pages require icons, slider and animation script so these features can be added dynamically (depend on content). But for simplicity, let’s just add all these scripts so that you can use them with GridlessBuilder.js.
We’ll use the popular Ionicon icons and include the icon css as follows:
<link href="assets/ionicons/css/ionicons.min.css" rel="stylesheet">
We’ll use the popular Glide slider (glidejs.com) and include the script as follows:
<link rel="stylesheet" href="assets/scripts/glide/css/glide.core.min.css"> <link rel="stylesheet" href="assets/scripts/glide/css/glide.theme.css"> <script src="assets/scripts/glide/glide.min.js"></script>
We’ll use Skrollr script (https://github.com/Prinzhorn/skrollr). Please note that this script is optional:
<script src="assets/scripts/skrollr/skrollr.min.js"></script> <script> setTimeout(function () { window.skrollr = skrollr.init({ forceHeight: false, mobileCheck: function () { return false; }, smoothScrolling: true, smoothScrollingDuration: 1500 }); window.skrollr.refresh(); }, 100); </script>
Example file: index.php
Now we can move to our simple CMS. It basically uses all the code as explained in the step 1 – 8 plus some added small but important features, such as: menu and site settings for uploading logo and favicon.
One last thing that needs to be explained is about URL rewriting feature. In the previous examples, we edit About page by specifying the filename:
$filename = 'about';
In our CMS, we remove this line and use .htacess file to perform an URL rewriting. With URL rewriting, you can type in your browser: http://localhost/about and our PHP page will see it as:
index.php?f=about
So we can get filename value by using:
$filename = $_GET['f'];
To achieve this, in .htaccess file, we add the following line:
RewriteRule ^([A-Za-z0-9-_]+)/?$ index.php?f=$1&$2 [NC,L,QSA]
You can also see in our .htaccess file that we also add a rewriting rule for our login.php and logout.php page, so that you can access the login and logout page using:
http://localhost/login
http://localhost/logout
About | Privacy | Delivery & Return
Copyright © 2021 Insite Mitra Inovindo. All Rights Reserved.