I was looking at the internal representation of PHP session file and I noticed that the session keys are separated by the pipe character |.
Before getting into the problem I encountered, let me give a quick tutorial on how the session file is formatted. At least, this is how it was formatted on my Mac (10.9.4, PHP 5.4.24).
Session File Format
Say I have the following code:
$_SESSION["age"] = 26;
$_SESSION["car"] = "Mazda";
$_SESSION["nerdy"] = true;
$_SESSION["likes"] = array(42, "being meta");
$_SESSION["stats"] = array("bmi" => 1000);
Then it gets stored in the session variable like this:
age|i:26;car|s:5:"Mazda";nerdy|b:1;
likes|a:2:{i:1;i:42;i:2;s:10:"being meta"}
stats|a:1:{s:3:"bmi";i:1000}
The general format is
session_key|session_value[;session_key|value] etc.
where session_value is of the general form
type[:size]:value
More specifically (if anyone's interested),
strings: s:3:"some text"
integers: i:4
booleans: b:1 (true) or b:0 (false)
arrays: a:2:{session_value;session_value;session_value;session_value}
where the four session_values in the array of size 2 are the key;value key;value pairs.
The Problem
You can see that in the above, the top-level session keys are separated by the | character. But what if one of our session key names includes the | character?
Well, I tried it. And when I did, the entire session file (in /tmp) was blank (and the variables were definitely not set). Is this an oversight by the PHP devs or an undocumented limitation (or is it documented somewhere)?
This could be easily solved by putting the $_SESSION keys themselves in quotes or backslashing any pipe in a $_SESSION key string. This isn't a big problem for me personally, since I can't fathom why I would need to put a | in a $_SESSION variable key - just curious about it.
Its a known bug
https://bugs.php.net/bug.php?id=33786
The work around is update to 5.5.4 and use the php_serialize session serializer
Using this php file 'test3.php', I demonstrated that both | (pipe) and ! (bang) will cause _SESSION to fail in PHP 5.4 if they are used in a _SESSION key. Also, no other ASCII characters between 0x20 and 0x7f cause it to fail. I don't have easy access to other versions of PHP to empirically check their behavior.
<?php
session_start( );
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test session keys</title>
</head>
<body>
<form method="post" target="test3.php">
<input type="submit" id="submit" name="submit" value="Submit">
<?php
echo "<br>_SESSION...<br>";
var_dump( $_SESSION );
echo "\n".'<br><input type="text" id="text" name="text" length="1" ';
if( $_SERVER[ 'REQUEST_METHOD' ] != 'POST' ) {
$t = chr( 32 );
echo 'value="&#'.ord( $t ).';">';
$_SESSION[ 'key' ] = ' ';
$str = 'first';
} else {
$str = 'good';
if( count( $_SESSION ) != 2 ) {
$str = 'BAD';
}
$_SESSION = array( );
$t = substr( $_POST[ 'text' ], 0, 1);
echo 'value="&#'.(ord($t) + 1 ).';">';
$_SESSION[ 'key' ] = chr(ord($t) + 1 );
}
echo "\n".'<br><input type="text" id="check" name="check" length="1" value="&#'.ord( $t ).';">';
echo "\n".'<br><input type="text" id="check2" name="check2" length="6" value="%'.bin2hex( $t ).'";">';
echo '<span id="success"></span>';
echo "<script> document.getElementById( 'success' ).innerHTML = '".$str."'; </script>";
$_SESSION[ "alpha".$_SESSION['key']."four" ] = 'Hello World';
?>
</form>
</body>
</html>
Related
the line $_SERVER['REQUEST_URI'] = MSU_REQUEST_URI;
Fills my errorslog with
Use of undefined constant MSU_PHPEX_PS - assumed 'MSU_PHPEX_PS' (this
will throw an Error in a future version of PHP)
So I was thinking to solved it with $_SERVER['REQUEST_URI'] = 'MSU_REQUEST_URI';
Than is the warning gone but the script isn't working any longer.
Any ideas?
The Problem you're having is that MSU_REQUEST_URI is undefined
This means whatever value you expected the constant MSU_REQUEST_URI to have, has not been set at the time of you executing $_SERVER['REQUEST_URI'] = MSU_REQUEST_URI;,
By surrounding MSU_REQUEST_URI with quotes like this 'MSU_REQUEST_URI' you are assigning the String Value (literally) "MSU_REQUEST_URI" to $_SERVER['REQUEST_URI'].
So as #alithedeveloper has asked in the comments:
What is MSU_REQUEST_URI supposed to be and how/where is it supposed to get it's value from?
You won't be able to solve your issue without figuring out why MSU_REQUEST_URI is not set.
Thanks for the response I found a other page with code about the MSU_REQUEST_URI
<?php
if(defined('MSU_REQUEST_URI')) {
return;
}
if(version_compare(PHPBB_VERSION, '3.1', '>=')) {
global $phpEx;
// Fixing Symphony rewrite compatibility
$_SERVER['PATH_INFO'] = '';
$_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'];
define('MSU_REQUEST_URI', $_SERVER['REQUEST_URI']);
if(
in_array(
basename($_SERVER['SCRIPT_NAME']),
array(
'viewtopic.'.$phpEx,
'viewforum.'.$phpEx,
'search.'.$phpEx,
'memberlist.'.$phpEx,
'faq.'.$phpEx,
'viewonline.'.$phpEx,
'ucp.'.$phpEx
)
)
) {
$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'].(!empty($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : '');
}
if(!defined('PHPBB_USE_BOARD_URL_PATH')) {
define('PHPBB_USE_BOARD_URL_PATH', true);
}
}
?>
Is that helping
I'm trying to use the Wordnik PHP API and I'm having some trouble. I tried to use the getDefinitions method but it returns an error: Notice: Trying to get property of non-object in C:\xampp\htdocs\index.php on line 18.
Here is the following code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post">
<input type="text" placeholder="First Word" name="word1">
<input type="submit" placeholder="Compare">
</form>
<?php
require('./wordnik/Swagger.php');
$APIKey = '342eac9900e703079b0050d5f7008eab962195189e75bfbcb';
$client = new APIClient($APIKey, 'http://api.wordnik.com/v4');
$word1 = $_POST['word1'];
$wordApi = new WordApi($client);
$word1 = $wordApi->getDefinitions($word1, null, null);
print $word1->text;
?>
</body>
</html>
I think your notice (not really an error in the php world) does not come from the $word1 = $wordApi->getDefinitions($word1, null, null); but from print $word1->text; is it possible?
If you check the WorldApi class :
https://github.com/wordnik/wordnik-php/blob/master/wordnik/WordApi.php#L182
https://github.com/wordnik/wordnik-php/blob/master/wordnik/WordApi.php#L138
You can see that getDefinitions(...) return an array of Definition or null.
One thing is sure, you cannot get the ->text property from $word1 but from one of these indexes if the return is valid. Try $word1[0]->text
Anyway you should also handle the case where the return of getDefinitions(...) return an empty array or null.
This sample code might help you:
apiUrl = 'http://api.wordnik.com/v4'
apiKey = 'YOURKEYHERE'
client = swagger.ApiClient(apiKey, apiUrl)
wordApi = WordApi.WordApi(client)
res = wordApi.getWord('cat')
res2 = wordApi.getDefinitions('cat')
assert res, 'null getWord result'
assert res.word == 'cat', 'word should be "cat"'
print res.word
print dir(res2[0])
print res2[0].partOfSpeech
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.
I have such code:
for ($j = 0; $j < mysql_num_rows($subcategoriesData); $j++)
{
$subcategoriesStrResult = mysql_fetch_array($subcategoriesData);
//echo $subcategoriesStrResult['title']."<br>";
$itemFeatures = array( $subcategoriesStrResult['title'] => $subcategoriesStrResult['path']);
array_push($arrayDataSubcategoryItems, $itemFeatures);
};
array_push($mainArrayForJSON, $item = array(
'parent_id' => $subcategoriesStrResult['parent'],
'level' => $subcategoriesStrResult['level'],
'items' => $arrayDataSubcategoryItems
));
After my $mainArrayForJSON is ready I'm trying to check the json-code by the simple echo
echo json_encode($mainArrayForJSON);
Meanwhile, to be sure that I get what I need I'm checking the single value of my string by the echo too (this string is commented now) - it works OK, I see on Chrome good readable text (in database this text is stored in utf8, of course).
But last call to echo for check the prepared JSON leads me to the next output:
[{"parent_id":"8-590","level":"3","items":[{"\u041c\u0435\u0442\u0430\u043b\u043b\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u043b\u043e\u0442\u043e\u043a BAKS (\u041f\u043e\u043b\u044c\u0448\u0430)":"8-590-1404"},{"\u041c\u0435\u0442\u0430\u043b\u043b\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u043b\u043e\u0442\u043e\u043a INPUK
So, I have no idea how to fix it - I tried to hardcode UTF-coding "SET NAMES ..." and called header(), and iconv() - last has no sense becouse of I'm sured that my text is in UTF8.
Please, help, thanks.
If you want to output your text on a web page, use javascript. And you'll get your Russian characters. For example:
<script type="text/javascript">
var a = "\u041c\u0435\u0442\u0430\u043b\u043b\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u043b\u043e\u0442\u043e\u043a BAKS (\u041f\u043e\u043b\u044c\u0448\u0430";
alert(a);
</script>
Outputs this:
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.