PHP 7 error 500 internal - php

I'm completely lost with an "500 internal server error".
Yesterday I updated to PHP 7.1.2 and then there were a lot of errors.
I solved them almost all except for this strange coding error.
When trying to find the problem I echoed some output to the screen.
And this is what happens:
for($iRecordNumber=0;$iRecordNumber==$iTotalAssignments;$iRecordNumber++){
$iNextRecordNumber = $iRecordNumber+1;
echo $iNextRecordNumber;
echo $aAssignments[$iRecordNumber][2];
echo $aAssignments[$iNextRecordNumber][2];
}
With this code I get the "500-error".
When I comment out the line with echo $aAssignments[$iNextRecordNumber][2]; the error is gone and it does what it should do. Showing me a record from the nested array $aAssignments(PDO query).
for($iRecordNumber=0;$iRecordNumber==$iTotalAssignments;$iRecordNumber++){
$iNextRecordNumber = $iRecordNumber+1;
echo $iNextRecordNumber;
echo $aAssignments[$iRecordNumber][2];
// echo $aAssignments[$iNextRecordNumber][2];
}
I looked through the Backward compatabilty list but did not find anything.
And the tool codechecker says it's good too.
I dont know how this is possible.
What can I do to find an answer? Are there any programs or code checkers to check for more php 7 errors in my code. I have several php sites running and I do not want to check all code manually for errors.

I think $aAssignments[$iNextRecordNumber][2] is not always set.
You could replace:
echo $aAssignments[$iNextRecordNumber][2];
By:
echo $aAssignments[$iNextRecordNumber][2]?? '';
I hope it could help.

In PHP 7 is the error handling completly revised. A fatal error other errors no longer stops the script. To find these kind of errors, use the new error() method in the try and catch class. For example:
try{
code to test on errors
} catch(error $eCatchedError) {
echo get_class($eCatchedError)."<br>".$eCatchedError->getLine()."<br>".$eCatchedError->getFile()."<br>".$eCatchedError->getMessage();
} // End try and catch
By this way you get an more elegant way of showing an error (with css and everything)

Related

