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.
Related
Everyone, hello!
I'm currently trying to write to an .ini file from PHP, and I'm using Teoman Soygul's answer and code from here: How to read and write to an ini file with PHP
This works out great, although, when I save the data to it, it shows up strange in my .ini:
[Server] = ""
p_ip = "192.168.10.100"
p_port = 80
p_password = 1234
[Variable] = ""
string1_find = "Caution"
Most notably it also seems to see attempt to give the categories Server and Variable an empty value. Also, sometimes it saves the variable between consistency and sometimes not. How come there is no consistency here?
The code I'm using to find/post in PHP is this:
...
$a=array("[Server]"=>'',"p_ip"=>$_POST['pip'],"p_port"=>$_POST['pport'], "p_password"=>$_POST['pass'],
"[Variable]"=>'',"string1_find"=>$_POST['string1_find'],
...
If anyone could point me into the right direction, that would really be appreciated. Thank you!
You are not using right, you should be passing a multidimentional array instead:
$data = array(
'Server' => array(
'p_ip' => '192.168.10.100',
'p_port' => 80,
'p_password' => 1234,
),
'Variable' => array(
'string1_find' => 'Caution'
)
);
//now call the ini function from Soygul's answer
write_php_ini($data, 'file.ini');
Here is my output:
[Server]
p_ip = "192.168.10.100"
p_port = 80
p_password = 1234
[Variable]
string1_find = "Caution"
Notice that you need to create an extra array per new section and then you can start listing your custom definitions.
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.
At the risk of getting a down vote I am going to ask this question to see if anyone can help me. I have been staring at this for a while and I can't figure it out.
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) on line 130
function pdf($type=null){
//get default or create a type
$data = $this->storeSessionData(
array(),
'SalesComp',
$this->variables
);
$type = ($type)? $type : $data['type']; //this is line 130
$this->set('data', $this->report('store', 'year', 3, $type));
$this->set(
'districtTitle',
array('N' => 'North', 'S' => 'South')
);
$districts = $this->Store->find(
'list',
array(
'fields' => array('Store', 'District'),
'conditions' => array('NOT' => array('District'=> 'O')
)
)
);
$this->set('districts', $districts);
$supervisor = $this->Store->find(
'list',
array('fields' => array('Store','Supervisor'),
'conditions' => array('NOT' => array('District'=> 'O')
)
)
);
$this->set('supervisor', $supervisor);
$this->set(
'supervisors',
$this->Supervisor->find(
'list',
array('fields' => array('Supervisor','ShortName')
)
)
);
$title = ($type == 'sales')?
'Sales Comparison Report':'Fuel Comparison Report';
$this->set('title', $title);
$this->layout = 'pdf';
$this->render();
}
The error suggests mismatched quotes or brackets somewhere. Unfortunately, when this happens, the line number in the error message may be some totally unrelated line -- it's just the first place where the compiler notices that the syntax is no longer valid. The error is actually somewhere before the code snippet in the question, so it's impossible for me to pinpoint it. Syntax highlighting in code editors can help in finding the mismatch.
You can find all php tokens here:
http://php.net/manual/en/tokens.php
There's 2 things about the marked line:
PHP is a scripted language with a VERY complicated syntax in reality. It might look simple, but in comparison to C or the like it's very complicated, and only because there where so many small (and many times incoherent) changes made over the years, and some things can't be changed anymore without breaking backwards compatibility. One of those things is handling of parantheses - PHP does not handle these in a mathematical way, but treat them specially depending on context. This means you should get rid of them in the marked line (there is no need for them in the first place either way)
"Invisible" (i.e. UTF8) whitespaces - these are source for many "strange" problems, especially if you develop on a mac (press alt + space). Easiest way to fix them: Retype the line. And DON'T try copy & pasting it, because you will copy the whitespace as well.
Also I would change the line to
if (! $type) $type = $data['type'];
I hope you know which values evaluate falsy in php, because it's not only NULL (you can find a list here: http://php.net/manual/en/language.types.boolean.php )
On a sidenote: PHP was developed as a simple way to write templates, so maybe you might want to have a look at some compiled programming languages if you want to build complex logic (C for example, which is by far simpler than PHP, and I've been doing PHP for more than 6 years now)
Try replacing
$type = ($type)? $type : $data['type'];
With
$type = $type ? $type : $data['type'];
I doubt that it makes any difference, but maybe a space between the variable named $type and the question mark is needed. For more information about this, check the PHP docs on the ternary operator.
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.
I am creating a 3D Secure PHP Project. I am having a rather bizzare issue in that the "MD" code is going missing when re-submitting the Array of data
My code is as follows :
$paRes = $_REQUEST['PaRes'];
$md = $_REQUEST['MD'];
require "payment_method_3d.php";
x_load('cart','crypt','order','payment','tests');
/*
* For Debugging Purposes
* Only.
echo "The Value Of PaRes is : ";
echo $paRes;
*/
$soapClient = new SoapClient("https://www.secpay.com/java-bin/services/SECCardService?wsdl");
$params = array (
'mid' => '',
'vpn_pswd' => '',
'trans_id' => 'TRAN0095', // Transaction ID MUST match what was sent in payment_cc_new file
'md' => $md,
'paRes' => $paRes,
'options' => ''
);
It seems that the $_REQUEST['MD'] string seems to go missing AFTER the soap call. Although I am having difficulty print this out to the screen. The strange thing is the $paRes variable works without issue.
Any ideas why this would be the case?
Check your case. PHP array keys are case sensitive. From this little bit of code it looks as if the request variable may be 'md' instead of 'MD'.
Try $md = $_REQUEST['md'];
PHP array statements are case sensitive, so this should work:....
$md = $_REQUEST['md'];
Thanks for your responses guys.
What was happening was the include page was sitting in front of the request methods and causing issues loading the REQUEST methods to the page.