How to properly use phpcs for checking all php files on project directory

Active3 hr before
Viewed126 times

10 Answers


Meta Stack Overflow , Stack Overflow Public questions & answers , Stack Overflow help chat ,I want to perform a check for all php files in my project directory to see if they are compatible with PHP 7.

1) No --extensions

phpcs - p - s - v--standard = PHPCompatibility / Users / natalisilverio / Sites / php7 / --runtime - set testVersion 7.0--report - file = phpcs - noExtensions.txt
load more v

It can be run using the commands php phpcs.phar and php phpcbf.phar.,Basically, you specify the directory of the PHP project that you would like to analyze as an argument. The command is phpcs. The following is an example use case.,It also corrects the passing of arguments based on the number of characters per line.,PHP has a variety of source code analysis tools. This time I will introduce PHP_CodeSniffer, also known as phpcs, to analyze a PHP project.

There are several methods for installing PHP_CodeSniffer. To install using Composer, type the following command.

$ composer global require "squizlabs/php_codesniffer=*"
load more v

Checking multiple files and folders,Checking a single file or folder, You can also specify multiple files and folders to check. The command below tells PHP_CodeSniffer to check the file and all files in the my_dir directory. , In the example below, the first command tells PHP_CodeSniffer to check the file for coding standard errors while the second command tells PHP_CodeSniffer to check all PHP files in the my_dir directory.

