Combining strings and numbers in PHP for loop - php

PHP newbie here
Can anyone please tell me what is wrong with the below syntax. I have a maximum of 4 files - $created_page1, $created_page2 each with a corresponding page title etc and would like to process these in a loop. However PHP throws a wobbly every time I try to concatenate the string and loop number - specifically $created_page.$num_pages doesn't result in sending $created_page1 or $created_page2 to the function, instead it just converts the string and number to an integer. Very basic I am sure but I would be very grateful for any help or a nicer solution that I can easily understand. Thanks in advance!
$addit_pages == 4;
for ($num_pages=1;$num_pages<=$addit_pages ;$num_pages++) {
replaceFileContent ($dir,$created_page.$num_pages,"*page_title*",$page_title.$num_pages);
//replaceFileContent ($dir,$created_page2,"*page_title*",$page_title2);
//replaceFileContent ($dir,$created_page1,"*page_title*",$page_title3);
//replaceFileContent ($dir,$created_page3,"*page_title*",$page_title4);
}

Your code to get the variable name should be:
${'created_page'.$num_pages}
This is because you have to evaluate the string inside the braces before you attempt to access the variable.
Your previous code was trying to access the variables $created_page and $num_pages, and simply concatenate their values into a string.
Of course, the same goes for the page_title variable
${'page_title'.$num_pages}

you could try this:
$addit_pages == 4;
for ($num_pages=1;$num_pages<=$addit_pages ;$num_pages++) {
replaceFileContent ($dir,$created_page.strval($num_pages),"*page_title*",$page_title.strval($num_pages));
//replaceFileContent ($dir,$created_page2,"*page_title*",$page_title2);
//replaceFileContent ($dir,$created_page1,"*page_title*",$page_title3);
//replaceFileContent ($dir,$created_page3,"*page_title*",$page_title4);
}
the PHP strval function makes any integer into a string

