Parse error syntax error unexpected expecting variable

Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers, it's just part of the learning process. However, it's often easy to interpret error messages such as: PHP ...

What are the syntax errors?

PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or identifiers. It can’t guess your coding intentions.

Function definition syntax abstract

Most important tips

There are a few basic precautions you can always take:

  • Use proper code indentation, or adopt any lofty coding style.
    Readability prevents irregularities.

  • Use an IDE or editor for PHP with syntax highlighting.
    Which also help with parentheses/bracket balancing.

    Expected: semicolon

  • Read the language reference and examples in the manual.
    Twice, to become somewhat proficient.

How to interpret parser errors

A typical syntax error message reads:

Parse error: syntax error, unexpected T_STRING, expecting ; in file.php on line 217

Which lists the possible location of a syntax mistake. See the mentioned file name and line number.

A moniker such as T_STRING explains which symbol the parser/tokenizer couldn’t process finally. This isn’t necessarily the cause of the syntax mistake, however.

It’s important to look into previous code lines as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.

Solving syntax errors

There are many approaches to narrow down and fix syntax hiccups.

  • Open the mentioned source file. Look at the mentioned code line.

    • For runaway strings and misplaced operators, this is usually where you find the culprit.

    • Read the line left to right and imagine what each symbol does.

  • More regularly you need to look at preceding lines as well.

    • In particular, missing ; semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )

    • If { code blocks } are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simplify that.

  • Look at the syntax colorization!

    • Strings and variables and constants should all have different colors.

    • Operators +-*/. should be tinted distinct as well. Else they might be in the wrong context.

    • If you see string colorization extend too far or too short, then you have found an unescaped or missing closing " or ' string marker.

    • Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone if it’s not ++, --, or parentheses following an operator. Two strings/identifiers directly following each other are incorrect in most contexts.

  • Whitespace is your friend.
    Follow any coding style.

  • Break up long lines temporarily.

    • You can freely add newlines between operators or constants and strings. The parser will then concretize the line number for parsing errors. Instead of looking at the very lengthy code, you can isolate the missing or misplaced syntax symbol.

    • Split up complex if statements into distinct or nested if conditions.

    • Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = fewer errors.)

    • Add newlines between:

      1. The code you can easily identify as correct,
      2. The parts you’re unsure about,
      3. And the lines which the parser complains about.

      Partitioning up long code blocks really helps to locate the origin of syntax errors.

  • Comment out offending code.

    • If you can’t isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.

    • As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.

    • Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)

    • When you can’t resolve the syntax issue, try to rewrite the commented out sections from scratch.

  • As a newcomer, avoid some of the confusing syntax constructs.

    • The ternary ? : condition operator can compact code and is useful indeed. But it doesn’t aid readability in all cases. Prefer plain if statements while unversed.

    • PHP’s alternative syntax (if:/elseif:/endif;) is common for templates, but arguably less easy to follow than normal { code } blocks.

  • The most prevalent newcomer mistakes are:

    • Missing semicolons ; for terminating statements/lines.

    • Mismatched string quotes for " or ' and unescaped quotes within.

    • Forgotten operators, in particular for the string . concatenation.

    • Unbalanced ( parentheses ). Count them in the reported line. Are there an equal number of them?

  • Don’t forget that solving one syntax problem can uncover the next.

    • If you make one issue go away, but other crops up in some code below, you’re mostly on the right path.

    • If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)

  • Restore a backup of previously working code, if you can’t fix it.

    • Adopt a source code versioning system. You can always view a diff of the broken and last working version. Which might be enlightening as to what the syntax problem is.
  • Invisible stray Unicode characters: In some cases, you need to use a hexeditor or different editor/viewer on your source. Some problems cannot be found just from looking at your code.

    • Try grep --color -P -n "[x80-xFF]" file.php as the first measure to find non-ASCII symbols.

    • In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.

  • Take care of which type of linebreaks are saved in files.

    • PHP just honors n newlines, not r carriage returns.

    • Which is occasionally an issue for MacOS users (even on OS  X for misconfigured editors).

    • It often only surfaces as an issue when single-line // or # comments are used. Multiline /*...*/ comments do seldom disturb the parser when linebreaks get ignored.

  • If your syntax error does not transmit over the web:
    It happens that you have a syntax error on your machine. But posting the very same file online does not exhibit it anymore. Which can only mean one of two things:

    • You are looking at the wrong file!

    • Or your code contained invisible stray Unicode (see above).
      You can easily find out: Just copy your code back from the web form into your text editor.

  • Check your PHP version. Not all syntax constructs are available on every server.

    • php -v for the command line interpreter

    • <?php phpinfo(); for the one invoked through the webserver.

    Those aren’t necessarily the same. In particular when working with frameworks, you will them to match up.

  • Don’t use PHP’s reserved keywords as identifiers for functions/methods, classes or constants.

  • Trial-and-error is your last resort.

If all else fails, you can always google your error message. Syntax symbols aren’t as easy to search for (Stack Overflow itself is indexed by SymbolHound though). Therefore it may take looking through a few more pages before you find something relevant.

Further guides:

  • PHP Debugging Basics by David Sklar
  • Fixing PHP Errors by Jason McCreary
  • PHP Errors – 10 Common Mistakes by Mario Lurig
  • Common PHP Errors and Solutions
  • How to Troubleshoot and Fix your WordPress Website
  • A Guide To PHP Error Messages For Designers — Smashing Magazine

White screen of death

If your website is just blank, then typically a syntax error is the cause.
Enable their display with:

  • error_reporting = E_ALL
  • display_errors = 1

In your php.ini generally, or via .htaccess for mod_php,
or even .user.ini with FastCGI setups.

Enabling it within the broken script is too late because PHP can’t even interpret/run the first line. A quick workaround is crafting a wrapper script, say test.php:

<?php
   error_reporting(E_ALL);
   ini_set("display_errors", 1);
   include("./broken-script.php");

Then invoke the failing code by accessing this wrapper script.

It also helps to enable PHP’s error_log and look into your webserver’s error.log when a script crashes with HTTP 500 responses.

Warning: Cannot modify header information — headers already sent

Happens when your script tries to send an HTTP header to the client but there already was output before, which resulted in headers to be already sent to the client.

This is an E_WARNING and it will not stop the script.

A typical example would be a template file like this:

<html>
    <?php session_start(); ?>
    <head><title>My Page</title>
</html>
...

The session_start() function will try to send headers with the session cookie to the client. But PHP already sent headers when it wrote the <html> element to the output stream. You’d have to move the session_start() to the top.

You can solve this by going through the lines before the code triggering the Warning and check where it outputs. Move any header sending code before that code.

An often overlooked output is new lines after PHP’s closing ?>. It is considered a standard practice to omit ?> when it is the last thing in the file. Likewise, another common cause for this warning is when the opening <?php has an empty space, line, or invisible character before it, causing the web server to send the headers and the whitespace/newline thus when PHP starts parsing won’t be able to submit any header.

If your file has more than one <?php ... ?> code block in it, you should not have any spaces in between them. (Note: You might have multiple blocks if you had code that was automatically constructed)

Also make sure you don’t have any Byte Order Marks in your code, for example when the encoding of the script is UTF-8 with BOM.

Related Questions:

  • Headers already sent by PHP
  • All PHP «Headers already sent» Questions on Stackoverflow
  • Byte Order Mark
  • What PHP Functions Create Output?

3

Fatal error: Call to a member function … on a non-object

Happens with code similar to xyz->method() where xyz is not an object and therefore that method can not be called.

This is a fatal error which will stop the script (forward compatibility notice: It will become a catchable error starting with PHP 7).

Most often this is a sign that the code has missing checks for error conditions. Validate that an object is actually an object before calling its methods.

A typical example would be

// ... some code using PDO
$statement = $pdo->prepare('invalid query', ...);
$statement->execute(...);

In the example above, the query cannot be prepared and prepare() will assign false to $statement. Trying to call the execute() method will then result in the Fatal Error because false is a «non-object» because the value is a boolean.

Figure out why your function returned a boolean instead of an object. For example, check the $pdo object for the last error that occurred. Details on how to debug this will depend on how errors are handled for the particular function/object/class in question.

If even the ->prepare is failing then your $pdo database handle object didn’t get passed into the current scope. Find where it got defined. Then pass it as a parameter, store it as property, or share it via the global scope.

Another problem may be conditionally creating an object and then trying to call a method outside that conditional block. For example

if ($someCondition) {
    $myObj = new MyObj();
}
// ...
$myObj->someMethod();

By attempting to execute the method outside the conditional block, your object may not be defined.

Related Questions:

  • Call to a member function on a non-object
  • List all PHP «Fatal error: Call to a member function … on a non-object» Questions on Stackoverflow

0

«Notice: Undefined Index», or «Warning: Undefined array key»

Happens when you try to access an array by a key that does not exist in the array.

A typical example of an Undefined Index notice would be (demo)

$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];

