I am in a very puzzling situation. Intially when an user visits a particular page, a popup is shown. User can accept it or decline it. When a user declines it, after 5 page visits, the pop up is again shown to user. This part is working perfectly. When user clicks ok, an ajax call is made and the SESSION variable is set to ok. Lets say initially $_SESSION['count'] = 0. I have two condition statements.
if($_SESSION['count']%5 === 0)
{ // do something
}
elseif($_SESSION['count'] === "ok")
{ // do something
}
Now when an user press ok, an ajax call is made updating $_SESSION['count'] = "ok".
When the user again reloads the page, condition if($_SESSION['count']%5 === 0) gets true even though $_SESSION['count'] is now ok. Later after much experimenting, i came to know that in php i am able to divide or find modulus string by number which will result in zero. How can i handle this?
You can use is_numeric to check if it is a count or 'ok'
http://php.net/manual/en/function.is-numeric.php
if(is_numeric($_SESSION['count']) && $_SESSION['count']%5 === 0)
{ // do something
}
elseif($_SESSION['count'] === "ok")
{ // do something
}
Though generally, I would set ok to be the value of a different variable in $_SESSION as a best practice. If I was looking at the code I would find it very odd to see something called count having a string value.
PHP is very good at implicit casting.
A solution to your issue is simply re-arrange your if else tree.
if($_SESSION['count'] === "ok")
{
// do something
}
elseif($_SESSION['count'] % 5 === 0)
{
// do something
}
Readability
Something to bare in mind, is that a variable count should really contain a value. Perhaps using a different variable might make your code a little less confusing to a reader.
In php, (int) "some string" == 0, so check if $_SESSION['count'] is an integer (e.g. using is_numeric()) before doing the modulus.
Check this working example. It may help:
if(!isset($_SESSION['foo'])) {
$_SESSION['foo'] = 0;
} else {
$_SESSION['foo']++;
}
var_dump($_SESSION['foo']%3);
if(is_numeric($_SESSION['count']) AND $_SESSION['count']%5 === 0)
{ // do something
}
elseif($_SESSION['count'] === "ok")
{ // do something
}
Related
Just wondering, do $_GET and $_POST still work properly in php7? Or do they actually work in a different way than in the old one?
I try to make this code work in a way it returns param 2 when the page url reads do = update at some point, but it didn't. Can someone help me?
<?php
if (isset($_GET['do']) == "update") {
$param=2;
}
else{
$param=1;
}
?>
I assume I am supposed to redirect to a certain page when $param=2 after this link is clicked
Update
$_GET and $_POST still works. Your conditional doesn't, should be :
if (isset($_GET['do']) && $_GET['do'] == 'update') {
$param = 2;
} else {
$param = 1;
}
(as a fun note, can be simplified to):
$param = (isset($_GET['do']) && $_GET['do'] == 'update' ? 2 : 1);
No there's no change to this functionality in PHP7. These variables are fundamental to interacting with HTTP, they can't really change unless that standard changes. Anyway it's nothing to do with that, you simply made a nonsensical comparison:
isset($_GET['do'])
will return either true or false. If it's false it will never be equal to the string "update". If it's true it might by equal by accident because you used == instead of ===. But either way it makes no logical sense to try and compare them. It's not a useful comparison
This code is probably more like you were intending:
<?php
$do = $_GET['do'];
if(isset($do)) //only continue if the variable is definitely set
{
if ($do == "update")
{
$param = 2;
}
else
{
$param = 1;
}
}
else
{
//do something else if the variable is not even set - perhaps an error?
}
?>
Or maybe you wanted to set $param = 1 in all cases except when "do" is set to "update". Your intent is not 100% clear, but the point is your that if statement is wrong.
I have an implemented control check on a form coded this way:
public function checkCittaResidenza() {
if (is_string($this->citta_residenza) && (strlen($this->citta_residenza) <= 45 || strlen($this->citta_residenza == 0))) {
$this->corretti['citta_residenza'] = htmlentities($this->citta_residenza, ENT_QUOTES);
} else {
$this->ErroriTrack('citta_residenza');
}
}
In this version, it simply checks if it is a string and check its lenght that should be less than 45 chars. It puts the string in an array corretti() if positive, else it initialize an error message specified above in an abstract class parent of the checking class.
What i'd love it to do is:
1) make a check on the string to see if it's not null.
2) if it's not null, do the check (that could be even more particular than the simple one shown here, but i don't have problems on this), put it in corretti() if correct and initializing the error if it's not, as the code now says.
3) if the string is null, the program should skip the check and directly write the null value into the array corretti(), because the form is imagined to be completed in different steps over the time, so it always happen that it's not fully filled.
I'm having problem on coding the if cycle for this last condition, every cycle i tried and imagined puts the empty condition as a cause for initializing an error.
Thank you!
Try this,
public function checkCittaResidenza() {
if(isset($this->citta_residenza)){
if ((is_string($this->citta_residenza) && (strlen($this->citta_residenza) <= 45) || $this->citta_residenza == "")) {
$this->corretti['citta_residenza'] = htmlentities($this->citta_residenza, ENT_QUOTES);
} else {
$this->ErroriTrack('citta_residenza');
}
} else {
$this->corretti['citta_residenza'] = "null";
}
}
$alerter2="false";
for ( $counter = 0; $counter <= count($filter); $counter++) {
$questionsubmitted=strtolower($_POST[question]);
$currentcheck =$filter[$counter];
$foundvalue=stripos((string)$questionsubmitted,(string)$currentcheck);
echo $foundvalue;
if ($foundvalue==0) {
$alerter2="true";
} else { }
}
if (!($alerter2=="true")) {
$sql="INSERT INTO Persons (Name, Email, Question)
VALUES
('$_POST[name]','$_POST[email]','$_POST[question]')";
} else {
echo "Please only post appropriate questions";
}
For some reason, whenever I run this, stripos returns 0 every time for every iteration. It's supposed to be a filter, and using echo I found that stripos is 0 every time that it appears. However, when I use 0 in the if, it returns true for even those that don't have the word in them.
Where should I use mysql_real_escape_string? After the query? Note, I am making this a piece of code where I want user input to be saved to a database.
stripos return false if the value is not found, or 0 if it is the first character. Problem is, php automatically cast boolean to the 0 integer or the 0 integer to false. So I think a cast is happening here and thus the condition don't do what you want.
You can use === to also check the type of the variable :
if ($foundvalue === 0) {
$alerter2="true";
}
There's more details about this problem in the linked documentation for stripos.
You should also remove the empty else clause for a cleaner code and use mysql_real_escape_string to sanitize the values before putting them in your database.
You need to change
if ($foundvalue==0)
to
if ($foundvalue===0) // three equals signs
or something equivalent, depending on your logic (I didn't quite understand what's going on).
But as everyone says, THIS CODE IS OPEN TO SQL INJECTION ATTACKS (among other problems).
Also,
$questionsubmitted=strtolower($_POST[question]);
should probably be:
$questionsubmitted=strtolower($_POST['question']);
I have a basic PHP question, take the code below for example, let's say I need to use this 10 times on a page, is there a better way to do it?
I realize I could wrap it in a function and just keep calling that function but is there a better way then to keep on checking if the item is set and equals a a certain value. After finding this out the first time is there some other way of remembering the result from the first time instead of doing it 10 different times?
Hope that makes sense.
<?PHP
if (isset($_SESSION['auto_id']) && $_SESSION['auto_id'] == "1") {
//do something
}
// do other code here that breaks these up
if (isset($_SESSION['auto_id']) && $_SESSION['auto_id'] == "1") {
//do something else
}
// do other code here that breaks these up
if (isset($_SESSION['auto_id']) && $_SESSION['auto_id'] == "1") {
//do something else
}
// do other code here that breaks these up
if (isset($_SESSION['auto_id']) && $_SESSION['auto_id'] == "1") {
//do something else
}
...ect
?>
In this case, yes you have to, although you could do it once and assign the result to a variable.
how about...
<?PHP
$myCheck = (isset($_SESSION['auto_id']) && $_SESSION['auto_id'] == "1") ;
if($myCheck) {
//do something
}
// do other code here that breaks these up
if($myCheck) {
//do something else
}
// do other code here that breaks these up
if($myCheck) {
//do something else
}
// do other code here that breaks these up
if($myCheck) {
//do something else
}
etc.
?>
Syntax may be off - it's a long time since I've done any PHP work...
Sure. Just save the value of the boolean expression in another variable.
<?php
$auto_id_is_one = ($_SESSION['auto_id']) && $_SESSION['auto_id'] == "1");
// ...
if ($auto_id_is_one) {
// do something
}
// ...
if ($auto_id_is_one) {
// do something else
}
// ...
?>
You probably want to give it a more meaningful name than $auto_id_is_one, though.
Maybe a better approach is to use isset once at the top of the function, and set the variable to a default value there. Then you can simply use the value through the rest of the function.
In your example, you could set it to "0", though I realize that may not be the real code...
It depends what the "do something" block of code is, and whether or not the auto_id index of $_SESSION is changed in the other code. You can be certain that, in the body of the first if, the variable exists and is 1. Once that if concludes, you can no longer be certain - you'll have to check again later unless all the rest of the code is executed in a context that only exists if the first test succeeds (i.e. there's an else clause that terminates the script), and you are sure you don't change the value (and no external code you call changes it).
A better way to check the sanity might be to ensure most of the environment is as you expect it just once, then just check specific values at various places. However, if you're constantly rechecking this, it might indicate a design flaw, where similar logic (i.e. that dependent on auto_id = 1) is not well isolated and grouped.
In the example you provided, PHP will just issue an E_NOTICE that the index is not found in the $_SESSION super global (It will not throw the notice if you turned off strict mode). The best practice would be to go and set the value to a default so that you know for sure that the variable is set.
ex
<?php
$myVar = isset($_SESSION['auto_id']) ? $_SESSION['auto_id'] : FALSE;
if (false !== $myVar)
{
//do something
}
//do something not realated to myVar being set
if (false !== $myVar)
{
//do somethign else
}
?>
<?PHP
if (isset($_SESSION['auto_id']) && $_SESSION['auto_id'] == "1") {
$sessionOK = TRUE;
}
if ($sessionOK) {
//do this
}
if ($sessionOK) {
//do that
}
Below is a snippet of PHP that I need to get working, I need to make sure that 3 items are not set already and not === ''
I have the part to make it check if not set but when I try to see if the values are empty as well (I might not even be thinking clearly right now, I might not need to do all this) But I need to make sure that redirect, login_name, and password are all not already set to a value, if they are set to a value I need to make sure that the value is not empty.
Can someone help, when I add in check to see if values are empty, I get errors with my syntax, also not sure if I should have 5-6 checks like this in 1 if/else block like that, please help
I need to check the following:
- $_GET['redirect'] is not set
- $_REQUEST['login_name'] is not set
- $_REQUEST['login_name'] is not != to ''
- $_REQUEST['password'] is not set
- $_REQUEST['password'] is not != to ''
if (!isset($_GET['redirect']) && (!isset($_REQUEST['login_name'])) && (!isset($_REQUEST['password']))){
//do stuff
}
UPDATE
Sorry It is not very clear, I was a bit confused about this. Based on Hobodaves answer, I was able to modify it and get it working how I need it. Below is the code how I need it, it works great like this... So if that can be improved then that is the functionality that I need, I just tested this.
if (!isset($_GET['redirect'])
&& empty($_GET['redirect'])
&& isset($_REQUEST['login_name'])
&& !empty($_REQUEST['login_name'])
&& isset($_REQUEST['password'])
&& !empty($_REQUEST['password'])
) {
echo 'load user';
}
if this was loaded then it will run the login process
login.php?login_name=test&password=testing
If this is loaded then it will NOT run the login process
login.php?login_name=test&password=
if (!isset($_GET['redirect'])
&& !isset($_REQUEST['login_name'])
&& empty($_REQUEST['login_name'])
&& !isset($_REQUEST['password'])
&& empty($_REQUEST['password'])
) {
// do stuff
}
This is exactly what you describe, (not != empty === empty). I think you should edit your question though to explain what you're triyng to do, so we can suggest better alternatives.
Edit:
Your updated question can be simplified as:
if (empty($_GET['redirect'])
&& !empty($_REQUEST['login_name'])
&& !empty($_REQUEST['password'])
} {
// load user
}
A more maintainable solution would be storing each key in an array, and then foreach over it and check if isset or empty. You're not very DRY with your current solution.
The implementation would look someting like:
<?php
$keys = array('login_name', 'password');
foreach($keys as $key)
{
if(!isset($_REQUEST[$key]) || empty($_REQUEST['key'])
// Show error message, kill script etc.
}
// Dot stuff
?>
If a global variable is not set, that is the same as being empty. Thus:
!is_set(($_REQUEST['username'])) is the same as empty($_REQUEST['username'])
So based on your update, you can simplify to:
if (empty($_GET['redirect'])
&& !empty($_REQUEST['login_name'])
&& !empty($_REQUEST['password'])
) {
echo 'load user';
}
please read!
Sorry, the previous answer I gave will not give you what you want. Here is why:
If you use !_REQUEST['password'], it will return true if the password is empty or if it is not set. However if you use if($_REQUEST['password']) it will pass the conditional anytime that global variable is set, even if it is empty.
Therefore I recommend:
$no_redirect = (!$_GET['redirect']);
$login_name = (!$_REQUEST['login_name']) ? false : true;
$password = (!$_REQUEST['login_name']) ? false : true;
if($no_redirect && $login_name && $password) {
echo 'load user';
}
Sorry for the previously bad info.
You could create an array
$array = array(
$_GET['redirect'],
$_GET['redirect'],
$_REQUEST['login_name'],
$_REQUEST['login_name'],
$_REQUEST['password'],
$_REQUEST['password']
);
foreach($array as $stuf)
{
if(!empty($stuff) && $tuff !=0)
//do something
}