grunt-contrib-watchgruntfilegrunt-phpgrunt-browser-sync

Grunt browserSync grunt-php does not reload PHP files on change


I am using Grunt + browserSync + grunt-php. The server starts normally. The problem is that whenever I make changes to PHP files, the changes are not reloaded automatically in browser. I have to manually reload the page despite having the settings in place. Been trying to solve this issue for the past 1 week, but no success. Tried out other online sources, but didn't help either. Please help.

Directory structure:

my_app/
   src/
      index.php
      about.php
   dist/

Gruntfile.js:

"use strict";

module.exports = function (grunt) {

    grunt.initConfig({

        pkg: grunt.file.readJSON('package.json'),

        watch: {
            php: {
                files: ['src/**/*.php']
            }
        },

        browserSync: {
            dev: {
                bsFiles: {
                    src: 'src/**/*.php'
                },
                options: {
                    proxy: '127.0.0.1:8010', //our PHP server
                    port: 8080, // our new port
                    open: true,
                    watchTask: true
                }
            }
        },

        php: {
            dev: {
                options: {
                    port: 8010,
                    base: 'src'
                }
            }
        }

    });


    grunt.registerTask('default', [
        'php', // Using the PHP instance as a proxy
        'browserSync',
        'watch'             // Any other watch tasks you want to run
    ]);

};

Solution

  • A kind soul helped me with the answer. I don't take credit for the answer and would like to share the solution so that it may help someone in need. Here it is:

    1) Just make sure that you have the body tag in the PHP file that you want to reload.

    2) Include the following JS code in the page:

    <script id="__bs_script__">
    //<![CDATA[
        document.write("<script async src='/browser-sync/browser-sync-client.js?v=2.17.5'><\/script>".replace("HOST", location.hostname));
    //]]>
    </script>