Both spinach and 1 do not exist in the array, causing an E_NOTICE to be triggered. In PHP 8.0, this is an E_WARNING instead.

The solution is to make sure the index or offset exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using array_key_exists or isset:

$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
    echo $data['spinach'];
}
else {
    echo 'No key spinach in the array';
}

If you have code like:

<?php echo $_POST['message']; ?>
<form method="post" action="">
    <input type="text" name="message">
    ...

then $_POST['message'] will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:

if ($_POST)  ..  // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') ..  // page was requested with POST

Related Questions:

  • Reference: “Notice: Undefined variable” and “Notice: Undefined index”
  • All PHP «Notice: Undefined Index» Questions on Stackoverflow
  • http://php.net/arrays

1

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given

First and foremost:

Please, don’t use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi — this article will help you decide which. If you choose PDO, here is a good tutorial.


This happens when you try to fetch data from the result of mysql_query but the query failed.

This is a warning and won’t stop the script, but will make your program wrong.

You need to check the result returned by mysql_query by

$res = mysql_query($sql);
if (!$res) {
   trigger_error(mysql_error(),E_USER_ERROR);
}
// after checking, do the fetch

Related Questions:

  • mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
  • All «mysql_fetch_array() expects parameter 1 to be resource, boolean given» Questions on Stackoverflow

Related Errors:

  • Warning: [function] expects parameter 1 to be resource, boolean given

Other mysql* functions that also expect a MySQL result resource as a parameter will produce the same error for the same reason.

6

Fatal error: Using $this when not in object context

$this is a special variable in PHP which can not be assigned. If it is accessed in a context where it does not exist, this fatal error is given.

This error can occur:

  1. If a non-static method is called statically. Example:

    class Foo {
       protected $var;
       public function __construct($var) {
           $this->var = $var;
       }
    
       public static function bar () {
           // ^^^^^^
           echo $this->var;
           //   ^^^^^
       }
    }
    
    Foo::bar();
    

    How to fix: review your code again, $this can only be used in an object context, and should never be used in a static method. Also, a static method should not access the non-static property. Use self::$static_property to access the static property.

  2. If code from a class method has been copied over into a normal function or just the global scope and keeping the $this special variable.
    How to fix: Review the code and replace $this with a different substitution variable.

Related Questions:

  1. Call non-static method as static: PHP Fatal error: Using $this when not in object context
  2. Copy over code: Fatal error: Using $this when not in object context
  3. All «Using $this when not in object context» Questions on Stackoverflow

3

Fatal error: Call to undefined function XXX

Happens when you try to call a function that is not defined yet. Common causes include missing extensions and includes, conditional function declaration, function in a function declaration or simple typos.

Example 1 — Conditional Function Declaration

$someCondition = false;
if ($someCondition === true) {
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case, fn() will never be declared because $someCondition is not true.

Example 2 — Function in Function Declaration

function createFn() 
{
    function fn() {
        return 1;
    }
}
echo fn(); // triggers error

In this case, fn will only be declared once createFn() gets called. Note that subsequent calls to createFn() will trigger an error about Redeclaration of an Existing function.

You may also see this for a PHP built-in function. Try searching for the function in the official manual, and check what «extension» (PHP module) it belongs to, and what versions of PHP support it.

In case of a missing extension, install that extension and enable it in php.ini. Refer to the Installation Instructions in the PHP Manual for the extension your function appears in. You may also be able to enable or install the extension using your package manager (e.g. apt in Debian or Ubuntu, yum in Red Hat or CentOS), or a control panel in a shared hosting environment.

If the function was introduced in a newer version of PHP from what you are using, you may find links to alternative implementations in the manual or its comment section. If it has been removed from PHP, look for information about why, as it may no longer be necessary.

In case of missing includes, make sure to include the file declaring the function before calling the function.

In case of typos, fix the typo.

Related Questions:

  • https://stackoverflow.com/search?q=Fatal+error%3A+Call+to+undefined+function

Fatal error: Can’t use function return value in write context

This usually happens when using a function directly with empty.

Example:

if (empty(is_null(null))) {
  echo 'empty';
}

This is because empty is a language construct and not a function, it cannot be called with an expression as its argument in PHP versions before 5.5. Prior to PHP 5.5, the argument to empty() must be a variable, but an arbitrary expression (such as a return value of a function) is permissible in PHP 5.5+.

empty, despite its name, does not actually check if a variable is «empty». Instead, it checks if a variable doesn’t exist, or == false. Expressions (like is_null(null) in the example) will always be deemed to exist, so here empty is only checking if it is equal to false. You could replace empty() here with !, e.g. if (!is_null(null)), or explicitly compare to false, e.g. if (is_null(null) == false).

Related Questions:

  • Fatal error: Can’t use function the return value

MySQL: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near … at line …

This error is often caused because you forgot to properly escape the data passed to a MySQL query.

An example of what not to do (the «Bad Idea»):

$query = "UPDATE `posts` SET my_text='{$_POST['text']}' WHERE id={$_GET['id']}";
mysqli_query($db, $query);

This code could be included in a page with a form to submit, with an URL such as http://example.com/edit.php?id=10 (to edit the post n°10)

What will happen if the submitted text contains single quotes? $query will end up with:

$query = "UPDATE `posts` SET my_text='I'm a PHP newbie' WHERE id=10';

And when this query is sent to MySQL, it will complain that the syntax is wrong, because there is an extra single quote in the middle.

To avoid such errors, you MUST always escape the data before use in a query.

Escaping data before use in a SQL query is also very important because if you don’t, your script will be open to SQL injections. An SQL injection may cause alteration, loss or modification of a record, a table or an entire database. This is a very serious security issue!

Documentation:

  • How can I prevent SQL injection in PHP?
  • mysql_real_escape_string()
  • mysqli_real_escape_string()
  • How does the SQL injection from the «Bobby Tables» XKCD comic work?
  • SQL injection that gets around mysql_real_escape_string()

3

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE

In PHP 8.0 and above, the message is instead:

syntax error, unexpected string content «», expecting «-» or identifier or variable or number

This error is most often encountered when attempting to reference an array value with a quoted key for interpolation inside a double-quoted string when the entire complex variable construct is not enclosed in {}.

The error case:

This will result in Unexpected T_ENCAPSED_AND_WHITESPACE:

echo "This is a double-quoted string with a quoted array key in $array['key']";
//---------------------------------------------------------------------^^^^^

Possible fixes:

In a double-quoted string, PHP will permit array key strings to be used unquoted, and will not issue an E_NOTICE. So the above could be written as:

echo "This is a double-quoted string with an un-quoted array key in $array[key]";
//------------------------------------------------------------------------^^^^^

The entire complex array variable and key(s) can be enclosed in {}, in which case they should be quoted to avoid an E_NOTICE. The PHP documentation recommends this syntax for complex variables.

echo "This is a double-quoted string with a quoted array key in {$array['key']}";
//--------------------------------------------------------------^^^^^^^^^^^^^^^
// Or a complex array property of an object:
echo "This is a a double-quoted string with a complex {$object->property->array['key']}";

Of course, the alternative to any of the above is to concatenate the array variable in instead of interpolating it:

echo "This is a double-quoted string with an array variable". $array['key'] . " concatenated inside.";
//----------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^

For reference, see the section on Variable Parsing in the PHP Strings manual page

Fatal error: Allowed memory size of XXX bytes exhausted (tried to allocate XXX bytes)

There is not enough memory to run your script. PHP has reached the memory limit and stops executing it. This error is fatal, the script stops. The value of the memory limit can be configured either in the php.ini file or by using ini_set('memory_limit', '128 M'); in the script (which will overwrite the value defined in php.ini). The purpose of the memory limit is to prevent a single PHP script from gobbling up all the available memory and bringing the whole web server down.

The first thing to do is to minimise the amount of memory your script needs. For instance, if you’re reading a large file into a variable or are fetching many records from a database and are storing them all in an array, that may use a lot of memory. Change your code to instead read the file line by line or fetch database records one at a time without storing them all in memory. This does require a bit of a conceptual awareness of what’s going on behind the scenes and when data is stored in memory vs. elsewhere.

If this error occurred when your script was not doing memory-intensive work, you need to check your code to see whether there is a memory leak. The memory_get_usage function is your friend.

Related Questions:

  • All «Fatal error: Allowed memory size of XXX bytes exhausted» Questions on Stackoverflow

Warning: [function]: failed to open stream: [reason]

It happens when you call a file usually by include, require or fopen and PHP couldn’t find the file or have not enough permission to load the file.

This can happen for a variety of reasons :

  • the file path is wrong
  • the file path is relative
  • include path is wrong
  • permissions are too restrictive
  • SELinux is in force
  • and many more …

One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like __DIR__ or dirname(__FILE__):

include __DIR__ . '/inc/globals.inc.php';

or:

require dirname(__FILE__) . '/inc/globals.inc.php';

Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.

The best way to solve this problem quickly is to follow the troubleshooting checklist below.

Related Questions:

  • Troubleshooting checklist: Failed to open stream

Related Errors:

  • Warning: open_basedir restriction in effect

0

Notice: Undefined variable

Happens when you try to use a variable that wasn’t previously defined.

A typical example would be

foreach ($items as $item) {
    // do something with item
    $counter++;
}

If you didn’t define $counter before, the code above will trigger the notice.

The correct way is to set the variable before using it

$counter = 0;
foreach ($items as $item) {
    // do something with item
    $counter++;
}

Similarly, a variable is not accessible outside its scope, for example when using anonymous functions.

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) {
  // Prefix is undefined
  return "${prefix} ${food}";
}, $food);