I think what you are asking is you want the variables $created_page1; $created_page2, $created_page3 but php is probably throwing a notice that $created_page doesn't exist.
You need to use variable variables (is this what they're called?)
$addit_pages == 4;
for ($num_pages=1;$num_pages<=$addit_pages ;$num_pages++) {
$createdVar = 'created_page'.$num_pages;
$titleVar = 'page_title'.$num_pages;
replaceFileContent ($dir,$$createdVar,"*page_title*",$$titleVar);
}
When you use $$ this first evaluates the variable $createdVar turns that into created_page1 and then evaluates created_page1 as if you had typed in $created_page1

Related

Odd and confusing PHP syntax

I am taking over the maintenance of an old web site and came across this confusing syntax for processing a form that I have never seen before, and I am not exactly certain what it does:
foreach (array('address','comments','country','email','mail_content','name','title') as $vuln)
{
isset($_REQUEST[$vuln]) and $_REQUEST[$vuln] = htmlentities($_REQUEST[$vuln]);
isset($_GET[$vuln]) and $_GET[$vuln] = htmlentities($_GET[$vuln]);
isset($_POST[$vuln]) and $_POST[$vuln] = htmlentities($_POST[$vuln]);
isset($$vuln) and $$vuln = htmlentities($$vuln);
}
It's the "and" that is throwing me - I read it as "if variable is set convert it to htmlentities, but why is there an "and" in there?
Finally what does the last line do?
isset($$vuln) and $$vuln = htmlentities($$vuln);
It's using the operator precedence rules of PHP in an unusual way.
If you have an and statement, PHP will stop processing it if the left side is false - there's no need to check the right hand side, because it won't make a difference to the end result. (The converse is also true for an or statement if the left hand side is true.)
So the coder that wrote this is using it as a shorthand for:
if (isset($_REQUEST[$vuln])) {
$_REQUEST[$vuln] = htmlentities($_REQUEST[$vuln]);
}
They've save a small amount of typing, at the cost of making the code slightly harder to read. It's good practice to use isset to make sure that your array values are set before you use them, which is why the check is there.
As to the last line; logically, it's doing the same as the above, but with a variable variable. The first time through, $vuln will be set to the first item in your array, which is address - the final line of code is checking to see if there's a variable called $address, and if so, set its value to htmlentities($address).
That's what the code is doing. Why it's checking REQUEST, GET, and POST is beyond me.
Hi These are the nothing but the shortend form.
isset($_REQUEST[$vuln]) and $_REQUEST[$vuln] = htmlentities($_REQUEST[$vuln]);
above line means
if(isset($_REQUEST[$vuln])){
$_REQUEST[$vuln] = htmlentities($_REQUEST[$vuln]);
}
Also the $$vuln is a reference variable its checking the same that if reference variable is set then assign it value
isset($var) and <statement goes here that uses $var>;
This basically only executes the <statement ...> if the statement preceding and (in this case isset($var)) evaluates to true. This happens because if anything is false before a and, there's no need to evaluate (or execute) the rest. This works similarly to:
if (false && condition) { ... }
The condition will never be evaluated, since no matter what its value evaluates to, the if condition will always evaluate to false.
A more readable alternative for the first example:
if (isset($var)) {
<statement goes here that uses $var>;
}
As pointed out in the comments by #chris85, see $$variable.
An example of a variable variable:
$vuln = 'abc'; /* Regular variable assignment */
$$vuln = 'def'; /* This is "equivalent" to $abc = 'def'
* because $$vuln expands to $<contents of $vuln>,
* therefore $abc is assigned with 'def'.
*/
/* $abc is now a variable with 'def' as its value */
It might be easier to comprehend as the following, for the first iteration through the array:
<?php
if(isset($_REQUEST['address'])) {
$_REQUEST['address'] = htmlentities($_REQUEST['address']);
}
if(isset($_GET['address'])) {
$_GET['address'] = htmlentities($_GET['address']);
}
if(isset($_POST['address'])) {
$_POST['address'] = htmlentities($_POST['address']);
}
if(isset($address)) {
$address = htmlentities($address);
}
It looks to me like legacy code that probably was a replacement for (or perhaps in addition to) 'magic quoting' when 'register globals' was turned on. Probably so they could do some pseudo escaping of variables before database inserts and or page echos.

What does this code actually do?

I have recently been employed at an office where they use a lot of php in their work, most of my development background is HTML, CSS, Jquery, Wordpress and Angularjs, I have an idea behind the logic of some of php but was just wondering if anyone can enlighten me as to what this code below actually means/does?
return (isset($rs[0][0]) ? $rs[0][0] : "");
It is located within this function that calls the database and returns values.
function get_temp($table, $field){
global $db;
$sql="select $field from $table";
$rs=$db->select($sql);
return (isset($rs[0][0]) ? $rs[0][0] : "");
}
I feel that is selecting one value from an array within an array but I cannot find any sources to confirm this so was hoping someone on here could help me out or at least point me in the right direction if I am wrong. The reason I believe this is the case is because if I pass the $field variable more than one result it will always only return the first one, if this is the case it would also be helpful to me if someone could suggest a way to get all of the results, whenever I simply try:
return $rs
It simply returns "Array".
(isset($rs[0][0]) ? $rs[0][0] : "");
This is a ternary operator. It does a check if $rs[0][0] is set. If yes it will make the function return $rs[0][0]'s value, if not it will return an empty string.
You could translate it to an if statement like this:
if (isset($rs[0][0])) {
return $rs[0][0];
}
return "";
In fact the method isset will check is the value is null.
Then it is simply a ternary operator, returning the value of the variable if it is not empty and an empty string if the value of the var is empty.

500 - Internal Server Error with extra pair of brackets

I have been looking for an error in my code since an hour. This was the error:
Writing:
if(isset(($_POST['to'])))
instead of
if(isset($_POST['to']))
I don't get why is this extra pair of brackets causing an Internal Server Error.
I don't think putting brackets around a variable never changes its value. I mean,
$a = $b;
$c = ($b);
$a==$c; //True
I am curious as to know why is it an error?
Thank you.
EDIT:
The above error was occurring for normal variable also.
This is because isset is not a function but a language construct; as such, its definition can be found in the language parser.
T_ISSET '(' isset_variables ')' { $$ = $3; }
It only expects one pair of braces; passing another pair will cause a parse error.
Im pretty sure it has something to do with the fact that isset can not take a function in parameter. You have to pass it a value. Your extra pair of parenthesis may be evaluated as a 'function' or something that need to be evaluated.
Normally, when you try to pass a function to isset, you get this error :
Can't use method return value in write context
isset:
Warning
isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just seperate them with a comma.
The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name:
<?php
function familyName($fname)
{
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>

How to convert string variable to integer in php?

I'm very new to php .I want to convert the string to integer value.
I used following code to convert
$val='(100*2)';
echo (int)($val); //This will showing output as 0
But echo (int)((100*2)); /This will showing output as 200
Please help me any one to solve this .Thanks advance
(int)($val) evaluates to 0 because $val's value is not a numeric string (ie one that can be directly cast to a number).
If you really need this kind of functionality, try eval():
$val='(100*2)';
echo (int)($val); //This will showing output as 0
eval('$newval='.$val.';');
echo $newval;
But be warned: eval() can be dangerous!
From http://php.net/manual/en/function.eval.php:
Caution
The eval() language construct is very dangerous because it allows
execution of arbitrary PHP code. Its use thus is discouraged. If you
have carefully verified that there is no other option than to use this
construct, pay special attention not to pass any user provided data
into it without properly validating it beforehand.
EDIT: Added .';' to eval parameter to make it a legit php instruction.
The most common suggestion will be - evaluate your string as PHP code, like:
$val = '(100*2)';
eval('$val = '.$val.';');
-but that's unsafe, eval should be avoided as long as possible.
Alternatively, there is bcParser for PHP, which can solve such issues. That's more safe than eval.
Finally, I doubt that you really need do such things - it seems you're solving some problem with wrong method (see XY-problem description)
You can do it using php eval function.
For that first you have to check for special characters and equation characters.
$val='(100*2)';
echo matheval($val);
function matheval($equation)
{
$equation = preg_replace("/[^0-9+\-.*\/()%]/","",$equation);
// fix percentage calcul when percentage value < 10
$equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
// calc percentage
$equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
// you could use str_replace on this next line
// if you really, really want to fine-tune this equation
$equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
if ( $equation == "" )
{
$return = 0;
}
else
{
eval("\$return=" . $equation . ";" );
}
return $return;
}
I not recommended this, but you can use eval to suit your need
eval('$val = (100*2)');
echo intval($val);
Why not just:
$x=intval(100);// <- or an other value from the cleaned user input
$y=intval(2);
$val=$x*$y;
echo $val;
You are not giving a goal.
I can just explain why your code works like it does.
'(100*2)' is a String that cannot be converted to int, since it does contain other chars than numbers. Every String that cannot be converted will result in 0.
echo (int)(100*2) will work, because you use numbers and no strings. No need to convert, either, would work without the cast, just echo (100*2);
Remember PHP use loose typing. You will almost never need to convert types. This scenario is very set up.

Fatal error: Can't use function return value in write context

I have a pretty nasty error I can't get rid of. Here's the function causing the issue:
function get_info_by_WatIAM($WatIAM, $info) {
$users_info = array();
exec("uwdir -v userid={$WatIAM}", $users_info);
foreach ($users_info as $user_info) {
$exploded_info = explode(":", $user_info);
if (isset($exploded_info[1])){
$infoArray[$exploded_info[0]] = $exploded_info[1];
}
}
return $infoArray[$info]; }
Here's what's calling the function:
} elseif ( empty(get_info_by_WatIAM($_POST['ownerId'])) ) { ...
I would really appreciate any suggestion. Thanks very much!
If the code doesn't make sense, here's a further explanation: exec uses a program that stores information on all the users in a school. These include things like faculty, name, userid, etc. The $_POST['ownerId'] is a username -- the idea is that, upon entering a username, all of the user's information is automatically filled in
You do not need empty around function calls, in fact empty only works with variables and not functions (as you see). You only need empty if you want to test a variable that may not be set for thruthiness. It is pointless around a function call, since that function call must exist. Instead simply use:
} else if (!get_info_by_WatIAM($_POST['ownerId'])) { ...
It does the same thing. For an in-depth explanation, read The Definitive Guide To PHP's isset And empty.
empty can only be used on variables, not on expressions (such as the result of calling a function). There's a warning on the documentation page:
Note:
empty() only checks variables as anything else will result in a parse
error. In other words, the following will not work: empty(trim($name)).
Just one of PHP's best-left-alone quirks.
One workaround is to store the result in a variable and call empty on that, although it's clunky. In this specific case, you can also use
if (!get_info_by_WatIAM(...))
...although in general, if (empty($a)) and if(!$a) are not equivalent.
get the value of this
$a = get_info_by_WatIAM($_POST['ownerId'])
then chack
empty($a)
it will work

Categories