basic PHP variable local/global issue - php

I have come from a background of C++ and am relatively new into the world of PHP.
I'm currently writing a little piece that has an index.php and definitions.php.
In definitions I have the variable
$passfile = "../ass1_data/passwords.txt";
I want to use $passfile inside a function in my index.
Can I just use it $passfile or do I have to use global with it as well?
This is what I have
function checkPasswd($login,$passwd){
global $passfile;
$p = $passfile;
foreach ($p as $line) {
// some code
}
}
At the moment I am getting the error 'Invalid argument supplied for foreach()'
Any help or explanations would be appreciated, thank you.

Assuming the text file contains lines with passwords in it you need to read the contents of the file in first and then loop through the results:
$passfile= file('../ass1_data/passwords.txt');
function checkPasswd($login,$passwd){
global $passfile;
foreach ($passfile as $line) {
// some code
}
}

1- you have to use global keyword for using global variable inside functions.
2- for second case(foreach) first you have to read the file, then use explode function to split it and use it in foreach.:
$passfile = "../ass1_data/passwords.txt";
function checkPasswd($login,$passwd){
global $passfile;
$p = explode("\n",file_get_contents($passfile));
foreach ($p as $line) {
// some code
}
}

You can't simply foreach over a string (even though you can access its bytes with subscript notation).
You need to turn it into an array first, one option for doing that is explode("\n").
However, it sounds like you want to open the file at that location. In that case, you can use file(), which will automatically provide you with an array of lines in that file.

Related

PHP. Pass variable by reference vs string. How to works with these two different arguments?

I'm writing my own debug functions and I need some help to fix the code below.
I'm trying to print a variable and its name, the file where the variable and the function was declared and the line of the function call. The first part I did, the variable, the variable name, the file and the line is printed correctly.
At the code, a($variable) works good.
The problem is I'd like this function accepts a string too, out of a variable. But PHP returns with a fatal error (PHP Fatal error: Only variables can be passed by reference in ...). At the code, a('text out').
So, how can I fix this code to accept a variable or a string correctly?
code (edited):
function a(&$var){
$backtrace = debug_backtrace();
$call = array_shift($backtrace);
$line = $call['line'];
$file = $call['file'];
echo name($var)."<br>".$var."<br>".$line."<br>".$file;
}
$variable='text in';
a($variable);
a('text out');
I need pass the variable by reference to use this function below (the function get the variable name correctly, works with arrays too):
function name(&$var, $scope=false, $prefix='unique', $suffix='value'){
if($scope) $vals = $scope;
else $vals = $GLOBALS;
$old = $var;
$var = $new = $prefix.rand().$suffix;
$vname = FALSE;
foreach($vals as $key => $val) {
if($val === $new) $vname = $key;
}
$var = $old;
return $vname;
}
The way your code is currently implementing pass by reference is perfect by design, but also by design cannot be changed to have two a() methods - one accepting a variable by reference and the other as a string-literal.
If the desire to pass a string literal instead of assigning it to a variable first is really needed, I would suggest creating a second convenience method named a_str() that actually accepts a string-literal instead of a variable by reference. This method's sole-purpose would be to relay the variable(s) to the original a() method - thereby declaring a variable to pass by reference.
function a_str($var) {
a($var);
}
The only thing to remember is, use a($variable); when passing by reference and a_str('some text'); when not.
Here is the same convenience-method for your name() function:
function name_str($var, $scope=false, $prefix='unique', $suffix='value'){
return name($var, $scope, $prefix, $suffix);
}
The only way to do what you are asking without writing an additional function like #newfurniturey suggests is plain and simply opening and parsing the file where your function was called as text (e.g. with fopen), using the data from debug_backtrace. This will be expensive in terms of performance, but it might be ok if used only for debugging purposes; and using this method you will no longer need a reference in your function, which means you can freely accept a literal as the parameter.

PHP $_POST[$variable] in an included file, doesn't recognize the $variable and creates an error message