This should instead be passed using use

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) use ($prefix) {
  return "${prefix} ${food}";
}, $food);

Notice: Undefined property

This error means much the same thing, but refers to a property of an object. Reusing the example above, this code would trigger the error because the counter property hasn’t been set.

$obj = new stdclass;
$obj->property = 2342;
foreach ($items as $item) {
    // do something with item
    $obj->counter++;
}

Related Questions:

  • All PHP «Notice: Undefined Variable» Questions on Stackoverflow
  • «Notice: Undefined variable», «Notice: Undefined index», and «Notice: Undefined offset» using PHP
  • Reference: What is variable scope, which variables are accessible from where and what are «undefined variable» errors?

Notice: Use of undefined constant XXX — assumed ‘XXX’

or, in PHP 7.2 or later:

Warning: Use of undefined constant XXX — assumed ‘XXX’ (this will throw an Error in a future version of PHP)

or, in PHP 8.0 or later:

Error: Undefined constant XXX

This occurs when a token is used in the code and appears to be a constant, but a constant by that name is not defined.

One of the most common causes of this notice is a failure to quote a string used as an associative array key.

For example:

// Wrong
echo $array[key];

// Right
echo $array['key'];

Another common cause is a missing $ (dollar) sign in front of a variable name:

// Wrong
echo varName;

// Right
echo $varName;

Or perhaps you have misspelled some other constant or keyword:

// Wrong
$foo = fasle;

// Right
$foo = false;

It can also be a sign that a needed PHP extension or library is missing when you try to access a constant defined by that library.

Related Questions:

  • What does the PHP error message “Notice: Use of undefined constant” mean?

1

Fatal error: Cannot redeclare class [class name]

Fatal error: Cannot redeclare [function name]

This means you’re either using the same function/class name twice and need to rename one of them, or it is because you have used require or include where you should be using require_once or include_once.

When a class or a function is declared in PHP, it is immutable, and cannot later be declared with a new value.

Consider the following code:

class.php

<?php

class MyClass
{
    public function doSomething()
    {
        // do stuff here
    }
}

index.php

<?php

function do_stuff()
{
   require 'class.php';
   $obj = new MyClass;
   $obj->doSomething();
}

do_stuff();
do_stuff();

The second call to do_stuff() will produce the error above. By changing require to require_once, we can be certain that the file that contains the definition of MyClass will only be loaded once, and the error will be avoided.

1

Parse error: syntax error, unexpected T_VARIABLE

Possible scenario

I can’t seem to find where my code has gone wrong. Here is my full error:

Parse error: syntax error, unexpected T_VARIABLE on line x

What I am trying

$sql = 'SELECT * FROM dealer WHERE id="'$id.'"';

Answer

Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement or, like the case above, missing the . operator. The interpreter stops running your program when it encounters a parse error.

In simple words this is a syntax error, meaning that there is something in your code stopping it from being parsed correctly and therefore running.

What you should do is check carefully at the lines around where the error is for any simple mistakes.

That error message means that in line x of the file, the PHP interpreter was expecting to see an open parenthesis but instead, it encountered something called T_VARIABLE. That T_VARIABLE thing is called a token. It’s the PHP interpreter’s way of expressing different fundamental parts of programs. When the interpreter reads in a program, it translates what you’ve written into a list of tokens. Wherever you put a variable in your program, there is aT_VARIABLE token in the interpreter’s list.

Good read: List of Parser Tokens

So make sure you enable at least E_PARSE in your php.ini. Parse errors should not exist in production scripts.

I always recommended to add the following statement, while coding:

error_reporting(E_ALL);

PHP error reporting

Also, a good idea to use an IDE which will let you know parse errors while typing. You can use:

  1. NetBeans (a fine piece of beauty, free software) (the best in my opinion)
  2. PhpStorm (uncle Gordon love this: P, paid plan, contains proprietary and free software)
  3. Eclipse (beauty and the beast, free software)

Related Questions:

  • Reference: PHP Parse/Syntax Errors; and How to solve them?

0

Notice: Uninitialized string offset: *

As the name indicates, such type of error occurs, when you are most likely trying to iterate over or find a value from an array with a non-existing key.

Consider you, are trying to show every letter from $string

$string = 'ABCD'; 
for ($i=0, $len = strlen($string); $i <= $len; $i++){
    echo "$string[$i] n"; 
}

The above example will generate (online demo):

A
B
C
D
Notice: Uninitialized string offset: 4 in XXX on line X

And, as soon as the script finishes echoing D you’ll get the error, because inside the for() loop, you have told PHP to show you the from first to fifth string character from 'ABCD' Which, exists, but since the loop starts to count from 0 and echoes D by the time it reaches to 4, it will throw an offset error.

Similar Errors:

  • Illegal string offset ‘option 1’

Notice: Trying to get property of non-object error

Happens when you try to access a property of an object while there is no object.

A typical example for a non-object notice would be

$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object

In this case, $users is an array (so not an object) and it does not have any properties.

This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).

This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returns NULL if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.

As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function … on a non-object) halting the script.

It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object

The problem is accessing the nodeValue property (field) of the first item while it has not been checked if it exists or not in the $result collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$div     = $result->item(0);
$divText = "-/-";
if (is_object($div)) {
    $divText = $div->nodeValue;
}
echo $divText;

Related errors:

  • Notice: Undefined Index
  • Fatal error: Call to a member function … on a non-object

4

