While loop: only Variables can be passed by reference error - php

I am running into a "Only variables should be passed by reference" error, because on the code I am using there is a line that does not put the explode() result into a variable. As required when using strict PHP standards.
However because the explode() function is used in a While loop I can't think of a appropriate solution.
My code looks like
function user_exists($username) {
rewind($this->fp);
while(!feof($this->fp) && trim($lusername = array_shift(explode(":",$line = rtrim(fgets($this->fp)))))) {
if($lusername == $username)
return 1;
}
return 0;
}
Any suggestions on how to solve this?

I think maybe you need to sit back and break your code apart a bit and take a look at what is happening.
First, condition is while !feof($this->fp)
From the manual:
feof — Tests for end-of-file on a file pointer
One thing you will notice here is that feof() is only a test which returns true or false. It does not advance the pointer position while looping over, so while using this function, somewhere else in your while loop there needs to be something that advances the pointer or else you will have an infinite loop.
Second condition is:
trim($lusername = array_shift(explode(":",$line = rtrim(fgets($this->fp)))))
First function from left to right is trim(), which returns a string. From our handy dandy comparison table we see that when doing if ((String) $var) it evaluates to false if and only if the string is empty ("") or the number zero as a string ("0"), otherwise it returns true. Personally I tend to really hate using if ((String) $var) (first because it's slightly unclear to newbies unless you know your comparison table well and second because 99% of the time people are doing that they are actually checking for string length, in which case I would want it to return true for the string "0"). So assuming that you don't need it to return false for "0" we could change this to strlen($var) > 0 and then manipulate the variable within the loop. That should greatly simplify things here.
So now we have:
while (!feof($this->fp) && strlen($var) > 0) { /*...*/ }
This will loop over until either we are at the end of the file or $var is an empty line. Everything else can be offloaded into the body of the while loop, so it is much easier to break apart.
So this is what we have now:
$line = rtrim(fgets($this->fp));
$lusername = array_shift(explode(":",$line)));
Uh-oh! There's that "nasty" error:
Strict Standards: Only variables should be passed by reference in /path/to/file.php on line x.
So we can see from here, the part producing the error is not explode(), but array_shift(). See also: Strict Standards: Only variables should be passed by reference
What this means is that since array_shift() modifies the array, it requires it to be by reference. Since you are not passing an actual variable but instead the result of a function, PHP is unable to modify it. It's similar to doing something like function($var) = 3;. Of course you can't do that. Instead you need to save the value to a temporary variable. So now we have:
$line = rtrim(fgets($this->fp));
$split = explode(":",$line);
$lusername = array_shift($split);
Woo hoo! No more warning message.
So putting this together, we now have:
while (!feof($this->fp) && strlen($lusername) > 0) {
$line = rtrim(fgets($this->fp));
$split = explode(":",$line);
$lusername = array_shift($split);
if($lusername == $username) {
return 1;
}
}
Also, as mentioned earlier, the fgets() will advance the pointer, which allows the !feof($this->fp) part in the while statement to vary.

Related

Why doesn't my code to test an email address against a specific domain work?

