Variable inside double quotes in PHP array keys - php

I've something weird into my code and I really don't get the behavior.
I always used array with string variables keys like this:
$string = "my key";
$array[$string] = "my value";
But in one case, it doesn't work. I'm forced to put $string into double quotes, otherwise my array remains empty.
I really don't understand why. Moreover, further in my code I use the same "$string" as an id to create an another array, and it works fine without double quotes.
Here is my code where double quotes are needed (array[]):
foreach($xml2->menu as $children) {
$id = $children['id'];
$this->array["$id"] = $children->label;//Problem here
}
And here, the code without double quotes ($resultArray[]):
for($i=0; $i < count($idArray); $i++){
$id = $idArray[$i];
$resultArray[$id] = $this->array[$id];//Problem here
}
Does someone have any idea about why this is happening?
Edit:
The content of $idArray[$i] and $children[$id] is some string like "about", "contact" etc.
And when I say "it doesn't work", I mean that the created array is null.

Does $children["id"] contain an object? Then type it to an int:
$id = (int) $children["id"];
Then you can use it again as $id.

Related

php array syntax ${ is confusing me

I create a $values array and then extract the elements into local scope.
$values['status'.$i] = $newStatus[$i];
extract($values);
When I render an html page. I'm using the following
<?php if(${'status'.$i} == 'OUT'){ ?>
but am confused by what the ${ is doing and why $status.$i won't resolve
$status.$i means
take value of $status variable and concatenate it with value of $i variable.
${'status'.$i} means
take value of $i variable, append id to 'status' string and take value of a variable 'status'.$i
Example:
With $i equals '2' and $status equals 'someStatus':
$status.$i evaluated to 'someStatus' . '2', which is 'someStatus2'
${'status'.$i} evaluated to ${'status'.'2'} which is $status2. And if $status2 is defined variable - you will get some value.
I wanted to add to the accepted answer with a suggested alternate way of achieving your goal.
Re-iterating the accepted answer...
Let's assume the following,
$status1 = 'A status';
$status = 'foo';
$i = 1;
$var_name = 'status1';
and then,
echo $status1; // A status
echo $status.$i; // foo1
echo ${'status'.$i}; // A status
echo ${"status$i"}; // A status
echo ${$var_name}; // A status
The string inside the curly brackets is resolved first, effectively resulting in ${'status1'} which is the same as $status1. This is a variable variable.
Read about variable variables - http://php.net/manual/en/language.variables.variable.php
An alternative solution
Multidimensional arrays are probably an easier way to manage your data.
For example, instead of somthing like
$values['status'.$i] = $newStatus[$i];
how about
$values['status'][$i] = $newStatus[$i];
Now we can use the data like,
extract($values);
if($status[$i] == 'OUT'){
// do stuff
}
An alternative solution PLUS
You may even find that you can prepare your status array differently. I'm assuming you're using some sort of loop? If so, these are both equivalent,
for ($i=0; $i<count($newStatus); $i++){
$values['status'][$i] = $newStatus[$i];
}
and,
$values['status'] = $newStatus;
:)

Using citation marks around a variable in array access

I'm reading som legacy code and come over a curious case:
$my_assoc_array; /* User defined associative array */
$my_key; /* User defined String */
$value = $my_assoc_array["$my_key"];
Is there any clever reason why you would want to have citation marks (") around the variable when it's used as a key? Like a very special corner case? Or is there simply no reason at all to do this?
-- EDIT --
Maybe in some old version of PHP there was a difference? (Remember this is legacy code).
There is one example that I can find where the output differs which is when $mykey = false.
(which perhaps does not apply to your example where $mykey is a string, but then again: this is the wild wild world of PHP)
<?php
$arr = array("1"=>"b", "0"=>"a");
$mykey = false;
var_dump($arr[$mykey]);
// returns "a"
var_dump($arr["$mykey"]);
// gives Undefined index error
$mykey = true;
var_dump($arr[$mykey]);
// returns "b"
var_dump($arr["$mykey"]);
// returns "b"
What this can be (mis-)used for beats me...
Its not necessary to bind variable name with double quotes inside array index:
you can simply write with out quotes:
$value = $my_assoc_array[$my_key];
it will be different one if $my_key is an integer value
$my_key = 3; /* User defined String */
$value = $my_assoc_array["$my_key"]; /* returns $my_assoc_array["3"] */
$value = $my_assoc_array[$my_key]; /* returns $my_assoc_array[3] */

Single quote breaking echo in input using htmlentities & htmlspecialchars when serialized mysql in php

UPDATE: So I spent the day reading various posts on SQL injection and parameterized queries. I've come up with something that works and I think it's a reasonable update to my approach.
$query = "UPDATE message_bundles SET bndName = ?, bndTagId = ?, bndSequence = ?, bndKeyboardArr = ? WHERE id = ?";
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, 'siisi', $bnd_name, $bnd_tag_id, $bnd_sequence, $bnd_keyboard_arr, $id);
$result = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
But, I still have the issue described in this original question. When I echo out the data, it's still breaking with the very first single quote it encounters; whether I use htmlspecialchars or htmlentities. Additional comments would be appreciated.
ORIGINAL: Normally when I save strings to MYSQL in PHP I run a function (below) that escapes quotes. I am doing the same thing but just after I serialize an array of strings before inserting into MYSQL. But when I retrieve the array and unsearialize it, only the first string with a single quote echo's inside an input field. Then the rest of the strings in the array won't echo.
Here is my loop through post to build array (note that the 3 values being added to an array are 1) string, 2) int, 3) string; maybe this is where my issue is):
foreach ($bnd_keyboard as $key) {
if ($key['keyboard']) {
$keyboard = $key['keyboard'];
$target_bundle = $key['targetBundle'];
$code_execute = $key['codeExecute'];
$bnd_keyboard_arr["keyboards"][$keyboard] = array(
"targetBundle" => $target_bundle,
"codeExecute" => $code_execute
);
}
}
Then my function to escape quotes (note that it's an older function that might need to be updated, but hasn't caused me any issues until now):
function mysqli_prep($value) {
global $connection;
$magic_quotes_active = get_magic_quotes_gpc();
$new_enough_php = function_exists("mysqli_real_escape_string"); // i.e. PHP >= v4.3.0
if($new_enough_php) { // PHP v4.3.0 or higher
// undo any magic quote effects so mysql_real_escape_string can do the work
if($magic_quotes_active) {$value = stripslashes($value); }
$value = mysqli_real_escape_string($connection, $value);
} else { // before PHP v4.3.0
// if magic quotes aren't already on then add slashes manually
if(!$magic_quotes_active) {$value = addslashes($value); }
// if magic quotes are active, then the slashes already exist
}
return $value;
}
Then I run this function on the array and serialize it:
$bnd_keyboard_arr = mysqli_prep(serialize($bnd_keyboard_arr));
Serialized data before insert into MYSQL looks like this:
a:1:{s:9:\"keyboards\";a:1:{s:5:\"aaa\'s\";a:2:{s:12:\"targetBundle\";s:2:\"93\";s:11:\"codeExecute\";s:3:\"aaa\";}}}
When I go to retrieve the data, unserialize it and echo into my page, If the 1st field (which is actually the KEY for an array within the array) has a quote, then it echo's ok, but then the next 2 values break and won't echo (either in a normal text echo, or within an input field).
If none of the 3 values have single quotes, then all 3 echo out properly inside the input's.
If the 3rd value has a single quote, then all three echo fine. Basically when my page encounters a single quote, even after htmlentites or htmlspecialchars is used, it breaks the rest of the values being echoed from the array.
I'm really stumped.
Well, I solved it. Good exercise for me though b/c it forced me to upgrade the way I send queries to MYSQL. I think that's way upgraded, although it turns out that had nothing to do with my original issue.
The problem, stupid as it always is, was this:
I was creating a htmlspecialchars string just fine like:
$keyboard = htmlspecialchars($keyboard, ENT_QUOTES);
Then I was grabbing a value from an array, except that used my $keyboard value like this:
$keyboard_arr = $bnd_keyboard_arr['keyboards'][$keyboard];
So of course if I was converting the $keyboard string using htmlspecialchars prior to inserting that string in my array key, well, it would break $keyboard_arr
The solution was to just move the $keyboard_arr = $bnd_keyboard_arr['keyboards'][$keyboard]; to one line after the $keyboard_arr = $bnd_keyboard_arr['keyboards'][$keyboard];
Yup. Like I said, JV.

PHP - Adding string value to associative array

This seem so simple, and yet I can't find a solution anywhere.
What I want to do is add the contents (r-value) of a variable to an associative array instead of a reference to the variable.
For example, I want this:
$myStr1 = "sometext";
$myStr2 = "someothertext";
$myArray = array(
"key1"=>$myStr1,
"key2"=>$myStr2
);
echo($myArray["key1"]);
To produce this:
"sometext"
Instead of this:
"1" // why??
Any help would be appreciated.
EDIT:
The above works; my bad. Here's the real problem - my $myStr1 variable isn't just assiged a string literal like in the above; it's created using the following syntax:
$myStr1 = "sometext" + anObject->intProperty + "moretext";
Basically I use the + to concatenate various types into a string. Maybe + isn't doing what I think it's doing?
EDIT:
It was definitely the + operator. I casted all non-strings to strings and used . to concatenate instead.
You've got it correct the first time. Try this:
$myStr1 = "sometext";
$myStr2 = "someothertext";
$myArray = array(
"key1"=>$myStr1,
"key2"=>$myStr2
);
unset($myStr1);
echo($myArray["key1"]);
Even though we unset() the $myStr1 variable, it still echoed sometext.
It should be noted that while it is possible to set $myStr1 by reference, it's not the default.
Try your code and its result is:
sometext

PHP not sending id

I have a script that I wrote to look up an ID based on uniqueID
if ($_REQUEST['uniqueId'] != ""){
$qA = "SELECT id FROM customerdata WHERE uniqueId = \"". $_REQUEST['uniqueId']."\"";
$rA = mysql_query($qA);
list($id) = mysql_fetch_row($rA);
echo $id;
exit;
if ( mysql_num_rows ($rA) > 0) {
header('Location:response-en.php?id=$id');
}
else
{
header('Location:not-found.php');
}
}
Rather than sending the user to response-en.php?id=1 it sends them to response-en.php?id=$id
Any idea why this is happening? Any help would be greatly appreciated! Thank you!
Use:
header('Location:response-en.php?id='.$id);
When you use a single quote: '
This is a string literal. Everything (and I mean EVERYTHING) inside that string is taken wholesale. If you did this: $something = 'Location:response-en.php?id=$id';, the value of $something is: Location:response-en.php?id=$id In order to add a variable into the string, you use the concatenation operator .. Thus, the value of $something after $something = 'Location:response-en.php?id='.$id; would be Location:response-en.php?id=5 (assuming $id = 5)
See: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
When you use double quote: "
PHP will search inside your sting to find any variables. It will then replace the variable name with the value of the variable. If you did this: $something = "Location:response-en.php?id=$id";, the value of $something is: Location:response-en.php?id=5 - note the use of double quotes.
See: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
Also, I wanted to add that your script is vulnerable to SQL-injection attack. Always sanitize query-string values before using them in an SQL query. For more info on sanitizing values for sql, see the docs for mysql_real_escape_string.
Variables inside a single-quoted string are not parsed. Variables inside double quotes are. Check out:
http://www.php.net/manual/en/language.types.string.php
You need double quotes to process variables in a string. Not single quotes.
You have to use " in stead of '
header("Location:response-en.php?id=$id");
or:
header('Location:response-en.php?id='.$id);
Try enclosing your string with double quotes instead of single quotes for correct variable parsing:
"Location:response-en.php?id=$id"
or use complex syntax with curly braces surrounding your variables:
"Location:response-en.php?id={$id}"
See manual.

Categories