PHP - Tips & snippets for configuration and development


New Relic

What is New Relic ?

New Relic is an APM software dedicated to web apps (Ruby, PHP, JAVA, .Net, Python, Node.js). It has quite a wide product offer, among which :

PHP APM : Enable the agent :

  1. Install the agent (1, 2)
  2. Enable the New Relic PHP module so that you have : /etc/php5/cgi/conf.d/20-newrelic.ini -> ../mods-available/newrelic.ini :
    cd /etc/php5/cgi/conf.d/; ln -s ../mods-available/newrelic.ini 20-newrelic.ini
  3. Make sure newrelic.appname is set accordingly in /etc/php5/mods-available/newrelic.ini
  4. Restart the webserver. Should be fine !

PHP APM : Configuring the application name (source) :

The application name can be configured system-wide with the newrelic.appname directive in :
  • php.ini
  • /etc/php5/conf.d/newrelic.ini

What if more than one application is installed on the server ?

  • It is possible to specify the appname in the code (source) :
    if (extension_loaded('newrelic')) {
    	newrelic_set_appname (name);
  • you can define PHP values in Apache vhost (source, Specify a custom php.ini for a website) :
    	ServerName www.myvhost1.tld
    	DocumentRoot "/path/to/vhost1/"
    	<IfModule PHP_MODULE>
    		php_value newrelic.appname "Application 1"
    	ServerName www.myvhost2.tld
    	DocumentRoot "/path/to/vhost2/"
    	<IfModule PHP_MODULE>
    		php_value newrelic.appname "Application 2"
  • With Lighttpd, it is possible to set per-directory PHP config values in .htaccess files (source) with the htscanner extension.

Upgrade to PHP 7.0

The upgrade from Debian 8.10 to 9.3 involved upgrading to PHP7.0. After that, I got an error from a web application saying :

"Can not connect to database. Make sure the 'mysqli' extension is enabled"

	apt install php7.0-cgi php-mysql
	systemctl restart lighttpd


Configuration File (php.ini) Path	/etc/php/7.0/cgi
Loaded Configuration File		/etc/php/7.0/cgi/php.ini


2017-12-13 11:31:10: (mod_fastcgi.c.2543) FastCGI-stderr: PHP Fatal error:  Uncaught Error: Call to undefined function utf8_encode() in /var/www/xxxxxxxx/index.php:552

	apt install php7.0-xml && systemctl restart lighttpd


How to install PHP on Debian via the DotDeb repositories ?


There are 2 questions before proceeding :


Here's the full procedure :

For PHP7.0 on Debian Jessie (8.x)

  1. Append to /etc/apt/sources.list :
    deb jessie all
    deb-src jessie all
  2. As root : wget && apt-key add dotdeb.gpg && rm dotdeb.gpg
  3. apt-get update
    apt-get install php7.0-common php7.0
  4. After installing/upgrading, there are chances you get the short_open_tag bug

How to set PHP configuration directives in Apache Virtualhost configuration ?

php_flag	log_errors	on
php_value	error_log	/path/to/php_errors.log

PHP snippets

How to perform an HTTP redirect :

$newDomainName = 'new.example.tld';

	"Location: http://$newDomainName".$_SERVER['REQUEST_URI'],

How to send an email :

Basic version (source) :

php -r 'mail("recipient@domain.tld", "subject", "body", "");'

Advanced version (source) :


$from		= 'test@domain.tld';		you can put anything here
$to		= '';
$subject	= 'This is the subject';
$message	= 'Hello World !';
$headers	= "From: $from\r\n" .
			"Reply-To: $from\r\n" .
			'X-Mailer: PHP/' . phpversion();

if(mail($to, $subject, $message, $headers)) {
	print "Mail sent\n";
else {
	print "Ooops\n";

How to test a DB connection (source) :


$dbHost		= 'myServer';
$dbName		= 'myDatabase';
$dbUser		= 'user';
$dbPassword	= 'password';
$dbTable	= 'myTable';

$dsn		= sprintf("mysql:dbname=$dbName;host=$dbHost");
$driverOptions	= array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$dbConnection	= new PDO($dsn, $dbUser, $dbPassword, $driverOptions);

$sql		= "select count(1) from $dbTable;";
$resultSet	= $dbConnection->query($sql);
foreach($resultSet as $result) {

Details on php.ini

List all known .ini files :
php --ini
Absolute path to currently loaded .ini file :
  • php --ini | grep -i loaded
  • phpinfo()
The result of these commands is environment-dependant : CLI / CGI.

Directives :

date.timezone = Europe/Paris (List of Supported Timezones)
Fixes the PHP Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. error.
Maximum amount of memory a script may consume. -1 means "no limit".
expose_php (source)
Boolean (on|off) used to toggle the presence of X-Powered-By: PHP/5.2.6-1+lenny4 HTTP header.
This header testifies that the corresponding response was generated by PHP rather than by the web server itself (Apache / Lighttpd / other), which could be worth knowing when dealing with redirections (HTTP 301, HTTP 302 responses).

Several php.ini files :

  • /etc/php5/apache2/php.ini : used by Apache
  • /etc/php5/cgi/php.ini : used by Lighttpd (source)
  • /etc/php5/cli/php.ini : used by all command line calls to PHP

phpinfo() : details on PHP configuration

For complete details on PHP configuration, you can create a short PHP file containing :

<?php phpinfo(); ?>
and read its result with any web browser.

Alternate methods (source) :

Details on SSL/TLS support :

php -r 'phpinfo();' | grep -i ssl



List installed PHP modules

php -m

Xdebug should appear twice : once under PHP Modules and once under Zend Modules (source).


Override php.ini settings and trigger/show PHP errors


I'm developing / testing a script on a (production ?) server where PHP is configured to log errors instead of displaying them. I need these error messages, but can't edit the php.ini.


Whether to display / hide / log / don't log PHP errors is configured thru the directives display_errors and log_errors from php.ini, that can be set on or off. Errors are logged in the file specified with the error_log directive.


Trigger errors

This can be achieved using trigger_error() (This function can only generate user-level errors such as E_USER_NOTICE or E_USER_WARNING.)
trigger_error('ARGL !', E_USER_NOTICE)

Show errors :

You can affect PHP settings from a script with ini_set(). To do so, just insert at the beginning of your script :
ini_set('log_errors', 'off');
ini_set('display_errors', 'on');

Show errors (alternate) :

ini_set('log_errors', 'on');
ini_set('error_log', '/path/to/logFile.log');

/path/to/logFile.log must be writable by the web server's user.


Fiddling with $_SERVER['SERVER_NAME']

$_SERVER['SERVER_NAME'] (explicit) is supposed to handle the "server name", but this name can have several values. It is possible to tune Apache to control which value is affected to this variable.

This is done by editing /etc/httpd/conf/httpd.conf and change the value of the parameter UseCanonicalName :

Value Output Example
Off IP address
On system hostname myServer
Dns system DNS name myServer.myCompany.tld



How to connect to Oracle ?

  1. Enable the corresponding PHP extensions (they are bundled with the PHP installation files) :
  2. php_oci8.dll allows the use of PHP functions such as oci_connect(), but these functions are defined in the Oracle client libraries. Follow this procedure to install these libraries. Basically, you have to :
    1. Download the Instant Client Basic package
    2. On the server running PHP, create a directory to store the Oracle client libraries. Let's say : C:\Oracle
    3. Extract these 3 DLLs into C:\Oracle :
      • oraociei10.dll
      • orannzsbb10.dll
      • oci.dll
    4. Edit system environment variables :
      • Add C:\Oracle to the PATH variable. Place it before any other Oracle-related stuff.
      • Create and set TNS_ADMIN to value C:\Oracle
      • Create and set NLS_LANG to value .AL32UTF8 (UTF-8)
  3. Restart the web service.

PHP complains unexpected end of file and doesn't recognize anymore the <?=myVariable?> syntax


A PHP script that used to work fine suddenly starts complaining after
On recent PHP versions :
PHP Parse error: syntax error, unexpected end of file in /path/to/file.php on line 294
On older ones :
Parse error: syntax error, unexpected $end in /path/to/file.php on line 84
The given line number being the very last line of the faulty script file.


This is often due to PHP setup defaults. Indeed, some PHP packages come with a default php.ini which is wide-open and not really security minded (fine for a development server, but not for a production box). Other PHP packages come with a recommended php.ini, which is much more production-oriented, and where some options are disabled.
Here, the disabled option is short_open_tag :
right PHP syntax short_open_tag = On short_open_tag = Off
<?=myVariable?> <?php echo(myVariable); ?>

your PHP code


your PHP code

For portability, the short_open_tag = Off syntax is recommended.


In php.ini, set short_open_tag to On and restart the webserver to reload parameters.

phpIniFile='/etc/php/7.4/cli/php.ini'; sed -ri '/^short_open_tag =.*$/ s/Off/On/' "$phpIniFile" && systemctl restart apache2

After that, make sure you have only short open tags (<?, but no <?php) in your code, otherwise the error may still occur.