Usage: phpcs [-nwlsapvi] [-d key[=value]]    [--report=<report>] [--report-file=<reportfile>] [--report-<report>=<reportfile>] ...    [--report-width=<reportWidth>] [--generator=<generator>] [--tab-width=<tabWidth>]    [--severity=<severity>] [--error-severity=<severity>] [--warning-severity=<severity>]    [--config-set key value] [--config-delete key] [--config-show]    [--standard=<standard>] [--sniffs=<sniffs>] [--encoding=<encoding>]    [--extensions=<extensions>] [--ignore=<patterns><file> ...        -n            Do not print warnings (shortcut for --warning-severity=0)        -w            Print both warnings and errors (on by default)        -l            Local directory only, no recursion        -s            Show sniff codes in all reports        -a            Run interactively        -p            Show progress of the run        -v[v][v]      Print verbose output        -i            Show a list of installed coding standards        -d            Set the [key] php.ini value to [value] or [true] if value is omitted        --help        Print this help message        --version     Print version information        <file>        One or more files and/or directories to check        <extensions>  A comma separated list of file extensions to check                      (only valid if checking a directory)        <patterns>    A comma separated list of patterns to ignore files and directories        <encoding>    The encoding of the files being checked (default is iso-8859-1)        <sniffs>      A comma separated list of sniff codes to limit the check to                      (all sniffs must be part of the specified standard)        <severity>    The minimum severity required to display an error or warning        <standard>    The name or path of the coding standard to use        <tabWidth>    The number of spaces each tab represents        <generator>   The name of a doc generator to use                      (forces doc generation instead of checking)        <report>      Print either the "full", "xml", "checkstyle", "csv", "emacs"                      "source", "summary", "svnblame" or "gitblame" report                      (the "full" report is printed by default)        <reportfile>  Write the report to the specified file path        <reportWidth> How many columns wide screen reports should be printed
load more v

To use the script associated with a specific remote PHP interpreter, choose the name of this interpreter.,To use the script associated with the default project interpreter, that is, the one chosen on the PHP page of the Settings/Preferences dialog, choose By default project interpreter.,To use a local script, choose Local. In this case the local PHP_CodeSniffer will be executed no matter which PHP interpreter - local or remote - is used in the project. Note that there can be only one Local configuration for PHP_CodeSniffer because PhpStorm runs a script (phpcs.bat for Windows or phpcs for Linux and macOS) that contains a path to a PHP engine.,Place the caret at the detected issue and click , or press Alt+Enter.

To use PHP_CodeSniffer from PhpStorm instead of command line, you need to register it in PhpStorm and configure it as a PhpStorm code inspection. Once installed and enabled in PhpStorm, the tool is available in any opened PHP file, and no additional steps are required to launch it. The on-the-fly code check is activated upon every update in the file thus making it easy to get rid of discovered problems.

Errors and warnings reported by PHP_CodeSniffer on-the-fly are displayed as popup messages. When the tool is run in the batch mode, the errors and warnings are displayed in the Inspection Results tool window. Each message has the phpcs prefix to distinguish it from PhpStorm internal inspections. PhpStorm also integrates with the PHP Code Beautifier and Fixer tool, which lets you fix many of the detected issues.

load more v

First, make sure that you installed Coder and PHPCS correctly by following the installation instructions.,Using coder.module to auto-format your code with drush,... or, restart your shell/terminal.,Check Drupal coding standards and ignore composer and node.js directories

Check only one rule

phpcs--standard = Drupal--extensions = php, module, inc, install, test, profile, theme, css, info, txt, md, yml--sniffs = Drupal.Classes.UnusedUseStatement / path / to / drupal / example_module

$ echo $SHELL

alias drupalcs = "phpcs --standard=Drupal --extensions='php,module,inc,install,test,profile,theme,css,info,txt,md,yml'"
alias drupalcsp = "phpcs --standard=DrupalPractice --extensions='php,module,inc,install,test,profile,theme,css,info,txt,md,yml'"
alias drupalcbf = "phpcbf --standard=Drupal --extensions='php,module,inc,install,test,profile,theme,css,info,txt,md,yml'"

$ source~/.bashrc 

... or...

$ source~/.bash_profile 

... or...

$ source~/.zshrc 

$ drupalcs sites / all / modules / mymodule
$ drupalcsp sites / all / modules / mymodule
$ drupalcbf sites / all / modules / mymodule
load more v

By default PHPCS comes pre-installed with a number of coding standard definitions. To see which definitions are available for checking, use the -i switch:,Now if we re-check the file against the PEAR standards you can see that only the missing PHPDocumentor comments are listed as problems with the file:,To understand how we can create our own standards definitions, let's take a look at the existing standards that ship with PHPCS. These differ in location between different platforms, depending where PEAR puts them.,Validating this class code against the Zend standard, we use the following syntax:

To use the PEAR method you simply need to update your PEAR repository and then type:

pear install PHP_CodeSniffer
load more v

One possibility is always to install the version of PHP we want to migrate to, run php -l or something like PHPSA to check for syntax errors, check the PHP documentation for known issues with the migration and hope for the best. Or, we can use some available third party tools to check for PHP version compatibility in our projects.,Finally, lets run the PHPCompatibility standard on a single file (we can now also run it on the whole project, but let’s use a single file for this demonstration).,Of course, we also want to know if this tool can help us with a real life, production type application. Let’s use it on a complex application to see the results. I’ve chosen PHPMailer for this one.,Hope this quick tip tool introduction helped! How do you test for compatibility?

For a local installation:

composer require "squizlabs/php_codesniffer=2.*"

After PHPCS is installed, let’s move into the PHPCS /Standards folder that’s located in /vendor/squizlabs/php_codesniffer/CodeSniffer/Standards and run:

git clone https: //

This command will deploy the PHPCompatibility coding standard directly into our standards folder, together with the coding standards already bundled in PHPCS. To check if both PHPCS and PHPCompatibility were successfully installed just run the command:

. / vendor / bin / phpcs - i

For a global installation, the same method is valid, just be sure to use Composer’s global require:

composer global require "squizlabs/php_codesniffer=2.*"

and then clone PHPCompatibility into the following folder:

~/.composer/vendor / squizlabs / php_codesniffer / CodeSniffer / Standards

<runtime-set> – some individual standards also require particular configuration options, which is also the case with PHPCompatibility. This command’s syntax is as follows:

phpcs --runtime-set <option>

./vendor/bin/phpcs --standard=PHPCompatibility --runtime-set testVersion 7 <path>

If we want to test for .php files only, we can use the <extensions> option. Adding it to the command we used earlier:

./vendor/bin/phpcs --standard=PHPCompatibility --extensions=php --runtime-set testVersion 7 <path>

Of course, we also want to know if this tool can help us with a real life, production type application. Let’s use it on a complex application to see the results. I’ve chosen PHPMailer for this one.

git clone https: // mailer
   cd mailer
composer install

This will clone PHPMailer into the /mailer folder and install all its dependencies. After that, we need to install both PHPCS and the PHPCompatibility standard:

composer require "squizlabs/php_codesniffer"
cd vendor / squizlabs / php_codesniffer / CodeSniffer / Standards
git clone https: //

Finally, lets run the PHPCompatibility standard on a single file (we can now also run it on the whole project, but let’s use a single file for this demonstration).

. / vendor / bin / phpcs--standard = PHPCompatibility--extensions = php--runtime - set testVersion 5.6 class.phpmailer.php
load more v

If PHPCompatibility is the only external PHP CodeSniffer standard you use, you can add the following to your composer.json file to automatically run the necessary command:,Like with any PHP CodeSniffer standard, you can add PHPCompatibility to a custom PHP CodeSniffer ruleset., PHP Compatibility check for PHP_CodeSniffer , PHP Compatibility check for PHP_CodeSniffer

…-on - error - reporting

GH Actions: turn display_errors on
load more v

You can also test an entire directory:,In order to test a single file, use the command:,phpcbf - automatically fixes the code according to the defined rules.,In order for the script to check the .module, .install, .theme files, add these extensions to the “Check files with extensions”.

composer global require "squizlabs/php_codesniffer=*"
load more v

All of the editors below require PHPCS to be pre-installed, and since we plan to use it across projects, we will install it globally with the following command:,Either Sublime Text, VS Code, or PHPStorm installed,This way we can specify our preferences in the phpcs.xml file and have it applied across our project (irrespective of the tool we are using). Our code is now automatically being checked against our preferred standard and errors originating from PHPCS will be prefixed with phpcs.,Code inspections are how PHPStorm detects (and corrects) problems such as dead code, misspellings, and of course, code style violations in your project.

$ composer global require "squizlabs/php_codesniffer=*"
load more v

Other "properly-undefined" queries related to "How to properly use phpcs for checking all php files on project directory"