1

Is there a problem with stacking functions on a variable. It seems to work but is there an underlying risk or problem doing this?

$username = mysql_real_escape_string(strtolower($_POST['username']));

I don't really see a problem with it but I'm relatively new to PHP and I'm not sure if this would cause issues. As compared to:

$username = $strtolower($_POST['username']);
$username = mysql_real_escape_string($username);

Just wondering if this is the best way to do it.

KriiV
  • 1,882
  • 4
  • 25
  • 43

2 Answers2

3

There is no problem in nesting functions like mysql_real_escape_string(strtolower($value)) as you propose. It can lead to easy to read and understand code. I would caution against going overboard with it, and nesting many many functions, however, as that quickly gets unreadable.

But wait!!!

Do not be tempted to nest everything. Some functions require good error checking to be used effectively. The mysql_*() functions related to querying and fetching in particular should not be nested (actually they should not be used at all, use MySQLi or PDO instead). It is pretty safe to nest string functions as you attempted, but always check the manual at http://php.net to make sure of the possible return types of the functions you are nesting. Be especially careful with functions that return resources, such as those handling database connections, file handles, sockets, etc.

// Don't do this:
// mysqli_query() will return false on failure, which will 
// not be a valid argument to mysqli_fetch_array()
$row = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM tbl"));

If the query fails, it will result in a fatal error in your code since the object passed to the outermost function is not the type expected.

Instead, cases like this require error checking that make nesting impractical:

$result = mysqli_query($conn, "SELECT * FROM tbl");
if ($result) {
  $row = mysqli_fetch_array($result);
} 

Another case to be wary of are functions which expect references as their arguments. For example, array_merge() returns an array but sort() expects a reference to an array (you wouldn't do this anyway since sort() doesn't return an array):

sort(array_merge([3,2,41], [5,1]));
// PHP Strict standards:  Only variables should be passed by reference in php shell code on line 1

A related and more likely use case in practical terms would be passing a function return value into empty() (which is technically a language construct rather than a function). Prior to PHP 5.5, only variables could be passed in, so the following would result in a parse error:

// Error in PHP < 5.5
if (empty(func_returning_string()) {}
Community
  • 1
  • 1
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
1

Yes, stack as many function calls as you like. Your example won't work however because you're missing a right paren

user1433150
  • 229
  • 3
  • 8