I would like to use "dynamic" $_POSTs, I don't know if I am using the right term but in other words I would like to use for example $_POST[$dynamic_variable] in a function that is in an included file. Because the $dynamic_variable isn't recognized or because I can't use $_POST[something] in included files it doesn't work and I get an error message like Undefined variable: lastname in filename.php.
What is the safe to way to use $_POSTs in included files and when the $_POST[name] is variable?
Thank you!
///// updated - piece of code ///////
[code.php]
include("functions.php");
$test_arr = array(
"10|field_name1|500",
"20|field_name2|750",
...
);
checkForm($test_arr);
[functions.php]
function checkForm($test_arr) {
foreach ($test_arr as $test) {
$test_details = explode("|", $test);
$field_name = $test_details[1];
echo $_POST[$field_name];
}
}
The $_POST array is available in all included PHP files. Normally, the $dynamic_variable is also available, if you do it like so:
$dynamic_variable = 'test';
include('include.php');
// in include.php:
echo $_POST[$dynamic_variable];
But when declaring the $dynamic_variable inside a function or class, you don't have access to it outside. You could also declare it as global or hand it over as a parameter. Please also read the documentation about variable scope.
I would not write if it is smart to use globals like that or not.
Your problem is you tried to access a variable which does not exists, as the error message said.
To avoid the error message, you can do:
if(isset($_POST[$your_var_name]){
//do something with $_POST[$your_var_name]
}

ob_start() within a loop

I've got a problem when looping using foreach() loop and inside of this loop using ob_start() and ob_get_clean().
Here's my function:
protected function renderEmail() {
$template = $this->_case.".php";
if(is_file($this->_dir.DS.$template)) {
ob_start();
if(!empty($this->_records)) {
foreach($this->_records as $key => $value) {
${$key} = $value;
}
}
require_once($this->_dir.DS.$template);
return ob_get_clean();
} else {
$this->_errors[] = "Email template not found";
return false;
} }
This function is basically generating content of the email and then returns it.
The problem I have is when I loop through a number of email addresses - to send the same email content - only the first one returns the content - the following ones are blank - any idea why?
Ok - you won't believe - once I've posted this question - straight after I've realised where the problem was - I'm using require_once() function - which prevents the same file to be included again - once changed to include() everything works fine!
Every time you are going to use a same file several times inside a loop, you should never user require_once() or include_once, instead use, 'include', and everything will be fine!
Why looping?
extract($this->_records);
looks a bit shorter than
foreach($this->_records as $key => $value) {
${$key} = $value;
}
and native in addition
and var_dump is a great help sometimes (for the next time you run into trouble like this one) :)

How to assign values into global array inside a function? (php)

I have a function that searches for a string inside a text file. I want to use the same function to assign all lines to an array in case I am going to replace that string. So I will read the input file only once.
I have the search function working but I do not know how to deal with the array thing.
the code is something like that (I made the code sample much simpler,so please ignore the search function that actually isn't below)
function read_ini($config_file_name,$string){
$config_file = file($config_file_name);
foreach($config_file as $line) {
return_string = trim(substr($line,0,15));
$some_global_array = $line'
}
}
echo read_ini('config.ini','database.db')
if ($replaced) {file_put_contents('config.ini', $some_global_array);}
http://php.net/parse_ini_file
I know it doesn't answer the question, but it quite possibly removes the need for even having to ask.
The deal with globals, though, is that they must be defined at the top of the function as globals, or else they're considered part of the function's scope.
function write_global() {
global $foo;
$foo = 'bar';
}
write_global();
echo $foo; // bar

How to get variable name in PHP?

func($name1) should return name1
Is it possible?
Here's a function that does it.
function var_name (&$iVar, &$aDefinedVars)
{
foreach ($aDefinedVars as $k=>$v)
$aDefinedVars_0[$k] = $v;
$iVarSave = $iVar;
$iVar =!$iVar;
$aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
$iVar = $iVarSave;
return $aDiffKeys[0];
}
Call it like this
$test = "blah";
echo var_name($test, get_defined_vars());
That will print out "test".
I originally found that function over here You can also do it by iterating over the array returned by get_defined_vars(). That might be a bit easier to understand.
No, there is no way to get the name of a variable in PHP.
When calling a function, that function will only receive the content of the variable, and not the "variable itself" -- which means a function cannot find out the name of the variable that was passed to it.
Good Idea ? No
Any usecase you where you should do it ? No
Proof of concept ? Sure !
<?php
a($test);
function a($x) {
$trace = debug_backtrace();
$file = file($trace[0]['file']);
$line = $file[$trace[0]['line']-1];
var_dump($line); // Prints "a($test);" Do the Stringparsing and your done
}
Yes, this takes the "easy" by reading the sourcefile, it is also doable by using a php extension called "bytekit" that gives you userland access to the php opcodes and work from there.
No.
When you define a function, you specify a local variable name for it to have inside the scope of that function. PHP will pass the function the appropriate value, but the symbol is no longer in scope.
You could look into using "variable variables" as an alternative, however.
Obviously, it is possible for sufficiently high values of crazy.
The comments on this page include several techniques:
http://php.net/manual/en/language.variables.php
lucas dot karisny at linuxmail dot org's answer works on my machine:
http://www.php.net/manual/en/language.variables.php#49997
YMMV.

Categories