问题
So this is my code. Now how do I use $pubname in another file.
mysqli_select_db($connect,"membership");
$retname = "select username from users where email='$globalname' limit 1";
$rn = mysqli_query($connect,$retname) or die(mysqli_error($connect));
$name = mysqli_fetch_array($rn);
//connecting for mathcing username with fullname and displaying it
$pubname = mysqli_real_escape_string($name['username']);
include('profile.php');
echo $pubname;
and also is this code secure? I did that...does not work yet.
回答1:
Include the file you would like the variable to be accessible within, like so
include('somefile.php')
and at the top of that file you might need put something like [depending on server configurations]
global $pubname
But in most cases you would not need to do this.
In regards to security, depending on how $pubname
is set, your query may or may not be prone to sql injection.
Note: There are other means to include()
files such as include_once()
, require()
and require_once()
, from php.net:
The documentation below also applies to require(). The two constructs are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error. In other words, use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well. Be warned that parse error in required file doesn't cause processing halting in PHP versions prior to PHP 4.3.5. Since this version, it does.
回答2:
To use $pubname
in another script, keep it as global variable. You don't need to echo it. (As caveat: global variables should be used sparingly, preferrably lumped into an array.)
As far as security is concerned: You should use mysqli_real_escape_string
rather on $globalname
right before you use it. And escape the $pubname
only right before you use that in the next query. As it looks now, you are encoding the output needlessly, but forgot to do escape the input - which _escape_string
is actually meant for.
回答3:
to use pubname
in a nother file. first you have to include the file where pubname
was set/created.
then use include()
or require()
function to call it.
来源:https://stackoverflow.com/questions/4572062/passing-variables-in-php-from-one-file-to-another