I'm refreshing some older code (someone else wrote), and came across this:
if ( empty ( $role_data["role_id" == 1]))
what are the reasons (if any) one would use the above instead of?:
if ( $role_data["role_id"] != 1)
IMO readability is worse and it's more code. Performance isn't a factor here.
--EDIT--
I should mention, that the expected input($role_data["role_id"]) is a number between 0 - 5 (inclusive)
--MORE INFO--
I've missunderstood the code the first time around.
But here's what's happening:
$role_id = htmlspecialchars ( mysql_real_escape_string ( $_GET["role_id"] ) );
$role_data = $db->fctSelectData ( "core_role" , "`role_id` = '" . $role_id . "'" );
This goes to get the permissions for creating the role. But if given an invalid $role_id in the first place (via the $_GET parameter), it returns nothing, hence checking for an empty value in:
if ( empty ( $role_data["role_id" == 1] ) )
I'm still not fully clear of why it's written this way
The line
if (empty($role_data["role_id" == 1]))
Gets translated into...
if (empty($role_data[0]))
...by the PHP interpreter. This code might be a "joke", a funny hack or an error as the line:
if (empty($role_data["role_id"]) == 1)
..sort of makes sense.
Related
I have the following SQLite table
CREATE TABLE keywords
(
id INTEGER PRIMARY KEY,
lang INTEGER NOT NULL,
kwd TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT 0,
locs TEXT NOT NULL DEFAULT '{}'
);
CREATE UNIQUE INDEX kwd ON keywords(lang,kwd);
Working in PHP I typically need to insert keywords in this table, or update the row count if the keyword already exists. Take an example
$langs = array(0,1,2,3,4,5);
$kwds = array('noel,canard,foie gras','','','','','');
I now these data run through the following code
$len = count($langs);
$klen = count($kwds);
$klen = ($klen < $len)?$klen:$len;
$sqlite = new SQLite3('/path/to/keywords.sqlite');
$iStmt = $sqlite->prepare("INSERT OR IGNORE INTO keywords (lang,kwd)
VALUES(:lang,:kwd)");
$sStmt = $sqlite->prepare("SELECT rowid FROM keywords WHERE lang = :lang
AND kwd = :kwd");
if (!$iStmt || !$sStmt) return;
for($i=0;$i < $klen;$i++)
{
$keywords = $kwds[$i];
if (0 === strlen($keywords)) continue;
$lang = intval($langs[$i]);
$keywords = explode(',',$keywords);
for($j=0;$j < count($keywords);$j++)
{
$keyword = $keywords[$j];
if (0 === strlen($keyword)) continue;
$iStmt->bindValue(':kwd',$keyword,SQLITE3_TEXT);
$iStmt->bindValue(':lang',$lang,SQLITE3_INTEGER);
$sStmt->bindValue(':lang',$lang,SQLITE3_INTEGER);
$sStmt->bindValue(':kwd',$keyword,SQLITE3_TEXT);
trigger_error($keyword);
$iStmt->execute();
$sqlite->exec("UPDATE keywords SET count = count + 1 WHERE lang =
'{$lang}' AND kwd = '{$keyword}';");
$rslt = $sStmt->execute();
trigger_error($sqlite->lastErrorMsg());
trigger_error(json_encode($rslt->fetchArray()));
}
}
which generates the following trigger_error output
Keyword: noel
Last error: not an error
SELECT Result: {"0":1,"id":1}
Keyword: canard
Last Error: not an error
SELECT Reult:false
Keyword:foiegras
Last Error: not an error
SELECT Result: false
From the SQLite command line I see that the three row entries are present and correct in the table with the id/rowid columns set to 1, 2 and 3 respectively. lastErrorMsg does not report an error and yet two of the three $rslt->fetchArray() statements are returning false as opposed to an array with rowid/id attributes. So what am I doing wrong here?
I investigated this a bit more and found the underlying case. In my original code the result from the first SQLite3::execute - $iStmt-execute() - was not being assigned to anything. I did not see any particular reason for fetching and interpreting that result. When I changed that line of code to read $rslt = $iStmt->execute() I got the expected result - the rowid/id of the three rows that get inserted was correctly reported.
It is as though internally the PHP SQLite3 extension buffers the result from SQLiteStatement::execute function calls. When I was skipping the assignment my next effort at running such a statement, $sStmt->execute() was in effect fetching the previous result. This is my interpretation without knowing the inner workings of the PHP SQLite3 extension. Perhaps someone who understands the extension better would like to comment.
Add $rslt = NONE; right after trigger_error(json_encode($rslt->fetchArray())); and the correct results appear.
FetchArray can only be called once and somehow php is not detecting that the variable has changed. I also played with changing bindValue to bindParam and moving that before the loop but that is unrelated to the main issue.
It is my opinion that my solution should not work unless there is a bug in php. I am too new at the language to feel confident in that opinion and would like help verifying it. Okay, not a bug, but a violation of the least surprise principle. The object still exists in memory so without finalizing it or resetting the variable, fetch array isn't triggering.
I looked to other questions that looked like mine,but couldn't find a good answer. So
$machines = get_machine($platform);
$options = array() ;
$options[0] = "please select";
foreach( (array)$machines as $machine_){
$options[$machine_[0]] = $machine_[1] ;
array_push($temp,$machine_[0]);
}
//print_r($options);
$form->addElement(new Element\Select("Existing machines :", "machine", array("onchange" => "this.form.submit()", "value" => $machine)));
if ( !in_array( $machine, $temp ) )
$machine = 0;
$form->addElement(new Element\Textbox("Add new/Edit machine:", "new_machine", array("placeholder" => "new machine", "shortDesc" => "Add new machine or edit the existing one", "value" => get_machine( $machine ))));
It says that the "machine" is not defined and unitialized offset .
Here is defined :
if ( isset($_POST['machine']) ) $mask = $_POST['machine']; else $machine = 0;
I had the exact same code with other variables and it didn't gave me an error of such nature. I am sure,that there are no typos.
I am sure this will get me another barrage of downvotes but one method that helped me keeping my statements short and readable (without doing isset($_POST['...']) all the time and everywhere) is placing an initialisation of the expected values at the top of my page and directly underneath it an extract($_POST) command like:
$amount=$mask=$machine=0; $flag1=$flag2=$flag2=false;
extract($_POST);
Yes, this will turn everything that has been posted into a php variable on my page, but ...
it needs to have been posted there in the first place (so that reduces the scope)
it will either be ignored (if it was an unasked variable) or reset later to its proper value in my own code.
The benefit is that after this initialisation I don't need to bother with any isset()s any more. I just use the intended variable directly. It will be there, either in its initialised form (with a value of 0 or false) or as a consequence of the extract() statement.
Trying to debug some issues with WordPress' notorious pseudo-cron. Thought about putting this on WordPressAnswers but I think this is less about WP and more a basic PHP question on a foreach that seems to never get past its first run. (Yes, definitely looked at a bunch of similar questions, but no love there, sorry.)
Here's the code, with 3 checkpoints where I added output for testing. I'm including the entire code of everything in the loop, just to be thorough, though most of it's probably beside the point. Checkpoints 2 and 3 never display for me, and checkpoint 1 only shows up once (i.e. on first iteration of loop). Not shown is where I'm outputting $crons, and count($crons) for good measure, to confirm that, yes, it absolutely has multiple elements.
foreach ( $crons as $timestamp => $cronhooks ) {
echo("<br>loop for timestamp " . $timestamp); // checkpoint 1
if ( $timestamp > $gmt_time ) {
break;
}
foreach ( $cronhooks as $hook => $keys ) {
echo("<br>loop for hook " . $hook); // checkpoint 2
foreach ( $keys as $k => $v ) {
$schedule = $v['schedule'];
if ( $schedule != false ) {
$new_args = array($timestamp, $schedule, $hook, $v['args']);
call_user_func_array('wp_reschedule_event', $new_args);
}
wp_unschedule_event( $timestamp, $hook, $v['args'] );
do_action_ref_array( $hook, $v['args'] );
// If the hook ran too long and another cron process stole the lock, quit.
if ( _get_cron_lock() != $doing_wp_cron ) {
echo("quitting!"); // checkpoint 3
return;
}
}
}
}
All the output I'm getting from this, despite my 5 elements, is:
loop for timestamp 1382968401
I'll be grateful for extra eyes on whatever I'm missing. I'm 95% sure this is WP core code, except my checkpoints, although for various reasons it's not out of the question that another programmer was mucking about in here in an end-run around our version control system. A whole other problem, obviously!
Assuming $gmt_time is current UTC time, then the timestamp 1382968401 will be greater (as of this writing):
$d = new DateTime('#'.'1382968401', new DateTimeZone('UTC'));
echo $d->format('Y-m-d H:i:s'); // output 2013-10-28 13:53:21
Which would explain why your loop breaks on the first iteration.
Well, foreach can't be wrong.
The only way your loop could do only one iteration is that it breaks. And that could only mean that the first $timestamp is greater than $gmt_time.
(There's also the return possibility near the bottom, but you already said you receive one line of text, so it couldn't have gone that way...)
I'm guessing that you want to just skip the iteration if the scheduled task is in the future. To do that, just change break with continue.
I'm having a small problem. In a class called reservation that has an attribute called reserve , which in the database is a tinyint(4), and an attribute kamp, which is int(10). I'm trying to do this:
if ($this->kamp == 387 || $this->kamp == 388 || $this->kamp == 389) {
$this->reserve = 0;
} else {
$this->reserve = 1;
}
Now my problem is, the code ALWAYS jumps straight to the else bracket. Even when I'm 100% sure $this->kamp is 387, 388 or 389.
Does this have anything to do with datatypes or am I missing something? I think the problem lies within this piece of code, since in my database there are objects showing up where reserve = 1 and the kamp is one of the three numbers I mentioned.
Thanks!
i think this will work for you.
$val = intval($this->kamp);
and then print or echo for result it will giving you value or not ?
let me know if i can help you more.
I know that an E_WARNING is generated by PHP
PHP Warning: Unknown: Input variables exceeded 1000
But how can I detect this in my script?
A "close enough" method would be to check if( count($_POST, COUNT_RECURSIVE) == ini_get("max_input_vars"))
This will cause a false positive if the number of POST vars happens to be exactly on the limit, but considering the default limit is 1000 it's unlikely to ever be a concern.
count($_POST, COUNT_RECURSIVE) is not accurate because it counts all nodes in the array tree whereas input_vars are only the terminal nodes. For example, $_POST['a']['b'] = 'c' has 1 input_var but using COUNT_RECURSIVE will return 3.
php://input cannot be used with enctype="multipart/form-data". http://php.net/manual/en/wrappers.php.php
Since this issue only arises with PHP >= 5.3.9, we can use anonymous functions. The following recursively counts the terminals in an array.
function count_terminals($a) {
return is_array($a)
? array_reduce($a, function($carry, $item) {return $carry + count_terminals($item);}, 0)
: 1;
}
What works for me is this. Firstly, I put this at the top of my script/handler/front controller. This is where the error will be saved (or $e0 will be null, which is OK).
$e0 = error_get_last();
Then I run a bunch of other processing, bootstrapping my application, registering plugins, establishing sessions, checking database state - lots of things - that I can accomplish regardless of exceeding this condition.. Then I check this $e0 state. If it's not null, we have an error so I bail out (assume that App is a big class with lots of your magic in it)
if (null != $e0) {
ob_end_clean(); // Purge the outputted Warning
App::bail($e0); // Spew the warning in a friendly way
}
Tweak and tune error handlers for your own state.
Registering an error handler won't catch this condition because it exists before your error handler is registered.
Checking input var count to equal the maximum is not reliable.
The above $e0 will be an array, with type => 8, and line => 0; the message will explicitly mention input_vars so you could regex match to create a very narrow condition and ensure positive identification of the specific case.
Also note, according to the PHP specs this is a Warning not an Error.
function checkMaxInputVars()
{
$max_input_vars = ini_get('max_input_vars');
# Value of the configuration option as a string, or an empty string for null values, or FALSE if the configuration option doesn't exist
if($max_input_vars == FALSE)
return FALSE;
$php_input = substr_count(file_get_contents('php://input'), '&');
$post = count($_POST, COUNT_RECURSIVE);
echo $php_input, $post, $max_input_vars;
return $php_input > $post;
}
echo checkMaxInputVars() ? 'POST has been truncated.': 'POST is not truncated.';
Call error_get_last() as soon as possible in your script (before you have a chance to cause errors, as they will obscure this one.) In my testing, the max_input_vars warning will be there if applicable.
Here is my test script with max_input_vars set to 100:
<?php
if (($error = error_get_last()) !== null) {
echo 'got error:';
var_dump($error);
return;
}
unset($error);
if (isset($_POST['0'])) {
echo 'Got ',count($_POST),' vars';
return;
}
?>
<form method="post">
<?php
for ($i = 0; $i < 200; $i++) {
echo '<input name="',$i,'" value="foo" type="hidden">';
}
?>
<input type="submit">
</form>
Output when var limit is hit:
got error:
array
'type' => int 2
'message' => string 'Unknown: Input variables exceeded 100. To increase the limit change max_input_vars in php.ini.' (length=94)
'file' => string 'Unknown' (length=7)
'line' => int 0
Tested on Ubuntu with PHP 5.3.10 and Apache 2.2.22.
I would be hesitant to check explicitly for this error string, for stability (they could change it) and general PHP good practice. I prefer to turn all PHP errors into exceptions, like this (separate subclasses may be overkill, but I like this example because it allows # error suppression.) It would be a little different coming from error_get_last() but should be pretty easy to adapt.
I don't know if there are other pre-execution errors that could get caught by this method.
What about something like that:
$num_vars = count( explode( '###', http_build_query($array, '', '###') ) );
You can repeat it both for $_POST, $_GET, $_COOKIE, whatever.
Still cant be considered 100% accurate, but I guess it get pretty close to it.