Parse error: syntax error, unexpected ‘[‘

This error comes in two variatians:

Variation 1

$arr = [1, 2, 3];

This array initializer syntax was only introduced in PHP 5.4; it will raise a parser error on versions before that. If possible, upgrade your installation or use the old syntax:

$arr = array(1, 2, 3);

See also this example from the manual.

Variation 2

$suffix = explode(',', 'foo,bar')[1];

Array dereferencing function results was also introduced in PHP 5.4. If it’s not possible to upgrade you need to use a (temporary) variable:

$parts = explode(',', 'foo,bar');
$suffix = $parts[1];

See also this example from the manual.

Warning: [function] expects parameter 1 to be resource, boolean given

(A more general variation of Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given)

Resources are a type in PHP (like strings, integers or objects). A resource is an opaque blob with no inherently meaningful value of its own. A resource is specific to and defined by a certain set of PHP functions or extension. For instance, the Mysql extension defines two resource types:

There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.

The cURL extension defines another two resource types:

… a cURL handle and a cURL multi handle.

When var_dumped, the values look like this:

$resource = curl_init();
var_dump($resource);

resource(1) of type (curl)

That’s all most resources are, a numeric identifier ((1)) of a certain type ((curl)).

You carry these resources around and pass them to different functions for which such a resource means something. Typically these functions allocate certain data in the background and a resource is just a reference which they use to keep track of this data internally.


The «… expects parameter 1 to be resource, boolean given» error is typically the result of an unchecked operation that was supposed to create a resource, but returned false instead. For instance, the fopen function has this description:

Return Values

Returns a file pointer resource on success, or FALSE on error.

So in this code, $fp will either be a resource(x) of type (stream) or false:

$fp = fopen(...);

If you do not check whether the fopen operation succeed or failed and hence whether $fp is a valid resource or false and pass $fp to another function which expects a resource, you may get the above error:

$fp   = fopen(...);
$data = fread($fp, 1024);

Warning: fread() expects parameter 1 to be resource, boolean given

You always need to error check the return value of functions which are trying to allocate a resource and may fail:

$fp = fopen(...);

if (!$fp) {
    trigger_error('Failed to allocate resource');
    exit;
}

$data = fread($fp, 1024);

Related Errors:

  • Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given

Warning: Illegal string offset ‘XXX’

This happens when you try to access an array element with the square bracket syntax, but you’re doing this on a string, and not on an array, so the operation clearly doesn’t make sense.

Example:

$var = "test";
echo $var["a_key"];

If you think the variable should be an array, see where it comes from and fix the problem there.

0

Code doesn’t run/what looks like parts of my PHP code are output

If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn’t actually getting executed. If you use View Source in your browser, you’re probably seeing the whole PHP source code file as is. Since PHP code is embedded in <?php ?> tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.

To actually run your PHP scripts, you need:

  • a web server which executes your script
  • to set the file extension to .php, otherwise the web server won’t interpret it as such*
  • to access your .php file via the web server

* Unless you reconfigure it, everything can be configured.

This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:

file://C:/path/to/my/file.php

This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:

http://localhost/my/file.php

You may also want to check whether you’re using short open tags <? instead of <?php and your PHP configuration has turned short open tags off.

Also see PHP code is not being executed, instead code shows on the page

Warning: Array to string conversion

Notice: Array to string conversion

(A notice until PHP 7.4, since PHP 8.0 a warning)

This simply happens if you try to treat an array as a string:

$arr = array('foo', 'bar');

echo $arr;  // Notice: Array to string conversion
$str = 'Something, ' . $arr;  // Notice: Array to string conversion

An array cannot simply be echo‘d or concatenated with a string, because the result is not well defined. PHP will use the string «Array» in place of the array, and trigger the notice to point out that that’s probably not what was intended and that you should be checking your code here. You probably want something like this instead:

echo $arr[0];  // displays foo
$str = 'Something ' . join(', ', $arr); //displays Something, foo, bar

Or loop the array:

foreach($arr as $key => $value) {
    echo "array $key = $value";
    // displays first: array 0 = foo
    // displays next:  array 1 = bar
}

If this notice appears somewhere you don’t expect, it means a variable which you thought is a string is actually an array. That means you have a bug in your code which makes this variable an array instead of the string you expect.

Warning: mysql_connect(): Access denied for user ‘name’@’host’

This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials (username/password). So this is typically not a code problem, but a server configuration issue.

  • See the manual page on mysql_connect("localhost", "user", "pw") for examples.

  • Check that you actually used a $username and $password.

    • It’s uncommon that you gain access using no password — which is what happened when the Warning: said (using password: NO).
    • Only the local test server usually allows to connect with username root, no password, and the test database name.

    • You can test if they’re really correct using the command line client:
      mysql --user="username" --password="password" testdb

    • Username and password are case-sensitive and whitespace is not ignored. If your password contains meta characters like $, escape them, or put the password in single quotes.

    • Most shared hosting providers predeclare mysql accounts in relation to the unix user account (sometimes just prefixes or extra numeric suffixes). See the docs for a pattern or documentation, and CPanel or whatever interface for setting a password.

    • See the MySQL manual on Adding user accounts using the command line. When connected as admin user you can issue a query like:
      CREATE USER 'username'@'localhost' IDENTIFIED BY 'newpassword';

    • Or use Adminer or WorkBench or any other graphical tool to create, check or correct account details.

    • If you can’t fix your credentials, then asking the internet to «please help» will have no effect. Only you and your hosting provider have permissions and sufficient access to diagnose and fix things.

  • Verify that you could reach the database server, using the host name given by your provider:
    ping dbserver.hoster.example.net

    • Check this from a SSH console directly on your webserver. Testing from your local development client to your shared hosting server is rarely meaningful.

    • Often you just want the server name to be "localhost", which normally utilizes a local named socket when available. Othertimes you can try "127.0.0.1" as fallback.

    • Should your MySQL/MariaDB server listen on a different port, then use "servername:3306".

    • If that fails, then there’s a perhaps a firewall issue. (Off-topic, not a programming question. No remote guess-helping possible.)

  • When using constants like e.g. DB_USER or DB_PASSWORD, check that they’re actually defined.

    • If you get a "Warning: Access defined for 'DB_USER'@'host'" and a "Notice: use of undefined constant 'DB_PASS'", then that’s your problem.

    • Verify that your e.g. xy/db-config.php was actually included and whatelse.

  • Check for correctly set GRANT permissions.

    • It’s not sufficient to have a username+password pair.

    • Each MySQL/MariaDB account can have an attached set of permissions.

    • Those can restrict which databases you are allowed to connect to, from which client/server the connection may originate from, and which queries are permitted.

    • The «Access denied» warning thus may as well show up for mysql_query calls, if you don’t have permissions to SELECT from a specific table, or INSERT/UPDATE, and more commonly DELETE anything.

    • You can adapt account permissions when connected per command line client using the admin account with a query like:
      GRANT ALL ON yourdb.* TO 'username'@'localhost';

  • If the warning shows up first with Warning: mysql_query(): Access denied for user ''@'localhost' then you may have a php.ini-preconfigured account/password pair.

    • Check that mysql.default_user= and mysql.default_password= have meaningful values.

    • Oftentimes this is a provider-configuration. So contact their support for mismatches.

  • Find the documentation of your shared hosting provider:

    • e.g. HostGator, GoDaddy, 1and1, DigitalOcean, BlueHost, DreamHost, MediaTemple, ixWebhosting, lunarhosting, or just google yours´.

    • Else consult your webhosting provider through their support channels.

  • Note that you may also have depleted the available connection pool. You’ll get access denied warnings for too many concurrent connections. (You have to investigate the setup. That’s an off-topic server configuration issue, not a programming question.)

  • Your libmysql client version may not be compatible with the database server. Normally MySQL and MariaDB servers can be reached with PHPs compiled in driver. If you have a custom setup, or an outdated PHP version, and a much newer database server, or significantly outdated one — then the version mismatch may prevent connections. (No, you have to investigate yourself. Nobody can guess your setup).

More references:

  • Serverfault: mysql access denied for ‘root’@’name of the computer’
  • Warning: mysql_connect(): Access denied
  • Warning: mysql_select_db() Access denied for user »@’localhost’ (using password: NO)
  • Access denied for user ‘root’@’localhost’ with PHPMyAdmin

Btw, you probably don’t want to use mysql_* functions anymore. Newcomers often migrate to mysqli, which however is just as tedious. Instead read up on PDO and prepared statements.
$db = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");

2

Deprecated: Array and string offset access syntax with curly braces is deprecated

String offsets and array elements could be accessed by curly braces {} prior to PHP 7.4.0:

$string = 'abc';
echo $string{0};  // a

$array = [1, 2, 3];
echo $array{0};  // 1

This has been deprecated since PHP 7.4.0 and generates a warning:

Deprecated: Array and string offset access syntax with curly braces is deprecated

You must use square brackets [] to access string offsets and array elements:

$string = 'abc';
echo $string[0];  // a

$array = [1, 2, 3];
echo $array[0];  // 1

The RFC for this change links to a PHP script which attempts to fix this mechanically.

Warning: Division by zero

The warning message ‘Division by zero’ is one of the most commonly asked questions among new PHP developers. This error will not cause an exception, therefore, some developers will occasionally suppress the warning by adding the error suppression operator @ before the expression. For example:

$value = @(2 / 0);

But, like with any warning, the best approach would be to track down the cause of the warning and resolve it. The cause of the warning is going to come from any instance where you attempt to divide by 0, a variable equal to 0, or a variable which has not been assigned (because NULL == 0) because the result will be ‘undefined’.

To correct this warning, you should rewrite your expression to check that the value is not 0, if it is, do something else. If the value is zero you either should not divide, or you should change the value to 1 and then divide so the division results in the equivalent of having divided only by the additional variable.

if ( $var1 == 0 ) { // check if var1 equals zero
    $var1 = 1; // var1 equaled zero so change var1 to equal one instead
    $var3 = ($var2 / $var1); // divide var1/var2 ie. 1/1
} else {
    $var3 = ($var2 / $var1); // if var1 does not equal zero, divide
}

Related Questions:

  • warning: division by zero
  • Warning: Division By Zero Working on PHP and MySQL
  • Division by zero error in WordPress Theme
  • How to suppress the “Division by zero” error
  • How to catch a division by zero?

2

Strict Standards: Non-static method [<class>::<method>] should not be called statically

Occurs when you try to call a non-static method on a class as it was static, and you also have the E_STRICT flag in your error_reporting() settings.

Example :

class HTML {
   public function br() {
      echo '<br>';
   }
}

HTML::br() or $html::br()

You can actually avoid this error by not adding E_STRICT to error_reporting(), eg

error_reporting(E_ALL & ~E_STRICT);

since as for PHP 5.4.0 and above, E_STRICT is included in E_ALL [ref]. But that is not adviceable. The solution is to define your intended static function as actual static :

public static function br() {
  echo '<br>';
}

or call the function conventionally :

$html = new HTML();
$html->br();

Related questions :

  • How can I solve «Non-static method xxx:xxx() should not be called statically in PHP 5.4?

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@longestdrive

  • Laravel Version: 5.5
  • PHP Version:7.01
  • Database Driver & Version:Mysql 5.6

Description:

On my VPS I have PHP version 7.0 installed. When A used clicks for a password reset I get this error

Parse error: syntax error, unexpected '?', expecting variable (T_VARIABLE) 

This relates to line 24 of RedirectIfAuthenticated.php

Researching I understand this is an issue with Mail and has been solved by others by upgrading to php7.1

I don’t have that option on my server and am forced to use php7.0 which this version of laravel 5.5 is meant to support

Can you advised how to overcome this issue please

Steps To Reproduce:

  1. Default Laravel authentication being used
  2. User clicks reset passowrd, completes form and then submits
  3. Error occurs

@tomhatzer

@devcircus

That’s not a core file anyway. Make the changes necessary to match the file that @tomhatzer shared above.

@TheDeadCode

I’d probably make sure you truly have PHP 7.0 installed.

Make a dummy file and put <?php phpinfo(); in it. Look for the PHP version and make sure 7.0 is really there.

@browner12

bonzai, daiduong47, alkoumi, millsoft, mfoote, CodeGirl300, romalytvynenko, mehaX, jjbutnotreally, gleycerparra, and 53 more reacted with thumbs down emoji

@kizomanizo

PHP Version, everytime. Laravel 5.6 needs a minimum of PHP 7.1.X make sure you are not on an older version.

@mutiemule

The real issue is some dependencies are using a higher PHP version other than 7.0.

You have two choices, to upgrade to PHP7.1 or instruct composer to download only dependencies which are compatible with PHP7.0 by doing the following:
For PHP7.0 only

If your server doesn’t have PHP7.1 and above and you are only restricted to use PHP7.0
do as below:

  1. Delete vendor folder
  2. Delete composer.lock file
  3. Add this to composer.json file under config
"platform": {
           "php": "7.0.0"
}

As well, ensure PHP version under require is set to 7.0.0 as shown below in config.platform.php:

"config": {
            "platform": {
                "php": "7.0.0"
            }
}
  1. Run composer install using CMD

This now will make sure that only dependencies compatible with php7.0 are installed.

wendellneander, mbuk, slavanossar, ermuhaimin, sismananitas, snipe, Malki, Gargravarr2112, bkmorse, tayyebi, and 2 more reacted with thumbs up emoji
wellington1993 reacted with eyes emoji

@anujs-webonise

@gopal-g

create a simple test.php page in your public folder

put phpinfo() in it and then hit test.php in your browser

Sometimes the php version being used by the webserver can be a different version to the command line

Sometimes we see the ‘Parse Error syntax error unexpected … ‘ when we edit WordPress files or we install an new theme or plugin.  This error can be frustrating and take your website down.   So let check the main reasons why this happen.

  • Parse error: syntax error, unexpected T_STRING
  • Parse error: syntax error, unexpected T_VARIABLE
  • Parse error: syntax error, unexpected T_IF …

All these messages, in fact, are different examples of the same error: the PHP compiler warns us of having found a type of construct that was not expected or trusted. These errors are almost always the result of a typing error. For example:

if $ xyz == 1) echo 'one';

