Is it possible to add a PHP file directive(...) to a .htaccess file?

PHP 7 has recently added a new strict option but it is only allowed on a per file basis and has to be the very first declaration.

I tried:

  1. using the PHP.ini auto_prepend but it only applies to the auto_prepended file.

  2. defining a constant in the auto_prepended file but testing the constant before adding the declaration produced an Exception.

This is the PHP declaration to be prepended to every PHP file:

declare(strict_types=1);

I’m not 100% sure what you’re asking, @John_Betong ?

So you’ve prepended a PHP file using .htaccess, and as the very first item in that file, you’ve done declare(strict_types=1);`

But that isn’t working? Is that the problem?

@heffreylees

I’m not 100% sure what you’re asking,


PHP 7.0 has recently introduced the new strict_type parameter declaration and it **must** be the very first declaration in a PHP file.

I use a PHP Framework that has hundreds of files and do not want to add the declaration to each individual PHP file - because that’s what computers are for :smile:

I was hoping to add a single line to the .htaccess file which would insert the following declaration into every PHP file:

BEFORE using .htaccess

<?php 
// script goes here.

AFTER using .htaccess

<?php 
declare(strict_types=1); // declaration added by .htaccess

// script goes here.

From the RFC page:

The declare(strict_types=1) directive must
be the first statement in a file. If it appears anywhere else in the
file it will generate a compiler error. Block mode is also explicitly
disallowed (declare(strict_types=1); is the only allowed form).

Like the encoding directive, but unlike the ticks directive, the strict_types
directive only affects the specific file it is used in, and does not
affect either other files which include the file nor other files that
are included by the file.

I would think the at the very least you’ll have to run a search/replace on the opening <?php of each file to add in the strict type declaration. Although, you’re not really getting the full benefit unless you refactor the existing code to use the additional type declarations (int, string, float and bool) and declare function/method return types.

I read the RFC page and tried without success to bypass the restrictions.

I was hoping that Apache2 would be able to insert the required line.

Meanwhile, only 180 files in my project had to have the line manually inserted, debugged and eventually:

Pingdom Speed Test

It is quite late now and I hope to modify the PHP Framework tomorrow.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.