PHP if(!#include_once()) doesn't work

This was working and then it stopped. That was in version 7.2.6 the latest.
if(!#include_once('config.php')) {
echo 'failed';
}
So we've downgraded to 7.1.9 but it doesn't work there as well.
There is no error thrown, nothing. Just a blank screen. It's as if it's not even there...
If I echo something before that, it works. If I echo something after this, nothing happens.
Why is this happening?
what, exactly, do you think # does? it suppresses errors. so when you say There is no error thrown, nothing, this is totally expected, because if there is any errors, # probably suppress them. remove the #, and if you can't trust your php.ini settings, do an ini_set call too, also set in some debug prints, eg
ini_set("error_reporting","-1");
echo "before include.";
if(!include_once('config.php')) {
echo 'failed';
}
echo "after include";
then check your error logs after it executed.
Maybe you could try the advice around "example #4" on this page and see if that makes a difference?
http://php.net/manual/en/function.include.php
E.g.
if ((#include_once 'config.php') === FALSE) {
echo "failed";
}
By the way: as other's have said, # suppresses PHP warnings/errors for the line of code where it's applied.
My interpretation of your question is that you have used # deliberately to suppress the engine's warning and echo your own message instead. If you removed the # and the include failed, I'd expect to see the warning message output if errors are set to show, AND the word 'failed' should still be echoed afterwards.
This is how I solved it.
if (!(#include 'config.php')) { die(json_encode(array('error'=>true))); }
I need the error to be suppressed because I wan't to handle the error without breaking my script—in a way that the other end know's it's an error and will inform the front-end user.

#date_default_timezone_get() silently crashes

I have the following test code:
<html>
<body>
<p>
Hi
</p>
<?php
if (function_exists('date_default_timezone_get')) {
echo "J";
$timezone = #date_default_timezone_get();
echo "K";
date_default_timezone_set($timezone);
echo "L";
}
phpinfo();
?>
</body>
</html>
When I retrieve it through my apparently working apache I get just:
<html>
<body>
<p>
Hi
</p>
J
If I comment out the '$timezone = #date_default_timezone_get();' then I get a response with an error about '$timezone' not being defined and then the standard phpinfo() output.
All of the debugging options I've found thus far don't show me anything of interest in any log.
Running the script with php on the command line it gives no error either.
FYI: This is me attempting to figure out why my websvn suddenly stopped working, I've narrowed down the failure to this line and it fails in the sample code, so I'm feeling reasonably good about this other than why it just wont work.
Why are you keeping the # before the function call? It suppresses the error output which may be of help.
Also, what PHP version are you using? DateTime functions are only enabled by default since 5.2.0.
I wouldn't also exclude the possibility that even though date_default_timezone_get() function exists, it is not a standard one that comes with PHP, but something custom-made instead.
After commenting out the call entirely in websvn I got a new error from another line:
Timezone database is corrupt - this should never happen!
This error led me to investigate what was wrong with my timezone info and apparently all of files in /usr/share/zoneinfo/ had 640 permissions, changing them to 644 and the errors have gone.

Exception MongoCursorException: couldn't send query: ët§ôï9·H'ﯤ7·ø?u§Ht§ ö·Ì­u§®u§Ì½u§4e

I am trying to talk to a remote MongoDB server from my system. The code i use is like this
$con_string='mongodb://server_ip:27017';
$m = new Mongo($con_string);
$temp=$m->selectDB("DBName");
try {
$mc=$temp->collection_name->find()->limit(5);
var_dump($mc->info());
var_dump(iterator_to_array($mc));
}
catch (MongoCursorException $e) {
echo "error message: ".$e->getMessage()."</br>";
echo "error code: ".$e->getCode();
}
Now i get the following message from Xdebug
MongoCursorException: couldn't send query: ët§ôï9·H'ﯤ7·ø?u§Ht§ ö·Ì­u§®u§Ì½u§4e
Why is this exception raised and why is there junk at the end of exception. I dont get this exception every time but 5 out of 6 times.
Also the message i got from catch block is
error message: couldn't send query: QY¥ôï9·H§ï³¤7·DCY¥h §
error code: 14
The error code 14 means "C socket error on send." says the PHP manual.
What does this error mean?
A guy in chat suggested that the junk is indicator that the data might not be utf8_encoded but i am doing a simple find() with no criteria so what do i need to encode?
EDIT:
To get around this scenario i wrote this
function getCursor($conn,$db_name,$coll_name,$query_options=array(),$fields=array(),$cursor_options=array(),$max_tries=0) {
$counter=0;
while(1) {
try {
$cursor=new MongoCursor($conn,$db_name.'.'.$coll_name,$query_options,$fields);
if (array_key_exists('count',$cursor_options))
return $cursor->count();
if (array_key_exists('limit',$cursor_options))
$cursor=$cursor->limit($cursor_options['limit']);
if (array_key_exists('skip',$cursor_options))
$cursor=$cursor->skip($cursor_options['skip']);
if (array_key_exists('sort',$cursor_options))
$cursor=$cursor->sort($cursor_options['sort']);
return $cursor;
}
catch (MongoCursorException $e) {
$counter+=1;
if ($max_tries>0) {
if ($counter>$max_tries)
echo "error message: ".$e->getMessage()."\n";
echo "error code: ".$e->getCode()."\n";
return false;
}
}
}
}
The functions takes the query parameters and then send the query to the server and if the MongoCursorException is raised it sends the query again. It does this $max_tries times. If $max_tries is set to 0 it will keep on sending this query to the server until the query succeeds. Maybe this is stupid, i should have set this to some fixed value like 50. On success the function returns the cursor except when your looking for the count and in that case it returns the count
Your string looks like that if:
You have a charset encoding issue
Memory is broken
As in your code not much strings are involved, the chances that this is an encoding issue are not very high.
But as Xdebug is a PHP extension that deals a lot with internals, breaking memory can be one thing.
An easy way to find out is to disable the extension you suspect that is causing the issue, e.g. xdebug.
It is also useful for documentation purposes tp write down which PHP and extension versions you are using as well as on which operating system. I asked for that in comments, it's a list like:
PHP 5.3.10
Mongodb Extension 1.2.10
Mongodb Server 2.0.6
Xdebug 2.2.0
Centos 6.2 64-bit
Checking the website for xdebug shows that there is a new version available. As you have found out earlier by disabling xdebug that it influences the result, try with updating the xdebug extension and see if it helps.
Even if it does, keep your version list for further reference (as well with a short description of the problem), because in case the problem is not fully solved with the upgrade, this information can be very useful at a later time to do a useful bug-report. Those internal problems in the software are sometimes hard to spot, so the information can help to reproduce easier then or to identify the areas involved.
This is fixed in Mongo driver v1.3+
ref: https://groups.google.com/forum/?fromgroups=#!topic/mongodb-user/IJ1n_Xt_al8
Downloads: http://docs.mongodb.org/ecosystem/drivers/

PHP looping failure when array reaches certain size

This has been edited a bit, sorry if any comments are out of context.
So, I'm working on the targeting challenge from gild.com. My solution concept is:
1) determine the worth of each target option (as defined by: how many options remain if it is struck)
2) slice the array at that strike point
3) drop any items with a Value lower that the last strike
4) repeat until array is empty
5) return count of strikes
Here's my latest code. I am on shared 1&1 hosting so I don't have direct access to error logs. I had a workaround in place but it's no longer writing to that file (so I'm guessing the error has changed). But when I was getting output, it was always an undefined offset...
UPDATE: now I've been playing around with echoing output from various points to see what's happening, and I found that this prevents a formal error, but it stops echoing after the depth++; loop
<?php
set_time_limit(0);
$targets=array();
$file="http://www.gild.com/coding_test_cases/missile/missile-a.in";
$input=file_get_contents($file);
$input=str_replace("\n\n","\n",$input);
$targets=explode("\n",$input);
if(strlen($targets[count($targets)-1])==0){
array_pop($targets);
}
$rich=array();
$order=array();
while(count($targets)>0){
for($i=0;$i<count($targets);$i++){
$key=$i;
$depth=0;
while($key<count($targets)){
if($targets[$key]>$targets[$i]){
$depth++;
}
$key++;
}
$rich[$i]=$depth;
echo "."; //-----------------------------------I will make it to the screen
}
echo "hi"; //--------------------------------------------------------I will not
$last_strike=$targets[array_pop(array_keys($rich,max($rich)))];
array_push($order,$last_strike);
$targets=array_slice($targets,array_pop(array_keys($rich,max($rich)))+1);
$rich=array();
$c=count($targets);
for($b=0;$b<$c;$b++){
if($targets[$b]<$last_strike){
array_splice($targets,$b,1,true);
$b--;
$c--;
}
}
}
echo count($order)."\n";
?>
Maybe I'm missing something but isn't your entire code snippet equivalent to this?
$rich = range($_GET['lim'] - 1, 0);
echo $rich[0];
As for your actual error, it sounds like a memory allocation problem. Try rethinking your algorithm for this problem.
I think reason that you have 500 error instead of Human-readable error is switched off dislay_errors ini setting.
Try to switch on it or find error message in your Apache error log