In the example above we forgot to open the round bracket after the if. In this case we will get unexpected T_VARIABLE because the interpreter found himself facing a variable – $ xyz – that he didn’t expect.

Any error message that includes a word that begins with T_ refers to a token, that is, an internal representation of a language construct. For example, T_VARIABLE is the token used by PHP to indicate a variable. Similarly, T_STRING is the token that represents a string, and so on. The token list is available on this page of the official PHP documentation.

In general, these can be some of the most difficult errors to trace because often the line number indicated in the error could be very far from the line where the actual error was made. It is therefore a good idea to regularly run tests to run the script during the programming phase in order to find the error on a limited portion of the code, otherwise the risk is to have to look for a needle in a haystack.

Parse error: syntax error, unexpected $ end
This error is related to the errors mentioned above, but it is worth treating it separately. This error message informs us that the PHP interpreter arrived at the end of the file but was still expecting something (that was not there). Very often this error is caused by the lack of a “}” in the code. Unfortunately you will have to scan the entire file to find out where the mistake was made …

This error can also be generated by bad syntax related to the heredoc construct. The heredoc syntax requires that the final delimiter must be the first element of the line, without any other character, including spaces, that precedes it. Often, due to typos or editors attempting to do automatic code formatting, this rule is not respected and this produces this error.

Parse error: syntax error, unexpected ‘=’, expecting ‘;’
This error is also part of the same family of errors seen above. In this circumstance the PHP interpreter is very precise in informing us of what we were expecting (and did not find) for example an equal for assigning a value to a variable or a semicolon as a terminator of an intrusion .

Debugging this type of error is a bit simpler than the previous one because PHP usually indicates a line of code rather close to the exact point where the error was made.

Normally to find the issue you have to find the exact line where the problem is through the error you see on the front page:

As you see in the error message above you have to edit the file single.php on the line 43 you can find one of the issue i had described above. If you website is published online you have to access the ftp service to edit the file.

Содержание

  1. PHP parse/syntax errors; Ошибки Unexpected XXX и как решить их
  2. 8 ответов 8
  3. Unexpected T_STRING
  4. Unexpected identifier «xxx»
  5. Строки с неверными кавычками
  6. Незакрытые строки
  7. Кавычки, не связанные с программированием
  8. Отсутствует точка с запятой
  9. Невидимые символы Unicode
  10. Заэкранированная кавычка
  11. Unexpected T_VARIABLE
  12. Unexpected ‘$varname’ (T_VARIABLE)
  13. Отсутствует точка с запятой
  14. Неверная конкатенация строк
  15. Пропущен оператор выражения
  16. В перечислениях в массивах или функциях
  17. В объявлении свойств классов
  18. Переменные сразу после идентификаторов
  19. Отсутствие скобок до/после языковых конструкций if, for, foreach
  20. Else не ожидает условий
  21. Необходимы скобки для замыканий (closure)
  22. Невидимые пробелы
  23. Общее о синтаксических ошибках
  24. ### Заметка:
  25. ### Как интерпретировать ошибки парсера
  26. Unexpected (
  27. Выражения в параметрах объявленной функции
  28. Выражения в свойствах класса
  29. isset(()), empty, key, next, current
  30. Unexpected )
  31. Висячая запятая при вызове функции/метода
  32. Незавершённые выражения
  33. Foreach as constant
  34. Unexpected <
  35. Unmatched subexpressions in an if (Несовпадающие подвыражения) в if
  36. < and >в выражениях
  37. Unexpected >
  38. Последнее выражение в блоке и потеря точки с запятой
  39. Недопустимая вложенность блоков/Forgotten < (забытая < )
  40. Unexpected < , expecting (
  41. Список параметров функции/метода
  42. Условные конструкции
  43. Unexpected T_CONSTANT_ENCAPSED_STRING
  44. Unexpected T_ENCAPSED_AND_WHITESPACE
  45. Неправильная интерполяция переменных
  46. Отсутствует конкатенация
  47. Отсутствует начальная кавычка
  48. Пропущена запятая в массиве
  49. Пропущена запятая в аргументах функции/метода
  50. Строка закрыта слишком поздно
  51. Отступ в HEREDOC
  52. Unexpected $end
  53. Unexpected end of file
  54. Отступ в HEREDOC
  55. Заэкранированная кавычка
  56. Альтернативный синтаксис
  57. Unexpected T_FUNCTION

PHP parse/syntax errors; Ошибки Unexpected XXX и как решить их

Часто программисты допускают ошибки. Могут возникать ошибки синтаксиса. Например:

Неожиданный символ не всегда является настоящим виновником. Но номер строки дает приблизительное представление о том, с чего начать поиск.

Всегда смотрите на контекст кода. Синтаксическая ошибка часто кроется в упомянутых или в предыдущих строках кода. Сравните свой код с примерами синтаксиса из руководства.

Дополнительные ссылки для поиска ошибок:

В ответах ниже обобщены распространенные ошибки, найдите ошибку в списке ниже и перейдите к ответу с её описанием.

Unexpected $end / Unexpected end of file

Unexpected continue (T_CONTINUE)
Unexpected continue (T_BREAK)
Unexpected continue (T_RETURN)

В работе.

Unexpected character in input: ‘ ‘ (ASCII=92) state=1

Unexpected ‘public’ (T_PUBLIC)
Unexpected ‘private’ (T_PRIVATE)
Unexpected ‘protected’ (T_PROTECTED)
Unexpected ‘final’ (T_FINAL)

Unexpected ‘use’ (T_USE)

Unexpected ,
Unpexected .
Unexpected ;
Unexpected *
Unexpected :
Unexpected ‘:’, expecting ‘,’ or ‘)’
Unexpected &
Unexpected .

8 ответов 8

Unexpected T_STRING

Unexpected identifier «xxx»

Означает, что был обнаружен необработанный идентификатор. Это может быть разное: от «голых слов» до оставшихся констант или имен функций, забытых строк без кавычек или любого простого текста. Примерные проблемы:

Строки с неверными кавычками

Любая неэкранированная и случайная кавычка » или ‘ образует недопустимое выражение.

В данном примере используются двойные кавычки в двойных. Это неверно. Интерпретатор «увидит» строку » и строку «>click here» (т.к. строки заключаются в кавычки), а что такое http://example.com он не поймёт. Важно не забывать использовать обратный слэш для экранирования » двойных кавычек или ’ одинарных кавычек — в зависимости от того, что использовалось снаружи для всей строки (для ознакомления со строками). Например если снаружи двойные кавычки, то внутри проще использовать одинарные, чтобы не запутаться, либо экранировать двойную. С одинарными аналогично. Ещё проще большой текст помещать в HEREDOC или NOWDOC

