Detecting PHP Files That Don't Start With <?php
In the past week I’ve had two weird bugs come up. After an hour or two of troubleshooting they both revolved around an extra character before the <?php
tag in a PHP file. In one case I added an extra return line before the <?php
and in another I added an extra “`”.
In trying to debug these problems I wrote a script to find PHP files with extra characters and I’ve added it to my pre-commit check.
How to Fix this Proactively
The most annoying thing about trying to detect this type of problem is that the files are valid PHP so linting your files won’t catch the problem. I initially try solving the problem using grep and awk and a combination of things but that was both hard to maintain and difficult to do.
The Script
I ended up using PHP to solve this problem because I have a feeling I’ll want to do checks similar to this in the future and I’m much better with PHP than BASH :-) .
I would like to highlight a couple things about this script.
- We’re using
exit(1)
to show there’s a problem andexit(0)
to show that everything is correct. This allows us to use the scripts return value to drive another script (which I’ll have to share later). if ($dir == './directory/to/skip') {
allows you to define project specific directories to ignore. For example, my current project has a series of JS and SCSS files inside the src directory and they never start with<?php
so I’m ignoring the whole directory.- Although unlikely, I take no responsibility for any problems this code creates.
An Example Run
Sound Off!
Has this script helped you? Let us know in the comments or share this on social media.
Scott Keck-Warren
Scott is the Director of Technology at WeCare Connect where he strives to provide solutions for his customers needs. He's the father of two and can be found most weekends working on projects around the house with his loving partner.
Top Posts
- Working With Soft Deletes in Laravel (By Example)
- Fixing CMake was unable to find a build program corresponding to "Unix Makefiles"
- Upgrading to Laravel 8.x
- Get The Count of the Number of Users in an AD Group
- Multiple Vagrant VMs in One Vagrantfile
- Fixing the "this is larger than GitHub's recommended maximum file size of 50.00 MB" error
- Changing the Directory Vagrant Stores the VMs In
- Accepting Android SDK Licenses From The OSX Command Line
- Fixing the 'Target class [config] does not exist' Error
- Using Rectangle to Manage MacOS Windows