I wanted to allow only specific email domain. Actually I did it. What i wanted to ask why my first code did not work at all.
I am just trying to learn PHP so that the question may seem silly, sorry for that.
Here is my code:
function check_email_address($email) {
$checkmail = print_r (explode("#",$email));
$container = $checkmail[1];
if(strcmp($container, "gmail.com")) {
return true;
}else {
return false;
}
}
Check out the documentation for strcmp() , it will return 0 of the two strings are the same, so that's the check you want to be doing. Also, you're using print_r() when you shouldn't be, as mentioned by the other answerers.
Anyway, here's how I would have done the function - it's much simpler and uses only one line of code:
function check_email_address($email) {
return (strtolower(strstr($email, '#')) == 'gmail.com');
}
It uses the strstr() function and the strtolower() function to get the domain name and change it to lower case, and then it checks if it is gmail.com or not. It then returns the result of that comparison.
It's because you're using print_r. It doesn't do what you seem to expect from it at all. Remove it:
$checkmail = explode("#", $email);
You can find the docs about print_r here:
http://php.net/print_r
Besides that, you can just use the following (it's much shorter):
$parts = explode("#", $email);
return (strcmp($parts[1], "gmail.com") == 0);
The following row doesn't work as you think it does:
$checkmail = print_r (explode("#",$email));
This means that you're trying to assign the return value from print_r() into $checkmail, but it doesn't actually return anything (if you don't supply the second, optional parameter with the value true).
Even then, it would've gotten a string containing the array structure, and your $container would have taken the value r, as it's the second letter in Array.
Bottom line: if your row would've been without the call to print_r(), it would've been working as planned (as long as you made sure to compare the strcmp() versus 0, as it means that the strings are identical).
Edit:
Interesting enough, I just realized that this could be achieved with the use of substr() too:
<?php
//Did we find #gmail.com at the end?
if( strtolower(substr($email, -10)) == '#gmail.com' ) {
//Do something since it's an gmail.com-address
} else {
//Error handling here
}
?>
You want:
if(strcmp($container, "gmail.com")==0)
instead of
if(strcmp($container, "gmail.com"))
Oh! And no inlined print_r() of course.
Even better:
return strcmp($container, "gmail.com")==0;
No need for the print_r; explode returns a list. And in terms of style (at least, my style) no need to assign the Nth element of that list to another variable unless you intend to use it a lot elsewhere. Thus,
$c = explode('#',$mail);
if(strcmp($c[1],'gmail.com') == 0) return true;
return false;

Strange PHP string error

This is a very very weird bug that happens randomly. So I will try to explain this as best as I can. I'm trying to diminish the code substantially to pinpoint the problem without having to reference a framework, nor deal with 500 lines of code outside of the framework - so I will try and come back and update this question when I do. OK, so here we go.
So basically say I'm taking a string in a function and preg_replace like so:
$table = '/something';
print $table;
$table = preg_replace("#^(/)#",'prefix_',$table);
print $table;
The output will look something like
...
/something - prefix_something
/something - prefix_something
/something - /something
You have an error in you sql query... blah blah somewhere around SELECT * FROM /something
What happens is that after rolling through the code, this simply stops working and the sql errors out. What's more strange is that if I start commenting out code outside the function it then works. I put that code back in, it breaks.
I tried recoding this by substr($var,0,1) and var_dumping the variable. After a few rounds it returns a bool(false) value even though $var is in fact a string. It's very very strange. Has anybody run into this before? Is this a PHP bug? It's looking like it to me.
-- EDIT --
Example:
foreach ( $user as $id => $user ) {
get_data("/table_name","*", "user_id = '$id'");
}
#in the function $_table_ holds "/table_name"
$_table_ = trim($_table_);
$tmp = explode(',', $_table_);
$tables = array();
foreach ($tmp as $c => $n) {
$n = trim($n);
$a = substr($n, 0, 1);
$b = substr($n, 1);
if ($a == false) {
var_dump($n);
$a = substr($n, 0, 1);
var_dump($b);
var_dump($a);
}
if ($a == '/') { etc...
Output:
string(11) "/table_name" string(10) "table_name" bool(false)
If I switch to the original preg_replace functionality, it simply does not preg_replace and the same thing happens "/table_name" is return rather then "prefix_table_name" and this happens randomly. Meaning it will work on the string it broke on if I comment code out outside of the function that is seemingly unrelated.
--- SOLUTION ----
I found out that it has to do with string to array conversion in another function that caused this strange error.
Basically a function was expecting a null or array() value and instead a number was passed. We have notices turned off, so I turned them on and started fixing all the notices and warnings and that's how I found this strange bug. Now exactly what the inner workings are that created the problem is unknown to me. However I can define the symptom as a string assignment problem that would occur at some other place in the code which we caught when it wouldn't reassign the $table variable with the new preg_replace value which is detailed above. Now you know. The function looks something similar to this:
function format_something($one, $two, $three = array()){
if ($three['something'] == 'Y') {
/** etc... */
}
...
format_something('one','two',3);
After a while in a loop this type of conversion started having problems randomly in the code.
substr doesn't always return a string. If it can't find the substring, it returns false.
Return Values
Returns the extracted part of string, or FALSE on failure or an empty string.
You should test for this condition and var_dump the string you are searching to see what it contains in such cases.

PHP GET Question: How do I set a variable value only if it's not in the query string?

I know how to get the value from the query string if the parameter exists:
$hop = $_GET['hop'];
But I also need to set a default value IF it's not in the query string. I tried this and it didn't work:
$hop = $_GET['hop'];
if ($hop = " ") {
$hop = 'hardvalue';
};
Please help me handle the case where the query string has and does not have the "hop" parameter, and if it's present but not defined:
example.com/?hop=xyz
&
example.com/
&
example.com/?hop=
PS I don't know what I'm doing, so if you explain to me, please also include the exact code for me to add to my PHP page.
use array_key_exists
if (array_key_exists('hop', $_GET))
{
// the key hop was passed on the query string.
// NOTE it still can be empty if it was passed as ?hop=&nextParam=1
}
else
{
//the key hop was not passed on the query string.
}
Thought about it a bit more and decided it should be a bit more robust:
$hop = 'hardvalue';
if (array_key_exists('hop', $_GET)) {
if (!empty($_GET['hop'])) { $hop = $_GET['hop']; }
}
You already got the fiddly solutions. When working with URL or form parameters, you often want to treat the empty string or zeros as absent values too. Then you can use this alternative syntax:
$hop = $_GET["hop"] or $hop = "hardvalue";
It works because of the higher precedence of = over or, and is easier to read with extra spaces.
Starting from PHP 5.3 it's also possible to use:
$hop = $_GET["hop"] ?: "hardvalue";
The advantage here is that this syntax doesn't slurp up php notices, which are useful for debugging.
Actually, I would use
$hop = !empty($_GET['hop']) ? $_GET['hop'] : 'default';
Using empty() instead of isset() takes care of your third scenario, where the parameter is present but not defined.
Also, in if ($hop = " ") the = would need to be changed to ==. = assigns, == tests equality. The way you have it, the if-statement will always run, no matter what $hop equaled.

count of false gives 1 and if of an empty array gives false. why?

I have a function which returns only one row as array.
I give a query as a parameter which will exactly gives only one row.
function getFields($query)
{
$t =& get_instance();
$ret = $t->db->query($query);
if(!$ret)return false;
else if(!$ret->num_rows()) return array();
else return $ret->row_array();
}
$ret = getFields('query string');
What i thought was ...
if there is an error then i can check it like if(!$res)//echo error
if it is empty i can check it like if(!count($res))// no rows
else i assume that there is a row and continue the process...
BUT
when there is an error false is returned. In if(count($ret)) gives 1.
If($ret) conditions fails (gives false) if i return as empty array.
//
$ret = getFields('query string');
if(!$fes)jerror('status,0,msg,dberror');
if(!count($fes))jerror('status,1,msg,no rows');
// continue execution when there atleast one row.
this code is called using ajax. so i return a json response.
why count gives 1 and if empty array gives false.
i just wanted to code with logical conditions instead of giving more relations conditions. just to reduce code.
Where can i get all these BUGGING stuff of php so that i can make sure i should not end up making logical errors like the above.
BUGGING - in the above sentence
bugging i referred as not a bug but
things bugs us. things which makes us
logical errors.
I edited this following code to include the following meanwhile i got this as the reply by https://stackoverflow.com/users/451672/andrew-dunn
i can do it like this but still i want to know why for the above explanation
if($fes===false)jerror();
if(!$fes)jsuccess('status,4');
"why count gives 1" - see http://docs.php.net/count:
If var is not an array [...] 1 will be returned.
"and if empty array gives false." - see http://docs.php.net/language.types.boolean#language.types.boolean.casting:
When converting to boolean, the following values are considered FALSE:
[...]
an array with zero elements
Why don't you just check if $ret === false first?
If $myVariable is not array, but empty, then
$count = count($myVariable);
gives 1.
For this situation I check whether the variable is "array" or "bool(false)". If output is array, I use count, if it isn't an array I set number to zero.
if (is_array($myVariable)) {
$count = count($myVariable);
} else {
$count = 0;
}

PHP while(variable=mysql_fetch_assoc) - explanation

I have been working with C# so this is quite strange for me:
while($variable=mysql_fetch_assoc)
{ $X=$variable['A'];
$Y=$variable['B'];
}
If it is like an ordinary loop, then X,Y will be reset with every loop, right?
I have not been able to look up in PHP manual how it works. I guess that in each loop it advances to next element of assoc.array. But what is this generally called in PHP? I am just not used to see '=' in loop condition.
Assignment in PHP is an expression that returns the value that was assigned. If a row was retrieved then the result will be non-false, which will allow the loop to continue.
mysql_fetch_assoc() (and its related functions) advance $result's internal pointer every time it gets called. So $variable will be assigned a new row array every time the while condition is checked. After the last row is returned, mysql_fetch_assoc() can't advance the internal pointer anymore, so the next attempt to call it will return false. Once $variable becomes false, the condition is no longer satisfied and the loop exits.
In PHP (also JavaScript et al), a condition is true as long as it doesn't evaluate to either zero, an empty string, NULL or false. It doesn't have to evaluate to a boolean value. That's why such a loop works.
EDIT:
If it is like an ordinary loop, then X,Y will be reset with every loop, right?
Yes, they'll be reassigned with the new values from each new row that is fetched.
Perhaps looking at the code like this would be useful:
while (($variable = mysql_fetch_assoc($result)) == true) {
// loops until the fetch function returns false (no more rows)
// $variable will have be an associative array containing the 'next' row from the recordset in $result
}
It's a shorthand way of doing this:
$variable = mysql_fetch_assoc();
while ($variable) {
// loop
$variable = mysql_fetch_assoc();
}
It means something like "until you can mysql_fetch_assoc() an element from the variable you pass to that function, then do the body of the while.
It returns an array if it can find an element, FALSE otherwise, so you can exit the loop.
It's just short form of this code:
$variable = mysql_fetch_assoc($res);
while($variable != FALSE) {
// do something
$variable = mysql_fetch_assoc($res);
}

Categories