Jump to content

[SOLVED] Quick Variable Function question


Eggzorcist

Recommended Posts

In my script I made a quick function which secures the inputed variable like this.

function secure_var($var){

$var = mysql_real_escape_string(htmlentities($var));

}

 

I have a quick question of something I'm unsure of. To use a variable like this one. Should I be doing...

<?php

$var = secure_var($var)

// or would this just work?


secure_var($var)

?>

 

I will be retrieving the variable like "$var" I think the first option is best but I'm unsure of the right way of doing this.

 

 

Thanks

 

 

 

 

Link to comment
Share on other sites

To get a value from a function you use return:

 

function secure_var($var){

return mysql_real_escape_string(htmlentities($var));
}
$var = 'something...';
$var = secure_var($var);

Link to comment
Share on other sites

to expand... functions have their own scope, so if you do this:

function secure_var($var){

   $var = mysql_real_escape_string(htmlentities($var));
   
}

$var = "something";
secure_var($var);

 

your function is going to do its thing on its own copy of $var, and nothing will happen with your $var.  So you have to either return it, pass it by reference, or declare it as global inside your function. 

 

example of global:

function secure_var($x){
   global $var;
   $var = mysql_real_escape_string(htmlentities($x));
   
}

$var = "something";
secure_var($var);

 

passing by reference:

function secure_var(&$var){

   $var = mysql_real_escape_string(htmlentities($var));
   
}
$var = "something";
secure_var($var);

 

Best practice is to return assign the function to the value and return the results inside the function (as detailed by AlexWD's post), because one of the points of functions is that they have their own scope.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.