PHP Parse error: syntax error, unexpected ‘?’ in …

A widespread error: “PHP Parse error: syntax error, unexpected ‘?’ in …” It’s meaning is clear from error text – PHP parser run into syntax error in script.
Of course first of all you’ll need to check the script or it’s mentioned part if it really has misspelling – unclosed or excess bracket, period whatever.
If you’ve all checked and you are sure about correct syntax, then the next I recommend to check is file charset. Just open script in your favorite text editor(I use notepad++) and check what encoding the file was saved in. If just UTF-8 was used – so it could be the cause.
The fact is that saving the file in UTF-8 causes adding to file’s beginning some special signature. It’s called BOM – Byte Order Mark.
Actually it’s a symbol(it’s code is U+FEFF), that’s why PHP parser begins syntax analize from that symbol and not from <?php opening tag, so the syntax became broken in the opinion of parser.
To resolve it we just need to convert the file to UTF-8 charset without BOM at the same text editor.




We can do the same in the command line on the server.
Viewing our script in Hex:

# head -n1 AppAsset.php | hexdump -C
00000000 ef bb bf 3c 3f 70 68 70 0a |…<?php.|

Here we see something before <?php tag. In Hex – this is “ef bb bf” signature, which indicates that we have BOM in our script.
Open the script in Vi text editor, most servers have it.

# vi AppAsset.php

Type the next command while vi is still in command mode

:set nobomb

Save it and exit


Checking once again

# head -n1 AppAsset.php | hexdump -C
00000000 3c 3f 70 68 70 0a |<?php.|

Looks good.

PHP version problem

There maybe another error cause in some cases though and we need to investigate further.
Let me describe my case. I’ve got this error after site migration to another hosting. And PHP parser stopped exactly on the ‘?’ symbol.
I’ve checked the script for typos just in case, but everything was fine. The parser stopped at the next expression:

$query = $_SERVER[‘QUERY_STRING’] ?? ”;

No problems at all, no errors,’??’ operator was used correctly.
It turned out that the site was initially on hosting platform with PHP version 7, but was migrated to PHP version 5.6. But Null Coalesce operator(‘??’) was introduced in PHP 7 and I missed that.

So after switching PHP to version 7 the error dissapeared..

Напишите комментарий

Your email address will not be published. Required fields are marked *