How to $_GET php variable in url [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have this PHP code and trying to get the value of the variable language from the url parameters when specified link is clicked.
How do I do this? The code below only gets the value of Java in the first statement and not the values in the elseif statements.
if (isset($_GET['language'])) {
if ($_GET['language'] = 'Java') {
$q = 'title:(Java+Developer)';
}
elseif ($_GET['language'] = 'PHP') {
$q = 'title:(PHP+Developer)';
}
elseif ($_GET['language'] = 'JavaScript') {
$q = 'title:(JavaScript+Developer)';
}
}
Links:
<li>Java</li>
<li>PHP</li>
<li>JavaScript</li>

There's a difference between = and ==. One is for assigning, the other for comparing.
In your first if() statement, you're assigning the value Java to $_GET['language'], which will evaluate to Java. This will then be true.
Change the single = in the comparisons to ==, and you should be all set.

You are using a single equals sign. This is an assignment (as you do when defining a variable).
You need to use double equals signs ==. This is how you test equality.
$_GET['language'] == SOME_STRING
In addition, I would recommend using a switch statement instead of multiple if statements:
if ( isset( $_GET[ 'language' ] ) ) {
switch( $_GET[ 'language' ] ){
case "Java":
$q = 'title:(Java+Developer)';
break;
case "PHP":
$q = 'title:(PHP+Developer)';
break;
case "JavaScript":
$q = 'title:(JavaScript+Developer)';
break;
}
}
Using a switch statement will make this code much easier to maintain and also to add extra conditions (other languages).

Check the equal sign! Replace "=" with "=="

try with this code
if (isset($_GET['language'])) {
if ($_GET['language'] == 'Java') {
$q = 'title:(Java+Developer)';
}
elseif ($_GET['language'] == 'PHP') {
$q = 'title:(PHP+Developer)';
}
elseif ($_GET['language'] == 'JavaScript') {
$q = 'title:(JavaScript+Developer)';
}
}

You are assigning value Java to $_GET["language"] which always returns true. You must compare the value of $_GET["language"] against a string. Compare using == or === operator.
if ($_GET["language"] === "Java") {
/* here be dragons */
}
It is also good habit to use Yoda Conditions to catch this kind of errors.
if ("Java" === $_GET["language"]) {
/* here be dragons */
}

You are using "=" here which is for assigning the variable some value.
Have a look at the use of these:
"=" is used for assigning a value to some variable.
"==" is used for comparison (regardless of the data type). For example if
$var =1 and we evaluate a condition
if($var == TRUE )
The result will be bool True because TRUE is 1 and FALSE is 0 always.
3.
"===" comparison based on datatype also. The above condition will evaluate to Bool False because the data types are different.

You should use == instead of =.

Related

PHP Syntax: "or" in "If" Statement [duplicate]

This question already has answers here:
How to have multiple conditions on the same if statement? [duplicate]
(5 answers)
Closed 8 years ago.
hello I just wanted to check and see if this would be correct PHP syntax:
if ($input == "DeOnTRAY96#localhost"){
echo"
Projects: 1"?>
<br>
<?php
echo"
Admin: yes
";
}
elseif ($input == NULL){
die("Please enter password.");
}else{
header("Location:Invalidpassword.php");
exit;
}
Right where is says
if($input == "DeOnTRAY96#localhost"){
Could I put
if($input == "DeOnTRAY96#localhost" or "somethingelse"){
And still have it work?
You don't want
if($input == "DeOnTRAY96#localhost" or "somethingelse"){
You want
if($input == "DeOnTRAY96#localhost" or $input == "somethingelse"){
I might suggest using === instead of == in this case, as you'd like a type sensitive comparison.
Additionally, for $input == NULL you should use is_null($input). Null is weird in most programming languages, so language specific functions for testing are usually the way to go (rather than comparison)
OR syntax in PHP:
if($var == 'something' || $var == 'something else')
{
//do something
}
For reference:
|| means OR
&& means AND
For a more future-proof solution, consider in_array. I use it for as few as two options, if there's even the slightest chance there may be more added.
if( in_array($input, ["DeOnTRAY96#localhost", "somethingelse"]))
Once you get to four or more options, it's probably better to do something more like:
$whitelist = [
"DeOnTRAY96#localhost"
, "somethingelse"
, "anotheroption"
, "too many options to do inline!"
];
if( in_array($input, $whitelist))

Why do I have to check "IF" ($_GET["$view"]) && $_GET("$view")! . What does "!" mean? Why does it equal = ""

I can't understand that if sentence. Why can't I just check if $view is set? 2 more questions -What does "$_GET("$view")!" "!" sign mean there? What does ! change? Moreover, why does it equal = " "?
<?php
$myurl=htmlspecialchars($_SERVER["PHP_SELF"]);
$view="";
if(isset($_GET["$view"]) && $_GET("$view")! = "") { $view =$_GET["$view"];};
include(head.html);
switch($view] {
case "" :
include(main.html);
break;
case "people" :
include(people.html);
break;
case:"contact":
include(contact.html);
break;
default :
include(404.html);
break;
};
include_once(foot.html;
?>
Thanks for all the help
I think you messed up your code. This will not execute, due to numerous errors. The if statement is probably
if(isset($_GET[$view]) && $_GET[$view] != "")
Ie, first check that the $view key exists, then check that key it is not empty. Note the difference between a key that does not exist, and a key that exist but is empty, and why you check for both in this case.
Why can't I just check if $view is set?
Because apparently the author of that code didn't want the empty string to be valid. This will be the case if, say, there is a field called $view and the user does not put anything in it.
Actually, you could do that, since $view is initialized to the empty string anyway! This code was probably copy/pasted or written by a novice.
What does ! change?
It's actually !=, written in a confusing way. These two are the same:
&& $_GET("$view")! = "")
&& $_GET("$view") != "")
Also, your code has a bug. $_GET("$view") is not valid, the () should be []. So, here is the corrected and readable code:
if (isset($_GET["$view"]) && $_GET["$view"] != "") {
$view = $_GET["$view"];
}
Also:
switch($view] // ...what is this?
include_once(foot.html; // and this?
case:"contact": // ummmm
$view="";
if(isset($_GET["$view"]) && $_GET("$view")! = "") { $view =$_GET["$view"];};
You actually set $view=""; as an empty parameter
There for isset($_GET["$view"] looks like this isset($_GET[""]
You whole if statement with the above code is ignored
Likewise your switch($view); also looks like switch("")
This means only your first case will be executed no matter what you have in your $_GET
Check this portion of your code too for errors. the colon after case needs to be removed
case:"contact":
include(contact.html);
break;
For first, use correctly [] and (). Then you have to learn about operators: http://www.w3schools.com/php/php_operators.asp
For now your code is non-sense.

why does PHP variable with assigned null value is false in if statement?

I was just debuging some code, and found that
$id = null;
$field = $id === null ? true : false;
$field = $id ? true : false;
Both should set $field to TRUE value. However for some reason it does not work as intended. First one returns true, other one returns false.
Edit1: I accidentaly mistook things when writing question. It should be why its different.
Edit2: I ask my question since this behaviour is different on 2 different servers.
2nd Example is expected to return True, but somehow it does not return true on one of my servers.
Edit3: Here is the real code. Its class/ObjectModel.php in Prestashop 1.5
/* Copy the field, or the default language field if it's both required and empty */
if ((!$this->id_lang AND isset($this->{$field}[$id_language]) AND !empty($this->{$field}[$id_language]))
OR ($this->id_lang AND isset($this->$field) AND !empty($this->$field)))
$fields[$id_language][$field] = $this->id_lang === null ? pSQL($this->$field) : pSQL($this->{$field}[$id_language]);
elseif (in_array($field, $this->fieldsRequiredLang))
$fields[$id_language][$field] = $this->id_lang === null ? pSQL($this->$field) : pSQL($this->{$field}[Configuration::get('PS_LANG_DEFAULT')]);
else
$fields[$id_language][$field] = '';
The expected behaveior (that is true on most servers) is if $this->id_lang is set to null then $this->$field should be used instead of $this->$field[$id_language].
However, on my server set on CentOS machine this behaviour differ and when value is set to null it gets $this->$field[$id_language] as value.
The statement (you have unfortunately edited) is the same as:
$id = null;
if($id === null) {
$field = true;
} else {
$field = false;
}
Are you still expecting false? :)
The statement in your question is using the so called ternary operator. To understand your example you should read this documentation (Section: Ternary Operator)
The ternary operator is a shorthand for if statements that allows to shorten code, especially conditional assignments. However, the fact that you ask this question is a good example for it's disadvantage: It is less readable ;)
Regarding Edit 3, if you are experiencing different results on different distributions with the same code and data set then my guess is that the CentOS binaries you are using have been modified by their developers and a bug has been introduced, perhaps in operator precedence.
As a general rule, I personally prefer to enclose each clause or group of clauses in parentheses in order to reduce the chances of something like this happening, thus I suggest giving the following a try:
if ((!$this->id_lang && isset($this->{$field}[$id_language]) && !empty($this->{$field}[$id_language])) || ($this->id_lang && isset($this->$field) && !empty($this->$field))) {
$fields[$id_language][$field] = (($this->id_lang === null) ? pSQL($this->$field) : pSQL($this->{$field}[$id_language]));
} else if (in_array($field, $this->fieldsRequiredLang)) {
$fields[$id_language][$field] = (($this->id_lang === null) ? pSQL($this->$field) : pSQL($this->{$field}[Configuration::get('PS_LANG_DEFAULT')]));
} else {
$fields[$id_language][$field] = '';
}
This way, you force the parser to evaluate the various clauses and operators in the order you define rather than the order the parser thinks they should be processed.
Original Answer
$field is being set to true because the === operator compares two values and returns true if they contain both the same value and the same type.
By setting $id to null, you are essentially running this:
$field = (null === null);
You could expand your current code to clarify the logic as follows:
if ($id === null) {
$field = true;
} else {
$field = false;
}
Or, you could just simply run:
$field = ($id === null);

unexpected cast to boolean?

Given this input: http://example.com/item.php?room=248&supply_id=18823, the following 2 blocks ought to produce the same result. Why don't they? What am I missing other than coffee?
This block gives the expected values:
if (isset($_GET['supply_id']) && isset($_GET['room'])) {
$id=validkey($_GET['supply_id']); //18823
$room=validkey($_GET['room']); //248
$arr=array('s'=>$id,'r'=>$room); //s=>18823, r=>248
}
But if I do the check and the assignment in one step, $id ends up equal to 1 instead of 18823. Why?
if (isset($_GET['supply_id']) && isset($_GET['room'])) {
if($id=validkey($_GET['supply_id']) && $room=validkey($_GET['room']))
$arr=array('s'=>$id",'r'=>$room); //s=>1, r=>248
}
This is the function I'm using:
function validkey($value){
if(is_scalar($value)){
$value=(int)$value;
return ($value>0) ? $value : false;
}
return false;
}
You should use parentheses:
if(($id=validkey($_GET['supply_id'])) && ($room=validkey($_GET['room'])))
Otherwise the result of validkey($_GET['supply_id']) && $room=validkey($_GET['room']) is assigned to $id variable because && operator has higher precedence than =
The && operator binds stronger than the = operator.
So your code basically becomes if ($id = (validkey($_GET['supply_id']) && $room = validkey($_GET['room'])))
--> Add parenthesis around the $foo = $bar expressions in your IF statement.
You seem to have a small error in your second example - a stray doubble quote after $id. Also, your second approach is generally frowned upon (assigning variables in an if construct) as it makes code considerably harder to follow. Clearer would be the following:
if (isset($_GET['supply_id']) && isset($_GET['room'])) {
$id=validkey($_GET['supply_id']); //18823
$room=validkey($_GET['room']); //248
if($id && $room) {
$arr=array('s'=>$id,'r'=>$room); //s=>18823, r=>248
}
}

PHP: what's an alternative to empty(), where string "0" is not treated as empty? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Fixing the PHP empty function
In PHP, empty() is a great shortcut because it allows you to check whether a variable is defined AND not empty at the same time.
What would you use when you don't want "0" (as a string) to be considered empty, but you still want false, null, 0 and "" treated as empty?
That is, I'm just wondering if you have your own shortcut for this:
if (isset($myvariable) && $myvariable != "") ;// do something
if (isset($othervar ) && $othervar != "") ;// do something
if (isset($anothervar) && $anothervar != "") ;// do something
// and so on, and so on
I don't think I can define a helper function for this, since the variable could be undefined (and therefore couldn't be passed as parameter).
This should do what you want:
function notempty($var) {
return ($var==="0"||$var);
}
Edit: I guess tables only work in the preview, not in actual answer submissions. So please refer to the PHP type comparison tables for more info.
notempty("") : false
notempty(null) : false
notempty(undefined): false
notempty(array()) : false
notempty(false) : false
notempty(true) : true
notempty(1) : true
notempty(0) : false
notempty(-1) : true
notempty("1") : true
notempty("0") : true
notempty("php") : true
Basically, notempty() is the same as !empty() for all values except for "0", for which it returns true.
Edit: If you are using error_reporting(E_ALL), you will not be able to pass an undefined variable to custom functions by value. And as mercator points out, you should always use E_ALL to conform to best practices. This link (comment #11) he provides discusses why you shouldn't use any form of error suppression for performance and maintainability/debugging reasons.
See orlandu63's answer for how to have arguments passed to a custom function by reference.
function isempty(&$var) {
return empty($var) || $var === '0';
}
The key is the & operator, which passes the variable by reference, creating it if it doesn't exist.
if(isset($var) && ($var === '0' || !empty($var)))
{
}
if ((isset($var) && $var === "0") || !empty($var))
{
}
This way you will enter the if-construct if the variable is set AND is "0", OR the variable is set AND not = null ("0",null,false)
The answer to this is that it isn't possible to shorten what I already have.
Suppressing notices or warnings is not something I want to have to do, so I will always need to check if empty() or isset() before checking the value, and you can't check if something is empty() or isset() within a function.
function Void($var)
{
if (empty($var) === true)
{
if (($var === 0) || ($var === '0'))
{
return false;
}
return true;
}
return false;
}
If ($var != null)

Categories