Does PHP sometimes ignore function redeclarations? - php

I am working on a website with a few friends, and recently, users have complained about a fairly important feature doing nothing but return a blank page. This only happens for some users, while other users are able to use it perfectly fine.
I consulted debug output and it turns out that a function is being declared twice. Once in the feature's main page (foo.php) and one in a file that gets require_once'ed. Obviously I'm on the right path to fixing it now, but what confuses me is that many people do not get this problem when visiting the page. Both function declarations are identical; the bodies seem to have been copy+pasted from one file to the other. Neither of these function declarations are conditional; they should both always take place.
Does anybody know of situations where PHP will be able to handle my mistake and make the page work anyway, despite this fatal error?

it may be the type of your function declaration is public,private or protected so that you might be not getting fatal errors by luck as till to my knowledge php does not allow function redeclaration in or by any means .

Sorry, PHP can never ignore fatal errors or function redeclarations, because in that cases, PHP will be confused as to what function declarations to consider, whether to use a old declaration or a new declaration.
Fatal Error means, there has something is so wrong, that PHP is confused as to what to do next, and therefore its your job to do it right.
Sorry PHP wont try to figure out as if two or more declarations were same and then ignore one of them. If this had to be done, the already slow PHP will become even more slower. So in the interest of community, you should consider writing a correct code, rather then asking PHP interpreter to correct this for you.

Related

Laravel log changes without action, helpers.php issue

During the development, I opened website logs and found a large number of errors with the same text:
local.ERROR: Cannot redeclare fun() (previously declared in C:\laragon\www\am\bootstrap\helpers.php:10) {"exception":"[object] (Symfony\\Component\\ErrorHandler\\Error\\FatalError(code: 0): Cannot redeclare errorText() (previously declared in C:\\laragon\\www\\am\\bootstrap\\helpers.php:10) at C:\\laragon\\www\\am\\app\\helpers.php:10)
At first I thought that these errors occur in parallel with my action on local website, but it turned out that these errors appear every 1 minute in the logs. I do not understand what provokes them. There are no such errors in the browser during operation, even if the website without action for several hours, logs still fill every minute.
I learned everything I could about the help file. The only option is to check if the function exists, but this is not the best practice, especially since the site works and does not give any errors in the process.
Fucntion check example:
if (! function_exists('fun')) {
function fun($field) {
return view('static.error', ['field' => $field]);
}
}
But rewriting and wrapping dozens of functions is not a good idea. Moreover, the problem remains and it is still not clear to me where and how these errors appear, what provokes them? Additionally considering that I have a static php website.
I will try to explain everything in the simplest possible language. A long search for an answer led me to the obvious thing. The whole problem is solved by creating a file inside bootstrap laravel directory. I trusted the opinion of the weighty answers here, but they are no longer relevant for today's queries.
It is also very important not to leave helpers.php inside app directory, even if it is not connected anywhere. This is what caused constant log entries.
All this will avoid duplication errors of any type and and will be compliant.

Mad PHP - Randomly, Sometimes Some Built-in Functions Becomes Undefined While Other Times Ramaining Defined

[Update 18.01.14]
This question was marked a duplicate of Intermittent PHP Abstract Class Error . However, they are different in much of the bug appearance as follows.
That link only have contains x abstract method error. But mine have more types, and the errors are more weird (see the errors below, even containing some control characters).
In that link, the questioner said disabling opcache will make it happen less frequently. But in my case I did never enable the opcache but these bugs happened.
[/Update]
I am using Apache, PHP, Laravel to develop my web backend. But several times a day, errors will occur saying some php built-in functions are undefined, but at other time when it is not mad, these functions are obviously defined and work well. (So it is not because I call something really undefined!)
There are even stranger things. The "undefined" things can be a php function, system constant, or even some strange strings which look like regex, or even control characters in ASCII! The examples are as follows.
Declaration of PDO::() should be compatible with PDO::?)[CHAR1][CHAR2] where the [CHAR1] and [CHAR2] are SOHand ETX in ASCII.
Call to undefined method #^\\{\\w+\\}#::format()
Call to undefined method DateTime::format()
Undefined class constant 'PDO::ERRMODE_EXCEPTION'
(Other types of errors) Class Doctrine\DBAL\Driver\PDOStatement contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Doctrine\DBAL\Driver\Statement::errorInfo, Doctrine\DBAL\Driver\ResultStatement::closeCursor)
Here are some more information: It usually happens every several hours, but can happen in half an hour or do not happen for half a day. My server handles about 1 http GET or POST request every second from one of the 6 remote machines.
This annoys me for a very long time and I would appreciate it if anyone could help me! Thank you so much!

PHP: if ($Name=='ProxiedIP') leads to 500 (Internal Server Error)

This may be too obscure of an question, but I've been troubleshooting a baffling server error for hours and have pinned it down to the most bizarre issue; at this point I just want to know if anyone has ever had something similar occur, or might have any insight into what might possibly be happening.
The following line of code is triggering the error:
if ($Name=='ProxiedIP') { return true; }
This version runs without any problem at all:
if ($Name=='proxiedIP') { return true; }
It seems like somehow the token 'ProxiedIP' is fouling something up, but I cannot even think of how a string literal would be translated by the parser in a way that could hang the server up like this. BTW, I know for certain that $Name!='proxiedIP' and $Name!='ProxiedIP'.
Here's the entry in the apache error log:
[Fri Jan 18 18:15:12.924419 2013] [core:error] [pid 27676:tid 3427232831232] [client 12.345.67.890:34482] Premature end of script headers: index.php, referer: http://mySite.com/
I searched for 'ProxiedIP' as a keyword for every component that I can think of on my system and I'm coming up with nothing. The more imperative question for me though is how a string could somehow have this impact in a comparison check. Any ideas?
Also noteworthy that the PHP error log is completely silent about it. I'm enabling error output at the top of the page, but the script never finishes loading so that may be a factor. Here's how I'm setting it:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Because the code worked here, it seems more likely that it could be something specific to the platform implementation. I'm running this on an instance of Gandi.net's 'Simple Hosting' service, which runs Varnish for application acceleration. It may also be worth mentioning that the code is being loaded in an iframe in a separate domain.
I am also doing some intensive work with the headers, and this seems like the greatest potential source of the problem, although the strange thing as far as I'm concerned is the way the error is being triggered. Also, there's no common header that I'm aware of called 'ProxiedIP', although that use conflict is the only thing that seems like it could make sense so far. Regardless, I don't see it.
To me, the real item of relevance is the mere fact that a string comparison is crashing the server. I've been programming in PHP for over 10 years and I have never had anything like this happen before. I'm trying to understand the logistics behind how it could even happen.
Update: I've tried the following variation, and it still produces the same result:
if ($Name === (strtoupper("p").'roxiedIP')) { return true; }
It was asked whether I would post the full code, but the script for the iframe side is 1400+ lines long so that's not really feasible. I'm adapting the segment in question to try running it in a new script though and will post the results.
I think the problem is with the variable $Name. Check whether it is getting assigned properly. Also check the code after if statement which is causing the problem.
Actually, I think your problem lies in the calling function, i.e. depending on the return value it does something "stupid" and PHP crashes.
Try replacing the if() with a hard return true or return false and see what happens.
As i get from your error, you are messing up the framework, the change in that if of yours triggers some output being called before the fw is allowed to make output. Just read it in more detail, you got it on the wrong train, that is not the cause of the error, it is the beginning of an unhallowed state of the fw.
Try running the script in a php debugger rather then using var dump.
Thanks for the posts, but it turned out to be a really convoluted scenario, where conditions several levels down the function chain caused unexpected behavior outside the scope of either function in question.
The actual issue was due to a condition check while parsing through output of a debug_backtrace() array in a totally separate process, which ironically was in place to prevent infinite recursion and instead triggered a similarly disruptive cascade of events that overran the allocated memory limit.
I originally posted because I was baffled by what truly seemed to be a string literal comparison doing something I didn't think should be possible, and wanted to understand what conditions could allow it to happen if so. I'm just glad the cause wasn't actually what it seemed to be. Thanks for helping to solve the puzzle.
Update: The true source of the error hinges on PHP's difficulty translating objects or arrays that contain references to themselves. I'm storing converted headers, direct header references, $_REQUEST[] and $_SERVER[] items, as well as logging messages and associated data in complex associative arrays. There are a lot of dynamic references between these items, particularly those involving the native PHP globals which I've made use of.
PHP has traditionally had problems managing self-referencing entities, and although improvements have been made, my particular situation is complex enough to send ReflectionClass into an endless loop while attempting to map these objects. I've fixed it by manually dereferencing the items as I'm polling them, but it's something to be aware of if needing to work with multiple $GLOBALS-related vars within a common array or referencing structure.

PHP 4 to PHP 5 - isset checks on boolean if statements

Scenario:
We are in the process of converting an application from PHP 4 to PHP 5. The application needs to be able to work on PHP 4 for a little while, which means no PHP 5 specific elements can be used, yet. We are simply trying to make sure the application works on both platforms.
There are a lot of conditionals that look like this in the application:
if ($variable) { // do something }
Some of these variables end up not being defined at all and we are trying to reduce the number of errors (there's a lot of them).
To solve these errors, we are adding checks in various areas like this:
if (!isset($variable)) $variable = "";
or
if (!empty($variable)) { // do something }
Question:
Does anyone know of a simpler approach to fixing these errors. The problem is that these variables are being used across files (via includes) and defining the variable may change the logical flow in that file if its doing a check like (if (!isset($variable)) { // do something }).
The point of this question is to reduce errors and time consumption of tracking each individual use of these variables. Currently, we are having to either examine thoroughly what the variable is doing (which may take a good chunk of time), or we are doing a "fire and forget" / hope-its-fixed method of correcting.
-- Edit --
Does anyone know of a program like cppcheck for php that could somehow reference these variables or create some kind of chaining that could find errors and link possible references? (I hope that makes sense.)
AFAIK there is a code-checker that looks for uninitialized variables which works OK. You can work through it's messages, it's called PHP Mess Detector and one of it's rule covers uninitialized variables. However this can never be perfect.
Another method is to track the error messages and use them to locate the places within in the code. I've done that in the past and it worked very well, just do it in iterations and keep log of the warnings.
You can also work with a whitelist and import whitelisted variables when the request starts. Non-whitelisted submissions need to cause an access violation error to have this properly working, so this way is more work than tracking warnings albeit it might make your application more secure.
Please see as well:
PHP Syntax checking pre-source control
E_NOTICE ?== E_DEBUG, avoiding isset() and # with more sophisticated error_handler
isset() and empty() make code ugly

When to use Try Catch blocks

Ok, this might be a very noob question, but I find that PHP Documentation on that and several Internet Searches hasn't give me any idea about that.
When should I use try-catch blocks to improve my application?
I read someone saying that we should use try-catch blocks only to prevent fatal errors.
I read someone else saying that we should use it only on unexpected errors (wait what? unexpected? if they are unexpected errors how could I prevent them with try-catch? should I put all my application code inside a try block?).
Others simply say that try-catch blocks should be used everywhere because they can be also extended (extending the Exception class).
Finally someone says that PHP try-catch block are totally useless because they are very bad implemented. (On this I found a nice SO question about performance).
It seems to me that this topic is very strange and confused. Could someone lights me up?
It seems to me that this topic is very strange and confused. Could someone lights me up?
Definitely. I'm not a PHP user, but I might have a little insight after having worked with try/catch in ActionScript, Java, and JavaScript. Bear in mind though, that different languages and platforms encourage different uses for try/catch. That said...
The only times I'd recommend using try/catch is if you're using a native language function that
Can throw an error/exception
Does not give you any tools to detect whether you're about to do something stupid that would cause that error/exception. eg: In ActionScript, closing a loader that is not open will result in an error but the loader doesn't have an isOpen property to check so you're forced to wrap it in try/catch to silence an otherwise totally meaningless error.
The error/exception really is meaningless.
Let's take the examples you list and see how they square with that list.
I read someone saying that we should use try-catch blocks only to prevent fatal errors.
In the case of AS's loader.close() function, this is good advice. That's a fatal error, and all from an otherwise trivial misstep. On the other hand, virtually ALL errors in AS will bring your application to a halt. Would you then wrap them all in try/catch? Absolutely not! A "fatal error" is fatal for a reason. It means something terribly wrong has happened and for the application to continue on in a potentially "undefined" state is foolhardy. It's better to know an error happened and then fix it rather than just let it go.
I read someone else saying that we should use it only on unexpected errors
That's even worse. Those are presicely the errors you DON'T want to silence, because silencing them means that you're never going to find them. Maybe you're not swallowing them, though... maybe you're logging them. But why would you try/catch/log/continue as though nothing happened, allowing the program to run in a potentially dangerous and unexpected condition? Just let the error kick you in the teeth and then fix it. There's little more frustrating than trying to debug something that's wrong in a program that someone else wrote because they wrapped everything in a try/catch block and then neglected to log.
Others simply say that try-catch blocks should be used everywhere because they can be also extended (extending the Exception class).
There's potential merit to this if you're the one doing the throwing, and you're trying to alert yourself to an exceptional situation in your program... but why try/catch your own thrown error? Let it kick you in the teeth, then fix it so that you don't need to throw the error anymore.
Finally someone says that PHP try-catch block are totally useless because they are very bad implemented. (On this i find a nice SO question about performance).
Maybe so. I can't answer this one though.
So... this might be a bit of a religious question, and I'm certain people will disagree with me, but from my particular vantage point those are the lessons I've learned over the years about try/catch.
Different people will tell you different things. But this is what I think, specifically in the case of a web application.
Your whole page should be in a try/catch that displays an error message to the user. The error message shouldn't tell the user what happened in detail because thats a security concern. It should record information about the error into a log file.
The other case is where something could go wrong in the normal operation of affairs. PHP is not very exception happy so this may not happen very much. Basically, if you run into a function that throws an exception when it fails, you can catch the exception and do something else in that case.
In general, your question is like asking how you would use a hammer to improve the qualify of a house. Use exceptions to help you implement particular behaviors. Don't look for places to use exceptions.
I think it's simply a matter of preferences, but from my experiences, I'd encourage you to use them as much as possible.
In application we currently develop at work (using Zend Framework if it matters), we use one single try..catch block to catch all exceptions throughout the application which are shown to user as, for example, error 500s and exception is logged with more information to database. I, personally, love this approach in case of PHP application as exceptions are extendable and you can basically write whatever functionality you need.
I predominantly use Try/Catch around database calls...especially inputs, updates and deletes etc.
I sometimes use it around complex data processing with arrays and loops using dynamic data and arrays where there is a chance something might go wrong, ie: missing array elements or something (I normally check for stuff like that though).
I also use them around operations over which I don't have complete control such as importing data from an external or foreign data source where there could be problems with the data or accessing the source file.
I think what is meant by "Unexpected Errors" is where you can't prevent problems through good programming practices such as checking if a file exists before "including" it, Some problems you CAN anticipate so use good practices to prevent them. Don't just leave them to chance by wrapping them in a try/catch.
Use good programming practices instead as you should do everywhere. Don't use try/catch as a lazy shortcut for everything, everywhere. That's major overkill.
I agree with #scriptocalypse. In fact I only use try/catch blocks in PHP in 2 kind of situations.
If it's possible that some external (not inside my code) issues or DB errors may take place:
Getting data from another source (eg. curl)
Getting data from files
DB-Exceptions
If I work inside another system, like a CMS or similar and I want to override a certain behavior. For example I don't want an Exception being thrown but the exceptions message being returned to the view.
You cant put try catch blocks everywhere.
However during application testing, exceptions generated should alert you to places where you need try catches. This is one reason why you should run thorough testing of you application/code.
If you see a place where you think you need it, i would put one in.
EDIT: ok you CAN put them everywhere, but you need some sense as to where to put them in your code.
I normally put Try and Catch around areas in the code that have external forces acting on it that I have no control over. For example, Opening and reading external files.. you have no control that at some point in the reading of the file, the file becomes corrupted or something else happens that you can not control like the file server dc's or something

Categories