Незакрытые строки

Если вы пропустите закрывающую кавычку, то синтаксическая ошибка обычно возникает позже.

Кавычки, не связанные с программированием

Обычно возникают, когда копируют текст из книги. Они могут выглядеть так:

Отсутствует точка с запятой

Невидимые символы Unicode

Если вы получили жалобу парсера T_STRING на совершенно не вызывающий подозрений код, например:

Нужно взять другой текстовый редактор. Или даже hexeditor. То, что здесь выглядит как простые пробелы и символы новой строки, может содержать невидимые константы. Такое бывает в документах с кодировкой UTF-8 BOM и нужно сделать кодировку UTF-8 без BOM

Заэкранированная кавычка

Символ имеет особое значение. Часто символ применяют для экранирования в строках. Чтобы кавычка внутри строки, которая обёрнута в такие же кавычки, печаталась как есть, то её экранируют. Т.е. строка echo «Jim said »Hello»»; выведет Jim said «hello» . Если применить последовательность » , то она будет расценена как попытка экранирования кавычки. Поэтому строка ниже, выдаст ошибку

правильно будет экранировать обратные слэши тоже:

Unexpected T_VARIABLE

Unexpected ‘$varname’ (T_VARIABLE)

Означает, что есть конкретная переменная с указаннымв ошибке именем, которая не вписывается в текущую структуру выражения/инструкции.

Отсутствует точка с запятой

Как правило пропущена точка с запятой, а на следующей строке идёт переменная:

Неверная конкатенация строк

Пропущен оператор выражения

В перечислениях в массивах или функциях

В объявлении свойств классов

В свойства можно назначать только статические значения (которые однозначно определены), но не выражения.

Если необходимо присвоивать переменной выражение, то это нужно делать либо в конструкторе, либо в другом каком-либо инициализирующем методе

Переменные сразу после идентификаторов

Отсутствие скобок до/после языковых конструкций if, for, foreach

Else не ожидает условий

тут надо либо фигурные скобки, либо применять elseif (если не нарушает логики)

Необходимы скобки для замыканий (closure)

Переменные, которые передаются в замыкания всегда надо оборачивать в круглые скобки

Невидимые пробелы

Как отмечалось ранее. Могут быть невидимые символы. Проверьте на их наличие (читайте выше ошибки Unexpected T_STRING)

Общее о синтаксических ошибках

### Заметка:

Если ваш браузер отображает сообщения об ошибках, такие как «SyntaxError: illegal character», то это на самом деле связано не с PHP, а с Javascript и синтаксическими ошибками в нём

Синтаксические ошибки, возникающие в коде vendor: если синтаксическая ошибка возникла после установки или обновления пакета vendor’а — это может быть связано с несовместимостью версии PHP, поэтому проверьте версию vendor’а. и требования к настройке вашей платформы.

Используйте IDE, например PHPStorm, который всегда подскажет, что с кодом что-то не так. Обращайте внимание на подсказки:

Иногда возникают ошибки из-за лишних символов в начале файла, в частности BOM. Убедитесь, что файл сохранён в UTF-8 без BOM. (если нужен именно utf8)

Если ваш веб-сайт просто пустой с белым экраном, то, как правило, причиной является синтаксическая ошибка. Включите их отображение с помощью этой инструкции

### Как интерпретировать ошибки парсера

Типичное сообщение об ошибке синтаксиса:

Parse error: syntax error, unexpected T_STRING, expecting ‘ ; ‘ in file.php on line 217

(Ошибка синтаксического анализа: синтаксическая ошибка, неожиданный T_STRING, ожидалось ‘ ; ‘ в файле file.php в строке 217)

Тут указано возможное место синтаксической ошибки. См. упомянутые имя файла и номер строки.

Токен, такой как T_STRING , объясняет, какой символ синтаксический анализатор/токенизатор не смог окончательно обработать. Однако это не обязательно является причиной синтаксической ошибки. Поэтому важно изучить предыдущие строки кода. Часто синтаксические ошибки — это ошибки, произошедшие ранее. Номер строки ошибки — это именно то место, где синтаксический анализатор окончательно отказался от обработки всего этого, а не точная линия ошибки