PHP voting code works on 5.2.5 but not on 5.2.11 anymore

Ok, so a little while back I had some help writing some PHP voting code, it worked just fine after I upgraded my server to use the latest version of PHP. However now I have switched servers, and the PHP isn't as up to date as the other one. Anyways here's my code:
<?php
if(!file_exists('vote/1u.txt')){
file_put_contents('vote/1u.txt', '+1');
}
if($_GET['click'] == 'up1'){
file_put_contents('vote/1u.txt', ((int) file_get_contents('vote/1u.txt')) + 1);
header('Location: ' . $_SERVER['SCRIPT_NAME']);
die;
}
?>
Execute and display:
<img src="images/thumbsup.jpg" width="40px"border="0"> <br>Votes: <?php echo file_get_contents('vote/up1.txt'); ?>
Now when on my other server (PHP version 5.2.5) this code worked great! However on my new server the PHP version is 5.2.11, and because of this the code won't work. My question is, is there any way to make this more compatible with an earlier version of PHP, or to write completely new code that will work just like this one? Or is there a way to tell my servers to use PHP 5.2.5+? I'm using cPanel X admin panel.
I have set the text file permissions to 777 and still nothing!
you are checking for variable "click" but executing the code only if it equals "up1".
But your link tells click to equals "yes" so that part of the code is never true, hence never executed.
Change your executor to this:
<img src="images/thumbsup.jpg" width="40px"border="0"> <br>Votes: <?php echo file_get_contents('counteru.txt'); ?>
But more logically, your processing code should be rationalized a bit to this:
if the link is clicked :
First, if the data file (lu.txt) does not exist, create it and write '+1' inside of it, else, add 1 to its existing value.
Then, redirects to the initial page.
if($_GET['click'] == 'up1'){
if(!file_exists('vote/1u.txt')){
file_put_contents('vote/1u.txt', '+1');
}else{
$content = file_get_contents('vote/1u.txt');
if(!$content){
die("Error! file_get_content failed !");
}
file_put_contents('vote/1u.txt', ((int)$content) + 1);
}
header('Location: ' . $_SERVER['SCRIPT_NAME']);
}
exit;
Not a bad idea to add a trim() around file_get_contents(). Or to check if $_GET['click'] isset() prior to checking if it's equal to 'up1'.
It's conventional to exit() instead of die() after a header redirect--well, from what I've seen at least.
Basically, during development, turn on error reporting and set your error flag to E_ALL to see everything, including warnings and notices--neither of which halt your code, but should still be known and addressed.
You might discover the reason your code produces different outcomes under different minor versions of PHP by turning on full error reporting.

Categories