Category: Web Development

  • How to use PHP built-in web server

    If you are a PHP developer, chances are you have already set up a web server (WAMP or LAMP software) on your desktop. It gives you the ability to test your PHP code locally rather than testing it on a remote server.

    But what if you are working on a machine where you do not have a web server installed? Or, you may not have sufficient permissions to install the webserver on a desktop.

    Luckily, PHP provides a way out of this situation. PHP has a built-in web server that can be run directly without the need for any setup or installation.

    Some assumptions

    For this tutorial, I am making the following assumptions-

    1. My first assumption is that you are on a Windows machine, but you can implement this on any system by downloading appropriate PHP files.
    2. My second assumption is that your website is in the following folder in your desktop- F:projectsmy-php-website. You may change it to the appropriate folder of your website.
    3. My third assumption is that there is a valid index.php file in your website root folder

    How to run the PHP built-in web server

    1. Download PHP for Windows.
    2. Unzip it and save it on your desktop- F:projectsmy-php-websitephp
    3. Now press, type cmd, and press enter, to open your command prompt
    4. Now navigate to your website’s root folder using this command- cd f:projectsmy-php-website
    5. Now execute this command to run the webserver pathtophpphp.exe -S localhost:4000

    It will immediately fire up the PHP web server. You can type localhost:4000 in your web browser and it will run your index file.

    That’s great! Such a convenience without the hassles of setting up an entire web server. You can run any number of instances of this server. It is single-threaded and has its limitations, but it is sufficient for running the PHP website test code.

    You can also make changes to the PHP configuration by editing the php.ini file. You can also add/remove PHP modules.

    URL Rewriting and routing

    There is one important feature missing in PHP built-in server- URL Rewriting. Suppose you have URL rewriting for pretty permalinks enabled in your website and you want to test that functionality locally.

    Apache webserver provides the capability to add the .htaccess file to implement URL rewriting. In the PHP server, you can implement similar functionality by setting up a router.php file.

    Add a router.php file to your website root and add the following code-

    // router.php
    
    // Get the url path and trim leading slash
    $url_path = trim( $_SERVER[ 'REQUEST_URI' ], '/' );
    
    // If url_path is empty, it is root, so call index.html
    if ( ! $url_path ) {
        include( 'index.html' );
        return;
    }
    
    // If url_path has no dot, it is a post permalink, so add .html extension
    if( ! preg_match( '/[.]/', $url_path ) ) {
        include( $url_path . '.html' );
        return;
    }

    This code takes the path from URL and rewrites requests for HTML files to call them without .html extension. You can implement any functionality you want.

    Do remember, adding router.php will give the responsibility of adding the entire response on your shoulders. So, if you are including static files like style files with .css extension, you will have to handle that as well.

    // Get the url path and trim leading slash
    $url_path = trim( $_SERVER[ 'REQUEST_URI' ], '/' );
    
    // In case of css files, add the appropriate header
    if( preg_match( '/[.css]/', $url_path ) ) {
        header("Content-type: text/css");
        include( $url_path );
        // You can do the same for other file types as well
    }

    Now, go to the command line. If your PHP server is already running, press ctrl+c to stop it. Run this command-
    pathtophp.exe -S localhost:4000 router.php
    Now, again open the localhost:4000 in your web browser. It will now execute your router.php file and which, in turn, will include the required PHP files.

    This technique will save you time if you quickly need to check your code.

    Limitations of PHP built-in server

    PHP built-in server is a useful tool for developers. However, it has its limitations.

    1. It is single-threaded. That means if a request is blocked, the server will stall the execution.
    2. Once you start adding more logic to your router.php file, it will soon become cluttered. It is very difficult to scale it for large projects.
    3. There is no SQL support. You can either use SQLite, which is a good option or install a separate SQL server.

    Conclusion

    Despite its limitations, PHP built-in web server is a useful tool for web developers. It helps in saving time in many situations and makes code testing, an easy task.

  • Customize your link preview on Facebook

    When you share a link to your post on Facebook or Twitter, it automatically generates a preview card with a title, description, and optional image. This preview helps your post visibility by presenting it in an attractive manner to other users.

    This preview can be customized for all our pages using Open Graph Protocol (OGP) created by Facebook. Twitter supports this protocol adding a few tags of its own as well. In this post, I will discuss the required meta tags to customize your link preview.

    In this article, based on the Open Graph Protocol, I will tell you the exact tags to be added in the head section of your blog. This will transform your posts into rich social objects on Facebook, Twitter etc.

    What is Open Graph Protocol

    Open Graph Protocol is a schema to assign properties to a web page which can be easily understood by the compliant applications. Open Graph Protocol is implemented through meta tags in the head section of HTML web page and is loosely based on other existing schema technologies.

    Open Graph Protocol provides different meta tags to be added to your page to customize the different elements of a web page as well as to define a lot of other properties for that page.

    Though we can add all the tags defined in the Open Graph Protocol for a webpage or blog post, it will be redundant and will add to extra code. So, in this post, we will look at the basic required meta tags which will be sufficient for your customized link previews on Facebook & Twitter.

    Customizing a link preview

    If you look at your link preview of a post you shared on Facebook or Twitter, you will observe that there are three important elements-

    • Title
    • Short Description
    • Image

    These are the visible elements which are needed in a link preview. Apart from these, there are two more properties, which are type and url.

    Type defines the type of web page. For blog posts and news articles, it is ‘article’. Url is the canonical url of the object. This acts as a unique id for the object in the entire graph. In case of multiple pages sharing same data like comment pages on a blog post, this url remains same.

    Apart from this, Facebook requires you to add their FB App ID in another meta tag. As described in my previous post on the topic Social Sharing Buttons, you can easily get your Facebook app id from your Facebook for Developers dashboard.

    In case of Twitter, though it defines it’s own tags, it officially supports the Open Graph Protocol as well. So, if you add separate Twitter meta tags along with Open Graph tags, Twitter tags will be redundant. So, in the interest of keeping our code concise, we will only add those Twitter tags, which are not covered by Open Graph Protocol.

    Twitter only requires one extra meta tag, ‘twitter:card’, which we will add in our code.

    Let’s take a look at the final code.

    <meta property="og:type" content="article" />
    <meta property="og:title" content="Title of your page">
    <meta property="og:description" content="Description of your page">
    <meta property="og:image" content="Image/url/of/your/post's/featured/image">
    <meta property="og:url" content="Canonical/url/to/your/page">
    <meta property="fb:app_id" content="Your_FB_App_ID" />
    <meta property="twitter:card" content="summary_large_image">

    You can see that "og:type" and "twitter:card" tags are static and will remain the same for all blog posts. "fb:app_id" will also remain the same if you are using same app id for entire website.

    You will have to modify four tags as per your post data- "og:title", "og:description", "og:image", "og:url".

    Paste these tags in the head section of your HTML page. Your page is now rich social object.

    Sometimes Facebook or Twitter fetches wrong values for these tags, or sometime they may not even able to fetch any data. Also, you may have changed the post title, description or image after the page has been fetched by Facebook/Twitter. As Facebook & Twitter cache their data for many days, you may not be able to see the updated data when you share that link.

    In such cases, you may use the Facebook Sharing Debugger which shows how Facebook looks at the Open Graph Meta of your page and shows you the open graph data currently saved by Facebook for your post. It also allows you to force Facebook to fetch the data again, in case, there is a discrepancy.

    What happens when there are no Open Graph meta tags on your page

    If there are no Open Graph meta tags on a page, Facebook tries to get that data automatically based on page content. Usually, the title of the page is taken as title. Description is taken from the description meta tag, if available. Otherwise, it takes first few lines from the content. Similarly, the first image found on the page which is larger than 200×200 pixels id taken as image.

    There is no confirmation that in the absence of Open Graph meta tags, Facebook will take only these values. It can take any value as defined by their fetching algorithms. So, to avoid this uncertainty, it is always advised to add the above seven meta tags to all your web pages.

    Conclusion

    So, you can see that Facebook’s Open Graph Protocol is currently kind of a universal protocol to define social properties of a web page. It is supported by Twitter and many other social networks.

    It is very easy to implement as it requires adding only seven basic tags. You can add many more tags by referring to the Open Graph Protocol Documentation.

    So, don’t wait anymore. If you have not yet implemented the Open Graph meta tags in your blog or website, it is important that you do it now.

  • JSON-LD: Add Structured Data to improve SEO

    JSON-LD: Add Structured Data to improve SEO

    Adding structured data like JSON-LD to your blog or website is a very important search engine optimization (SEO) technique. It helps Google to understand your content better and helps your website to get a better search ranking.

    What is Structured Data

    Structured data is a standard format to add information to a page which can be easily understood by search engines to identify the content of the page. For example, if you have a cooking blog, Google needs to understand if a particular page is for recipe and if yes, it needs to extract key information from that page to match with the user query. Structured data helps Google by directly providing this information.

    Structured data is comprised of predefined properties which are based on schema.org.

    There are multiple formats to add structured data to your website. The three most popular formats which are supported by Google are-

    • JSON-LD
      This is a subset of JSON where all the properties are defined in the head section of an HTML page.

    • Microdata
      In the Microdata format, structured data properties are nested within HTML content by using HTML tag attributes.

    • RDFa
      Similar to Microdata, RDFa uses HTML tag attributes which are officially HTML5 extension.

    Out of these three, Google recommends using JSON-LD for structured data whenever possible.

    So, our focus in this post will be only on JSON-LD. There is no use to add multiple structured data formats. One structured data format implemented efficiently is enough for Google to understand the key information provided by our content.

    JSON-LD is the easiest to implement among all other structured data formats as it is consolidated at a single place in the head section. Also, the JSON structure is easy to create either manually or through programming making it very fast to implement. The cluttered approach of Microdata & RDFa is something which actually results in errors in implementing structured data. JSON-LD is free from all that mess.

    The content on internet is mainly written in the form of blogs containing a lot of blog posts. So, in this article, I will tell you how to implement JSON-LD for a blog post.

    Though, schema.org provides a large number of properties for each page type, it is not necessary for you to implement all those properties. A few important ones are enough.

    Implementation of JSON-LD in a Blog Post

    First of all, let’s take a look at the complete JSON-LD snippet to be added to the head section of a blog post. Then, I will explain each property. Most of the properties are self explanatory.

    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "BlogPosting",
      "headline": "Enable browser caching on Apache server using htaccess",
      "description": "Browser caching for all types of files can be easily done using Apache's .htaccess file. This simple configuration results in a faster website, less consumption of bandwidth and better user experience.",
      "mainEntityOfPage": "https://webrosis.com/enable-browser-caching-apache-server-htaccess",
      "image": "https://webrosis.com/assets/images/logo.jpg",
      "datePublished": "2019-08-06",
      "dateModified": "2019-08-06",
      "author": {
        "@type": "Person",
        "name": "Abhineet Mittal",
        "description": "Abhineet is IIM Alumnus and Founder of popular Digital Publishing Platform, Sahityapedia. He is a technology enthusiast by hobby &amp; an avid reader.",
        "image": "https://webrosis.com/assets/images/logo.jpg",
        "url": "https://webrosis.com/about"
      },
      "publisher": {
        "@type": "Organization",
        "name": "Webrosis.com",
        "logo": {
          "@type": "ImageObject",
          "url": "https://webrosis.com/assets/images/logo.jpg"
        }
      }
    }
    <script>

    In this code, I have taken JSON-LD from one of the blog posts of this blog. Let’s discuss each element used in this code.

    • The entire JSON-LD snippet has to be wrapped inside <script type="application/ld+json"> and </script> tags.
    • @context is standard and should be used as-is.
    • The most relevant type for a blog post in schema.org is BlogPosting. So, we will use that for @type.
    • Headline is the page title. This title will be visible on the Google search results page.
    • Description is a short summary of the page, and like Heading, it will be visible on the Google search results page.
    • mainEntityOfPage defines that the topic discussed is the primary topic for this page. That means it has to have canonical URL.
    • Image is URL to featured post or thumbnail of this post.
    • datePublished & dateModified are self-explanatory.
    • Author adds nested properties to define a Person. Add your name, description (biography), image and URL.
    • Finally, Publisher is similar to Author, but it indicates an organization and must have name and logo properties.

    Interestingly, according to schema.org, Publisher can be either Person or Organization. But Google only accepts Organization as a Publisher. So, do not use Person there.

    Finally, you can validate your schema using Google Structured Data Testing Tool. If you see any error, try to fix it based on the comments provided by Google.

    And that’s it. Your blog posts are now SEO ready which can be easily understood by Google.

    Make sure you do not stuff structured data with unrelated content. Structured data should clearly describe the actual content in the blog post. Doing otherwise, will hurt your search ranking as Google’s algorithm’s are smart enough to notice any discrepancies.

    When all this is done, wait for a few days and observe the change in your search rankings. Properly implemented structured data will definitely boost the search ranking of your blog bringing in more traffic.

  • Social Sharing Buttons without Javascript

    If you are developing a website, it is imperative to have social sharing buttons to increase social engagement which in turn will result in higher traffic. A lot of widgets are available for this purpose.

    The Pros

    Adding a single line of Javascript adds all the popular sharing buttons to your website. Some services allow you to customize them through remote dashboards. They also add share count and other metrics to your buttons.

    From button styling to icons, everything is handled by these widgets. All you have to do is select which buttons to show and style of those buttons.

    These services also provide cloud-hosted analytics data where you can easily monitor the visitor and their sharing pattern of different posts.

    The Cons

    When you add these widgets, they simply add the Javascript SDKs of these social websites which load the sharing button and other metrics like the number of shares, likes, etc. along with the buttons.

    This may seem good, but it adds a lot of processing to the webpage. This results in higher load time and thus, lower ranking in search engine result pages (SERP).

    A major portion of your added analytics becomes redundant if you already have Google Analytics code installed on your website. Social analytics can also be implemented through events in Google Analytics, thus making additional tracking redundant. In most cases, social analytics added by these sharing buttons adds little value.

    Also, many of these services, track your visitors and you have no option to opt-out of it. They get all the traffic data of your website, slowing down your website with their trackers, and you have no control of that. For a webmaster, this is an uneasy situation.

    The Simple Solution: No Javascript

    The simple solution is to eliminate all the Javascript and add simple HTML buttons with sharing links provided by almost all social networks. This entire code will be purely HTML and CSS without Javascript.

    I have created sharing buttons for some popular social networks and included the required CSS for the buttons. You can add your styles as well. In case you need an even better look, you can also add icons to your buttons.

    The CSS

    First, let’s create CSS for these buttons.

    .button {
      text-decoration: none;
      display: inline-block;
      text-align: center;
      padding: .25rem .5rem;
      font-size: 1rem;
      font-weight: 300;
      border-radius: .2rem;
      color: black;
      background-color: white;
    }
    
    .button-facebook {
      background-color: #4267b2;
      color: white;
    }
    
    .button-twitter {
      background-color: #1DA1F2;
      color: white;
    }
    
    .button-whatsapp {
      background-color: #25D366;
      color: white;
    }

    Facebook

    In the case of Facebook, you will also need a Facebook App ID which is very easy to get. Don’t worry, you do not have to create an app. Just go to Facebook for Developers dashboard, and fill the form with new app details. A Facebook app will be created and added to your Facebook developers account. Once you get the app id, use it in the following code to add simple Facebook sharing buttons.

    <a href="https://www.facebook.com/dialog/share?app_id=your-app-id&href=https://example.com/link-to-your-post" target="_blank" title="Share on Facebook" class="button button-facebook" rel="noopener noreferrer">Facebook</a>

    Twitter

    <a href="https://twitter.com/intent/tweet?url=https://example.com/link-to-your-post&text=Post-Title&via=your-twitter-username" target="_blank" title="Share on Twitter" class="button button-twitter" rel="noopener noreferrer">Twitter</a>

    WhatsApp

    <a href="//example.com/link-to-your-post" target="_blank" title="Share on WhatsApp" class="button button-whatsapp" rel="noopener noreferrer">WhatsApp</a>

    These are just three, but you can add any number of buttons of different social networks based on the sharing link provided in their documentation.

    These links are simple HTML and CSS with NO Javascript. They do not add extra load on your page and give you the required functionality. You may miss the share count displayed on your sharing buttons, but it is not needed and the downsides of adding it to your website are simply not worth it.

    So, just add these buttons to your website posts and pages to replace the heavy sharing widgets, and move towards a faster, cleaner code and a fast loading website.

  • Add url rewriting router to PHP built-in server

    While developing a project, PHP built-in server is much more flexible and easy to use compared to desktop setups like LAMP, XAMP, WAMP, etc.

    However, without Apache, you also lose access to the magical and powerful .htaccess feature where you can create simple rewrite rules.

    What if our application needs such rewrites like loading .html files for permalinks without extension?

    Don’t worry. PHP provides an excellent and simple solution for this as well. You can create your router.php and call it while starting the server. Now, you are free to add any rewrite rule or any other condition to run your code.

    To do this, create a file named router.php in your project root. You can choose any name for this file, but router.php provides the right context.

    In this use case, I have a static website with all the static content like HTML, CSS, etc. But my permalinks are without HTML extension, though the file name is the same. I want to write a router that can rewrite my permalinks to .html version and at the same time, not mess us my style (.css) and script (.js) files.

    Here is the code which I wrote for my particular use case. You can modify it to suit your requirements.

    // router.php
    
    // Get the url path and trim leading slash
    $url_path = trim( $_SERVER[ 'REQUEST_URI' ], '/' );
    
    // If url_path is empty, it is root, so call index.html
    if ( ! $url_path ) {
        include( 'index.html' );
        return;
    }
    
    // If url_path has no dot, it is a post permalink, so add .html extension
    if( ! preg_match( '/[.]/', $url_path ) ) {
        include( $url_path . '.html' );
        return;
    }
    
    // In case of css files, add the appropriate header
    if( preg_match( '/[.css]/', $url_path ) ) {
        header("Content-type: text/css");
        include( $url_path );
        // You can do the same for other file types as well
    }

    Your router.php is ready. Now, open your terminal, go to the project root and start the PHP server with the following command.

    pathtophp.exe -S localhost:8000 router.php

    Finally, open your website by going to localhost:8000 on your browser. It works. Great.

    Please note that this method is good for small applications so that you can quickly do a test run and check the code without deploying it on a proper server. In the case of bigger applications, this setup may become complicated as it is difficult to scale.