Unexpected (

Открывающие круглые скобки обычно следуют за языковыми конструкциями, такими как if / foreach / for / array / list , или начинают арифметическое выражение. Они синтаксически неверны после «strings» , предыдущих скобок () , одинокого $ и в некоторых типичных контекстах объявлений. Типичные ошибки:

Выражения в параметрах объявленной функции

Параметры в объявлении функции могут быть только литеральными значениями или константными выражениями. То есть выражение time() + 90000 нельзя использовать в качестве дефолтного значения параметра функциию. Тем не менее при вызове функции можно свободно использовать выражение:

Выражения в свойствах класса

Как и ошибка выше, нельзя применять выражения для свойств класса, т.е.

Если необходимо что-то вычислить, то данные вычисления/выражения стОит помеестить в конструктор класса.

Единственное, PHP 7 позволяет написать public $property = 1 + 2 + 3; . Но это посзволительно, т.к., по сути, это выражение с константными значениями, не вычисляемое «на лету».

isset(()), empty, key, next, current

И isset() и empty() являются встроенными языковыми конструкциями языка, а не функциями, им необходим прямой доступ к переменной. Если вы непреднамеренно добавите слишком много скобок, то вы создадите доп. выражение:

Для PHP Parse error: syntax error, unexpected ‘(‘

Для PHP Fatal error: Cannot use isset() on the result of an expression

Начиная с версии 7.0 — ошибки не будет

Unexpected )

Висячая запятая при вызове функции/метода

В новых версиях языка позволены висячие запятые при нициализации массивов или списков (а также в объявлении функций/методов), но не при вызове функций/методов

Незавершённые выражения

Например если забыли в арифметическом выражении, то синтаксический анализатор сдается. Потому что он не знает как интерпретировать это:

Но если забыли закрывающую скобку вдобавок, то получите жалобу о неожиданной точке с запятой.

Foreach as constant

Если забыть добавить доллар к переменной:

PHP здесь иногда говорит, что вместо этого ожидался -> или ?-> . Поскольку class->variable мог бы удовлетворить ожидаемому выражению.

Unexpected <

Фигурные скобки < и >окружают блоки кода. И синтаксические ошибки о них обычно указывают на какую-то неправильную вложенность.

Unmatched subexpressions in an if (Несовпадающие подвыражения) в if

Чаще всего несбалансированные ( и ) являются причиной, если парсер жалуется на открывающуюся фигурную скобку < , которая появляется слишком рано. Простой пример:

Необходимо посчитать все открывающие и закрывающие скобки и сопоставить их количество. Также используйте IDE, которая помогает в этом и не пишите код без пробелов. Удобочитаемость имеет значение.

< and >в выражениях

Нельзя оборачивать выражения в скобки.

Придётся выражение вынести в переменную и подставлять уже её:

Unexpected >

Когда получаете ошибку «unexpected > «, чаще всего означает, что закрывали блок кода слишком рано.

Последнее выражение в блоке и потеря точки с запятой

Недопустимая вложенность блоков/Forgotten < (забытая < )

Блок кода был > закрыт слишком рано, или забыли открытую скобку < :

В приведенном выше фрагменте if не было открывающей фигурной скобки < . Таким образом, закрывающая >ниже стала излишней. И поэтому следующая закрывающая > , предназначенная для функции, не была связана с исходной открывающей фигурной скобкой < .

Unexpected < , expecting (

Языковые конструкции, требующие условия/объявления и блока кода, вызовут эту ошибку.

Список параметров функции/метода

Условные конструкции

То же самое для частых используемых конструкций: for / foreach , while / do , etc.

Как минимум всегда смотрите документацию, чтобы сравнить, правильно ли вы пишите ne или иную конструкцию/функцию/метод/класс и т.д.

Unexpected T_CONSTANT_ENCAPSED_STRING

Unexpected T_ENCAPSED_AND_WHITESPACE

Предупреждения T_ENCAPSED… появляются в контексте строки с двойными кавычками, в то время как строки T_CONSTANT… часто возникают в простых выражениях или операторах PHP.

Неправильная интерполяция переменных

Ключи массива должны быть в кавычках. Но в строках с двойными кавычками (или HEREDOC) это не так. Парсер жалуется на содержащуюся в одинарных кавычках строку.

Можно использовать PHP2-style для написания ключей мамссивов внутри строки

Но лучше изучить фигурный синтаксис и использовать его. Он позволяет писать ключи массива как обычно:

Отсутствует конкатенация

Отсутствует начальная кавычка

Пропущена запятая в массиве

Пропущена запятая в аргументах функции/метода

Строка закрыта слишком поздно

Отступ в HEREDOC

До версии 7.3 закрывающий идентификатор должен был находиться в самом начале новой строки. Поэтому код ниже вызовет ошибку

Unexpected $end

Unexpected end of file

Ошибка означает, что код закончился, в то время как парсер ожидает больше кода. (Сообщение немного вводит в заблуждение, если понимать его буквально. Речь идет не о переменной с именем «$end», как иногда предполагают новички. Оно относится к «концу файла»). Причина: несовпадение количества открывающих и закрывающих фигурных скобок.

Почти всегда речь идет об отсутствующей закрывающей фигурной скобке > для закрытия предшествующих блоков кода. Это говорит о том, что синтаксический анализатор ожидает найти закрывающую скобку > , но на самом деле достиг конца файла.

  • Используйте правильные отступы, чтобы избежать таких проблем. И вообще, в принципе, используйте отступы и форматирование!
  • Используйте IDE с сопоставлением скобок, чтобы выяснить, где > была утеряна. Большинство IDE выделяют совпадающие фигурные скобки, квадратные скобки и круглые скобки. Что позволяет довольно легко проверить соответствие:

Отступ в HEREDOC

До версии 7.3 закрывающий идентификатор должен был находиться в самом начале новой строки. Поэтому код ниже может вызывать ошибку

Заэкранированная кавычка

Символ имеет особое значение. Часто символ применяют для экранирования в строках. Чтобы кавычка внутри строки, которая обёрнута в такие же кавычки, печаталась как есть, то её экранируют. Т.е. строка echo «Jim said »Hello»»; выведет Jim said «hello» . Если применить последовательность » , то она будет расценена как попытка экранирования кавычки. Поэтому строка ниже, выдаст ошибку

правильно будет экранировать обратные слэши тоже:

С другой стороны, PHP обычно преобразует пути в стиле Unix (например, «C:/xampp/htdocs/» ) в правильный путь для Windows.

Альтернативный синтаксис

Несколько реже вы можете увидеть эту синтаксическую ошибку при использовании альтернативного синтаксиса для блоков операторов/кодов в шаблонах. Используя if: и else: отсутствует endif; , например (т.е. закрывающий тег)

Unexpected T_FUNCTION

Может возникнуть например в версии PHP ниже 5.3.0, когда не было ещё анонимных функций. В некоторые функции, такие как array_map нужно было передать имя функции обработчика, например $range = array_map( «name_of_function_to_call», $myArray ); . Так что минимум надо проверить версию PHP и проверить что именно на вход ожадает текущая функция. И принять решение: повысить версию PHP или переписать под старый стиль: создать отдельно функцию и во вторую передать имя первой.

Источник

За последние 24 часа нас посетили 11420 программистов и 1106 роботов. Сейчас ищут 180 программистов …

Страница 1 из 11


  1. kfurious

    kfurious
    Активный пользователь

    С нами с:
    15 авг 2008
    Сообщения:
    5
    Симпатии:
    0

    Здравствуйте, я только начал постигать азы PHP и у меня возникла проблема. Мне нужно написать скрипт, который будет передавать данные формы в базу данных. Вот код:

    1. <p>Регистрация новых участников гильдии:</p>
    2. <form id=»form1″ name=»form1″ method=»post» action=»»>
    3.   <input type=»text» name=»nickname» id=»textfield» />
    4. <form id=»form2″ name=»form2″ method=»post» action=»»>
    5.   <input type=»text» name=»level» id=»textfield2″/>
    6. <form id=»form3″ name=»form3″ method=»post» action=»»>
    7.   <input type=»text» name=»class» id=»textfield3″ />
    8. <form id=»form4″ name=»form4″ method=»post» action=»»>
    9.   <input type=»text» name=»rang» id=»textfield4″ />
    10. <form id=»form5″ name=»form5″ method=»post» action=»keypress»>
    11.   <input type=»submit» name=»button» id=»button» value=»добавить»  />
    12. {$query=«insert into sostav(nickname,level,class,rang) values($_REQUEST[‘form1] $_REQUEST[‘form2’] $_REQUEST[‘form3’] $_REQUEST[‘form4’])»;

    Но при обработке браузером кода появляется ошибка syntax error, unexpected T_VARIABLE on line 44(линию в коде отметил). Объясните пожалуйста причину этой ошибки, и укажите на какие-либо другие, если они есть.Заранее спасибо.


  2. Luge

    С нами с:
    2 фев 2007
    Сообщения:
    4.680
    Симпатии:
    1
    Адрес:
    Минск

    $dbhost=»localhost» забыл точку с запятой поставить.


  3. kfurious

    kfurious
    Активный пользователь

    С нами с:
    15 авг 2008
    Сообщения:
    5
    Симпатии:
    0

    Спасибо, глупая ошибка. теперь вот такая проблема возникла Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:xampphtdocsmyprojectregistration.php on line 47


  4. Luge

    С нами с:
    2 фев 2007
    Сообщения:
    4.680
    Симпатии:
    1
    Адрес:
    Минск

    1. <? $query=«insert into sostav(nickname,level,class,rang) values({$_REQUEST[‘form1’]}{$_REQUEST[‘form2’]}{$_REQUEST[‘form3’]}{$_REQUEST[‘form4’]}; 

    но оставлять так тоже не стоит. Так как можно получить sql-инъекцию. Поэтому надо ещё использовать mysql_real_escape_string, а перед составлением запроса проверить данные на соответстие тому, что должен был ввести пользователь.

    и после mysql_query($query,$link) тоже нужна ;


  5. kfurious

    kfurious
    Активный пользователь

    С нами с:
    15 авг 2008
    Сообщения:
    5
    Симпатии:
    0

    Спасибо большое, разобрался.


  6. Opo6ac

    Opo6ac
    Активный пользователь

    С нами с:
    12 дек 2008
    Сообщения:
    3
    Симпатии:
    0

    Вроде как тоже в тему, поможите?
    суть вопроса:
    нужно в нижеприведенной строчке слово bracer заменить значением переменной $slot

    1. <div align=center><strong><? echo $target_user->bracer[0][name]?></strong></div><br>

    Обкладывание кавычками и точками не помогло, простая замена bracer на $slot — тоже… как правильно?

    Это ответ на вариант с точками и кавычками:

    1. Parse error: syntax error, unexpected ‘.’, expecting T_STRING or T_VARIABLE or ‘{‘ or ‘$’ in /home/u28995/lebargecityru/www/voc/designes/default/item_show.php on line 11

    Это ответ на замену brace на $slot:

    1. Fatal error: Cannot use string offset as an array in /home/u28995/lebargecityru/www/voc/designes/default/item_show.php on line 11

    $slot=»bracer» — задается ссылкой из другого фрейма
    $targe_user->bracer[0][name] — тоже не пустой, т.е. самая первая приведенная строчка работает. Но нужна универсальность, чтобы она работала с передаваемым через $slot аргументом массива

  7. Opo6ac
    Попробуй

    1. echo $vars[$slot][0][«name»]; 

  8. Opo6ac

    Opo6ac
    Активный пользователь

    С нами с:
    12 дек 2008
    Сообщения:
    3
    Симпатии:
    0

    Спасибо! помогло (С)))

    Если можно, объясните в двух словах суть конструкции?


  9. Sergey89

    Sergey89
    Активный пользователь

    С нами с:
    4 янв 2007
    Сообщения:
    4.796
    Симпатии:
    0

    1. $target_user->{$slot}[0][‘name’] 


  10. Opo6ac

    Opo6ac
    Активный пользователь

    С нами с:
    12 дек 2008
    Сообщения:
    3
    Симпатии:
    0

    Кхм… второй вариант видится более лаконичным и, чего уж скрывать — более правильным. Спасибо, Сергей! Оба варианта — рабочие


  11. lela

    lela
    Активный пользователь

    С нами с:
    7 фев 2009
    Сообщения:
    7
    Симпатии:
    0
    Адрес:
    Казахстан

    доброго времени суток!
    у меня та же ошибка:
    Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/kobrakz/public_html/private.php on line 34

    лайн 34:
    $res_login = mysql_query(«select login from users where login=’$_SESSION[‘userid’]'»);

    выше $_SESSION[‘userid’] = $_POST[‘userid’]; (данные получаю из другой формы)

    в чем может быть дело?


  12. Kreker

    С нами с:
    8 апр 2007
    Сообщения:
    5.433
    Симпатии:
    0

    lela
    PHP запутался в кавычках


  13. lela

    lela
    Активный пользователь

    С нами с:
    7 фев 2009
    Сообщения:
    7
    Симпатии:
    0
    Адрес:
    Казахстан


  14. House M.D.

    House M.D.
    Активный пользователь

    С нами с:
    11 фев 2009
    Сообщения:
    1
    Симпатии:
    0

    1.  <center>’Spisok file servers'</center>
    2.     function echoservers (ip){
    3.     $sql=SELECT*FROM servers WHERE ip=‘$ip’;
    4.     echo «<p> Nazvanie Servera: «, $name, «</p>»; // название сервера
    5.     echo «<p> IP-adress: «,  $ip, «</p>»; // ип сервера
    6.     echo «<p> Adminstrator: «,  $master, «</p>»; // ник хозяина сервера
    7.     echo «<p> Size: «, $size , » gb</p>»; // объем
    8.     /*кароче тут рейтинг типо будет*/
    9.     echo «<p> Opisanie: «,  $desc,  «</p>»; // описание
    10.     echo «<p> Read-Only «,  $write,  «</p>»; // чтение (данет)
    11.     echo «<p> Dostup «,  $share , «</p>»; //доступ
    12.     echo «<p> Full opisanie: «,  $fulldesc , «</p>»; // полное описание
    13. [url=»edit.php»]Edit info[/url]

    :oops: я полный нуб но очень нужно разобраться почему этот код выдает ошибку:
    Parse error: syntax error, unexpected ‘)’, expecting ‘&’ or T_VARIABLE in /pub/web/givi/fileserv.php on line 5


  15. unicross

    unicross
    Активный пользователь

    С нами с:
    14 янв 2009
    Сообщения:
    194
    Симпатии:
    0

    А кто за вас будет строки в кавычки заключать???

    1. $sql=«SELECT*FROM servers WHERE ip=’$ip‘»;

    Что такое ip??? Если переменная, то $ip


  16. RAIDERS

    RAIDERS
    Активный пользователь

    С нами с:
    4 мар 2009
    Сообщения:
    2
    Симпатии:
    0

    1. <input name=«ok» type=«hidden» value=«ok»>
    2. <input name=«start» type=«hidden» value=«ok»>
    3. <br /> <input type=«submit» value=»                    »» class=b onclick=«if(ss){if(document.getElementById(‘ig’).checked==false){alert(‘                                     ,                                             ‘);return false;}}»>
    4. if(!isset($_POST[‘start’])) st();            //линия 245!!!
    5.         IF (isset($_POST[‘autobackup’]))
    6.          $get_mixdate = date («YmdHis»);
    7.          $dir_bkp = ‘backupfiles_’.$get_mixdate;
    8.          FOR ($x = 0; $x < count($bacupfiles); $x++)

    Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/a1680670/public_html/dle_photo.php on line 245

    Вот в чем может быть дело?


  17. Kreker

    С нами с:
    8 апр 2007
    Сообщения:
    5.433
    Симпатии:
    0

    RAIDERS
    http://phpfaq.ru/debug

    Лес, Шишка, Дорога,.

    Стоит пробел в закрывающем хередоке еще вроде.


  18. RAIDERS

    RAIDERS
    Активный пользователь

    С нами с:
    4 мар 2009
    Сообщения:
    2
    Симпатии:
    0

    Kreker Где именно прост я плохо в пхп разбираюсь((


  19. Kemel

    Kemel
    Активный пользователь

    С нами с:
    5 апр 2009
    Сообщения:
    1
    Симпатии:
    0

    <?
    final class protection {
    static public $_get;
    static public $_post;

    static public post_decode(){
    foreach($_POST as $key=>$value){
    $key=htmlspecialchars($key);
    if(is_array($value)){
    $value=$value;
    foreach($value as $sub_key=>$sub_value){
    $sub_key=htmlspecialchars($sub_key);
    if(is_string($sub_value)){
    $sub_value=htmlspecialchars($sub_value);
    }elseif(is_int($sub_value)){
    $sub_value=(int)$sub_value;
    }
    self::$_post[$key][$sub_key]=$sub_value;
    }
    }elseif(is_string($value)){
    $value=htmlspecialchars($value);
    self::$_post[$key]=$value;
    }elseif(is_int($value)){
    $value=(int)$value;
    self::$_post[$key]=$value;
    }
    }
    $_POST=array();
    }
    static public get_decode(){
    foreach($_GET as $key=>$value){
    $key=htmlspecialchars($key);
    if(is_string($value)){
    $value=htmlspecialchars($value);
    self::$_get[$key]=$value;
    }elseif(is_int($value)){
    $value=(int)$value;
    self::$_get[$key]=$value;
    }
    }
    $_GET=array();
    }
    }
    ?>

    Че за ошибка Parse error: syntax error, unexpected T_CLASS, expecting T_STRING in C:SERVERhomemirv.rudefen.php on line 2


  20. Luge

    С нами с:
    2 фев 2007
    Сообщения:
    4.680
    Симпатии:
    1
    Адрес:
    Минск


  21. OLEG55

    OLEG55
    Активный пользователь

    С нами с:
    9 апр 2009
    Сообщения:
    5
    Симпатии:
    0

    U menja problema
    Parse error: syntax error, unexpected T_VARIABLE in U:hometest1.ruwwwresult_mysqlphp.php on line 78

    1. if (isset($_POST[‘company’]))
    2. $company = $_POST[‘company’];
    3. if (isset($_POST[‘profile’]))
    4. $profile = $_POST[‘profile’];
    5. if (isset($_POST[‘profile2’]))
    6. $profile2 = $_POST[‘profile2’];
    7. if (isset($_POST[‘name1’]))
    8. $name1 = $_POST[‘name1’];
    9. if (isset($_POST[‘name2’]))
    10. $name2 = $_POST[‘name2’];
    11. if (isset($_POST[‘job’]))
    12. if (isset($_POST[‘job2’]))
    13. if (isset($_POST[‘address’]))
    14. $address = $_POST[‘address’];
    15. if (isset($_POST[‘address2’]))
    16. $address2 = $_POST[‘address2’];
    17. if (isset($_POST[‘phone’]))
    18. $phone = $_POST[‘phone’];
    19. if (isset($_POST[‘phone2’]))
    20. $phone2 = $_POST[‘phone2’];
    21. if (isset($_POST[’email’]))
    22. $email = $_POST[’email’];
    23. if (isset($_POST[‘www’]))
    24. $result2 = mysql_query («INSERT INTO vizitka_client (company, profile,
    25. profile2, name1,name2,job,job2,address,address2,phone,phone2,email,www)
    26. VALUES (‘$company‘,’$profile‘,’$profile2‘,’$name1‘,’$name2‘,’$job‘,
    27. $job2‘,’$address‘,’$address2‘,’$phone‘,’$phone2‘,’$email‘,’www’)»);
    28. echo «Infa dobavlena uspewa»;
    29. echo «infa ne dobavlena»;

    Uze zaputalsa ja noob v etom dele no o4en nuzna….


  22. kas1e

    kas1e
    Активный пользователь

    С нами с:
    6 апр 2009
    Сообщения:
    280
    Симпатии:
    0

    строка 75закрывать операторы не забываем, да?

    с такой ошибкой смотри предыдущую строку всегда.

    P.S.

    1. #  $result2 = mysql_query («INSERT INTO vizitka_client (company, profile,
    2. #  profile2, name1,name2,job,job2,address,address2,phone,phone2,email,www)
    3. #  VALUES (‘$company’,’$profile’,’$profile2′,’$name1′,’$name2′,’$job’,
    4. #  ‘$job2′,’$address’,’$address2′,’$phone’,’$phone2′,’$email’,’www’)»); 

    ‘$email’,’www’ — могу предположить, что пропущено $ у переменной www.

    P.P.S.
    И почитай статьи на тему защиты, ломануть 5 секунд этот скрипт.


  23. OLEG55

    OLEG55
    Активный пользователь

    С нами с:
    9 апр 2009
    Сообщения:
    5
    Симпатии:
    0

    kas1e
    sps razobralsa da ti bil prav ja tam propustil $ v 86 storke www.

    dlaee mne nuzno bilo zdelat 4tob skript pozicionirovanija dobavalsa v bazu teper kod vigledit tak

    1. $result2 = mysql_query («INSERT INTO vizitka_client (company, profile,
    2. profile2, name1,name2,job,job2,address,address2,phone,phone2,email,www,script_pos)
    3. VALUES (‘$company‘,’$profile‘,’$profile2‘,’$name1‘,’$name2‘,’$job‘,
    4. $job2‘,’$address‘,’$address2‘,’$phone‘,’$phone2‘,’$email‘,’$www‘,’$script_pos_k‘)»);
    5. $result = mysql_query(«SELECT script_pos FROM vizitka_def», $db);
    6. echo $myrow [«script_pos»];
    7. $result = $script_pos_k ;
    8. echo $myrow [«script_pos_k»];
    9. echo «Infa dobavlena uspew»;
    10. echo «infa ne dobavlena»;
    11. if ($script_pos_k == ‘true’)
    12. echo «<br>Infa pozicionirovanija dobavlena uspew»;
    13. echo «<br>Infa pozicionirovanija ne dobavlena»;

    vso dobovlaet vse danie a dobovlat sam skript pozocionirovanija ne ho4ew… pri4om nuzno sdelat tak 4tob on izmenonij dobovlal pomagite sdelat plz…

Страница 1 из 11

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Parse error syntax error unexpected expecting end of file in
  • Parse error syntax error unexpected end of file in что значит
  • Parse error syntax error unexpected end of file in wordpress
  • Parse error syntax error unexpected else
  • Parse error syntax error unexpected catch

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии