I have an existing method, which is part of Wordpress:
function process_checkout() {
global $wpdb, $wpdeals;
$validation = $wpdeals->validation();
...
Now I want to extend this a bit, should really be childs play, not sure what I am doing wrong?
function process_checkout() {
if (address_captured() == false)
{
echo '<script>alert("expected");</script>';
exit;
}
global $wpdb, $wpdeals;
$validation = $wpdeals->validation();
...
And (Simplified for testing)....
function address_captured()
{
return false;
}
Code stops executing around the if (address_captured() == false) line.
Can you spot anything out of the ordinary? Seems really 101 basics....
EDIT
It's not the exit statement either. Checked that too.
Related
So the problem is that the keys I want to delete from memcached are actually not being removed. I get no errors. At this point I don't really have a clue what the problem could be. It also shows the correct key it wants to delete so there is nothing wrong with that.
Down below my Class for using memcached, does anybody have any clue on what the problem might be? So far I didn't find any clues on what the problem might be or how to fix the problem.
class MemCacher extends Memcached{
function __construct(){
parent::__construct();
parent::addServer(MEMCACHED_SERVER,11211,1);
}
function add($p_sKey,$p_oData,$p_iTime = 43200){
$t_sKey = CACHE_NAME.$p_sKey;
parent::set($t_sKey,$p_oData,$p_iTime);
}
function get($p_sKey){
$t_sKey = CACHE_NAME.$p_sKey;
return parent::get($t_sKey);
}
function remove($p_sKey){
$t_sKey = CACHE_NAME.$p_sKey;
parent::delete($t_sKey);
debug("Deleted:".$t_sKey);
}
function show_all(){
if( $l_aCacheInfo = parent::getAllKeys() ){
foreach($l_aCacheInfo as $key){
if( strpos($key, CACHE_NAME) !== FALSE ){
debug($key);
}
}
}
}
function clear_all(){
if( $l_aCacheInfo = parent::getAllKeys() ){
foreach($l_aCacheInfo as $key){
if( strpos($key, CACHE_NAME) !== FALSE ){
parent::delete($key);
debug("Deleted:".$key);
}
}
}
}
}
So apparently the delete method requires the expiration time to be 0 in order to remove it else it doesn't work.
doesn't work
parent::delete($t_sKey);
works
parent::delete($t_sKey,0);
I have this script in php:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['data_id']) && $_POST['data_id'] != NULL){
$data = $_POST['data_id'];
DoConfig($data);
function DoConfig($param_data){
echo $param_data;
}
}
}else{
echo '0';
}
I don't understand why I'm getting an error Call to an undefined function, how can I fix it?
PHP is executed sequentially - declare the function before using it and you'll be fine.
To elaborate - in PHP the entire file is loaded, and parsed based on scopes. If the function was at the end of the global scope this would work because at that point the global scope was evaluated before the subscope of the conditional was entered. Since you are entering a subscope with the if, the same evaluation order applies - the function needs to be evaluated before being used in its current scope.
Your code is failing because the function is declared inside your if() loop and after it is called. You could move it outside of the if() and still leave it at the bottom of the script, but best practice dictates otherwise.
Declare your functions before you use them, and outside of any conditionals or loops; preferably in a separate file or in the very least at the very top of the script. For example:
function DoConfig($param_data) {
echo $param_data;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['data_id']) && $_POST['data_id'] != NULL) {
$data = $_POST['data_id'];
DoConfig($data);
}
} else {
echo '0';
}
please put DoConfig function outside if-else condition
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['data_id']) && $_POST['data_id'] != NULL){
$data = $_POST['data_id'];
DoConfig($data);
}
}else{
echo '0';
}
function DoConfig($param_data){
echo $param_data;
}
You need to declare your function before you call it. Do:
function DoConfig($param_data){
echo $param_data;
}
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['data_id']) && $_POST['data_id'] != NULL){
$data = $_POST['data_id'];
DoConfig($data);
}
}else{
echo '0';
}
Well, tell me more.. in my real project, inside the function DoConfig i have a insert into the DataBase in PDO, so if i put these function outside the ''if's'' , have problems into the security?
*Creating function inside if statement is not a best practice * because that will be called if condition is true else will give undefined error in case you call that function later on. Also you called your function before it is even created thats why giving undefined error.
So better to create function outside if statement and run it anywhere.
//Creating function first and then calling it afterwards
function DoConfig($param_data)
{
echo $param_data;
}
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['data_id']) && $_POST['data_id'] != NULL){
$data = $_POST['data_id'];
//Function call
DoConfig($data);
}
}else
{
echo '0';
}
EDITED as per your answer: There is absolutely no problem with security if you create it outside if statement, use functions when needed.
Alternatively for future purpose if you are creating function inside if statement then use
function_exist method later on so that you don't get undefined error
http://in1.php.net/function_exists
I have the following code to validate form data. I have created functions to validate various groups, and then have an if isset statement to check if these functions return true. I have tried many different ways to get this to work.
The problem I am having is this. I want the if isset to end if returning FALSE; but it doesn't, it keeps going and pops up the next alert (in my code I have many functions). How can I get it to exit after the first return FALSE? Do I need to make the isset into a function? So it can exit on return FALSE. thanks
I am having trouble writing a function to call functions in php.
function namecheck ($fname, $lname)
{
$regexp ="/^[A-Za-z]+$/";
//filter through names
if (preg_match($regexp,$fname,$lname))
{
return TRUE;
}
else
{
echo'<script type="text/javascript">alert("Enter your names.")</script>';
return FALSE;
}
}
function emailcheck ($email1, $email2)
{
$regexp="/^[a-zA-A-Z0-9_.]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$/";
//validate email address
if (preg_match($regexp,$email1,$email2))
{
return TRUE;
}
else
{
echo '<script type="text/javascript">alert ("Enter a valid email address.")</script>';
return FALSE;
}
}
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$namecheck=namecheck($fname,$lname);
$email1=$_POST['email1'];
$email2=$_POST['email2'];
$emailcheck=emailcheck($email1,$email2);
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck!==TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
A general structure for your functions you could follow is something like this:
function validateName($name) {
// Do Validation. Return true or false.
}
function validateEmail($email) {
// Do Validation. Return true or false.
}
function isFormValid()
{
// Name Validation
if( ! validateName( $_POST['name'] ) )
return false;
// Email Validation
if( ! validateEmail( $_POST['email'] ) )
return false;
// Form is valid if it reached this far.
return true;
}
// In your regular code on Form Submit
if( isset($_POST['submit']) )
{
if( isFormValid() ) {
// Save Form Data to DB
} else {
// Show Some Errors
}
}
That general structure should work fine for you. It could be made a LOT better but, for the sake of learning, this is sufficient.
If you want the script to, as you put, "exit" then you need to use exit(); Generally this is bad as the script will completely stop executing. Maybe you can look into using "break;" to get you out of a loop and stop executing functions within that loop. Another problem is that you are echoing out HTML code in your function which gets executed on assignment and so you will always get an alert generated when it evaluates to FALSE.
edit:
within your if(isset()) block. Inside here you can do{}while(false); which is a loop and will let you break out of it at anytime and prevent further execution of code within that loop.
If a function isn't returning false, then it never reached a return FALSE; statement. It's as simple as that. So let's examine the relevant code:
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck !== TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
So, if $_POST['submit'] is set and is not null, the if block will be reached. Then, if $namecheck is not true OR $emailcheck is not true, the function will return FALSE. You can simplify the above code to just:
if (isset($_POST['submit']))
{
return !(!$namecheck || !$emailcheck);
}
However, it doesn't look like this code is inside a function, so the return statement will do nothing. You have to put it in a function if you want it to work like a function.
Beyond that, I can't help you. I don't know what you want to do with this code. You seem to know how to use and call functions, so I'm not sure what the problem is. If you want to return from a function, put code in a function and call return. Right now your code is not in a function, so return won't do anything.
I have a function that takes an input variable and outputs a template with the following call:
outputhtml($blue_widget);
outputhtml($red_widget);
outputhtml($green_widget);
And a simplified version of the function:
function outputhtml($type)
{
static $current;
if (isset($current))
{
$current++;
}
else
{
$current = 0;
}
//some logic here to determine template to output
return $widget_template;
}
Now here is my problem. If I call the function in a script three times or more, I want the output to be one way, but if I only call the function twice, then I have some html changes that need to be reflected in the templates that are returned.
So how can I modify this function to determine if there are only two calls for it. I can't go back after the fact and ask "hey function did you only run twice???"
Having trouble getting my head around how I tell a function that it is not going to be used after the second time and the necessary html modifications can be used. How would I go about accomplishing this?
function outputhtml($type)
{
static $current = 0;
$current++;
//some logic here to determine template to output
if ($current === 2) {
// called twice
}
if ($current > 2) {
// called more than twice
}
return $widget_template;
}
That would not be practical using a static $current inside the function; I would suggest using an object to maintain the state instead, like so:
class Something
{
private $current = 0;
function outputhtml($type)
{
// ... whatever
++$this->current;
return $template;
}
function didRunTwice()
{
return $this->current == 2;
}
}
The didRunTwice() method is asking "did you run twice?".
$s = new Something;
$tpl = $s->outputhtml(1);
// some other code here
$tpl2 = $s->outputhtml(2);
// some other code here
if ($s->didRunTwice()) {
// do stuff with $tpl and $tpl2
}
The only way you can find out if a function was only called twice is by putting the test at the end of your code; but perhaps by then the templates are no longer accessible? Can't tell much without seeing more code.
Inherited an old CakePHP site and I'm trying to figure out what some functions do. I have several functions that have the same name as another function but with an underscore first, e.g. save() and _save(). However the function _save() is never called in any context, though save() is.
I read this question and it looks like it's from an old worst-practices exercise, but that doesn't really explain why it's in my code; you still have to call function _save() as _save() right? If there's no calls to _save() is it safe to remove?
I want it gone, even the save() function wasn't supposed to be there, rewriting perfectly good framework functionality. It looks like an older version of the same function, but there's no comments and I don't know if there's some weird context in which php/Cake will fall back to the underscored function name.
Here's the code for the curious. On closer inspection it appears the underscored functions were old versions of a function left in for some reason. At least one was a "private" method being called (from a public function of the same name, minus the underscore...):
function __save() {
$user = $this->redirectWithoutPermission('product.manage','/',true);
if ($this->data) {
$this->Prod->data = $this->data;
$saved_okay = false;
if ($this->Prod->validates()) {
if ($this->Prod->save()) $saved_okay = true;
}
if ($saved_okay) {
$product_id = ($this->data['Prod']['id']) ? $this->data['Prod']['id'] : $this->Prod->getLastInsertId();
if ($this->data['Plant']['id']) {
$this->data['Prod']['id'] = $product_id;
$this->Prod->data = $this->data;
$this->Prod->save_plants();
$this->redirect('/plant/products/'.$this->data['Plant']['id']);
} else {
$this->redirect('/product/view/'.$product_id);
}
die();
} else {
die('did not save properly');
}
} else {
die('whoops');
}
}
function save() {
$user = $this->redirectWithoutPermission('product.manage','/products',true);
if ($this->data) {
$this->Prod->data = $this->data;
if ($this->Prod->validates()) {
$this->Prod->save();
$gotoURL = isset($this->data['Navigation']['goto'])?$this->data['Navigation']['goto']:'/';
$gotoURL = str_replace('%%Prod.id%%', $this->data['Prod']['id'], $gotoURL);
if (isset($this->data['Navigation']['flash'])) {
$this->Session->setFlash($this->data['Navigation']['flash']);
}
if (isset($this->params['url']['ext']) && $this->params['url']['ext']=='ajax') {
$value = array(
'success'=>true
,'redirect'=>$gotoURL
);
print $this->Json->encode($value);
} else {
$this->redirect($gotoURL);
}
} else {
$value = array(
'success'=>false
,'message'=>"You have invalid fields."
,'reason'=>'invalid_fields'
,'fields'=>array(
'Prod'=>$this->Prod->invalidFields()
)
);
print $this->Json->encode($value);
}
} else {
$this->redirect('/products');
}
die();
}
I had hoped to learn whether or not some convention applied to this situation, but from testing I've found the functions are not called which is really the answer to the question I asked.