I have a txt file that contains an array like this:
array (
0 => 'jack',
1 => 'alex'
)
I want to use this array in my PHP code but it is not working as on this example which returns a
$list= file_get_contents(myfile.txt);
echo $list[0];
How can I convert it ?
Rather have the array serialized or json_encoded, inside that file.
Then, when reading it, just unserialize or json_decode in $list
Example:
$list = unserialize(file_get_contents(myfile.txt));
To answer the quextion - eval looks like it will handle the array (Array has been output with var_export ?)
BUT exec'ing unknown code is a bad idea, W0rldart has the better ways to do it (json would be my preference)
Related
My code
I have a function get_points_table() that returns an array like so:
Array
(
[0] => Array
(
[player] => steve
[points] => 10
)
[1] => Array
(
[player] => jess
[points] => 7
)
)
I would like to pass this array as JSON to a JavaScript script to output as HTML.
My current script looks like this:
<?php
require_once 'db.php';
$points_table = get_points_table($dbh);
echo json_encode($points_table);
?>
My problem
My understanding is that if I don't sanitise the data before echo'ing it back, there is a security risk posed by a player setting their username to something like steve<script>alert()</script> or using some other combinations of special characters.
My research suggests I need to use some combination of htmlentities() and/or htmlspecialchars() to safely output the data. However htmlentities() does not return utf8 encoded data, so I also need to use utf8_encode() in order for json_encode() to understand it. htmlentities() also does not allow you to pass an array as a value.
What I've tried
I've tried various combinations of array_walk(), array_walk_recursive() and array_map() to apply htmlentities() to each value of my array but to no success. I've also tried accessing the values in nested foreach loops to no success either. e.g.:
foreach($points_table as $key=>value) {
htmlspecialchars($value);
htmlentities($value);
utf8_encode($value);
}
echo json_encode($points_table);
What I need
I would like to know how to sanitise my array so I can safely pass it as JSON to be output as HTML, even if the user sets their username to something like steve<script>alert()</script><php echo "hello world";?> ;-- - &%00
Ideally I would like to do this so that the end result has the username in human readable format without converting symbols to html entities (i.e. steve<script> not steve"<script>")
This feels like a very common thing developers would do and should have a simple and easy answer, but I have done much searching and cannot work it out for myself.
I am trying to read string in session array.
Here is the code I entered $fruit_type into my session:($number is 2622232 here)
$_SESSION['fruit'][$number]=$fruit_type;
When I used print_r($_SESSION['fruit']), I get the following array:
Array ( [2622232] => [] => apple )
My question is how can I get the string "apple"? My editor give me error message when I tried to use $_SESSION['fruit'][$number][] to read string.
Any idea about my situation?
The only way to get that print_r() output is with an empty string as key [''], so you need to find where you do that and fix it. However you can access it:
echo $_SESSION['fruit'][2622232][''];
$_SESSION['fruit'][$number][] is wrong as you don't pass an index. Something like $_SESSION['fruit'][$number][0] should work.
You can find more information about arrays in the PHP documentation (here the example that solves your problem)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Im not sure what I am doing wrong here. I have a txt file that stores and array:
Array
(
[0] => Array
(
[sku] => 123123
)
)
When I go to read the file by php and loop over it, it gives me this error:
Invalid argument supplied for foreach()
Code:
$items = $file->getContents();
foreach($items as $item){
}
Alternate Code (serialize and unserialize):
$items = $file->getContents();
$itemsA = serialize($items);
$itemsB = unserialize($itemsA);
foreach($itemsB as $item){
}
Produces this error as well: Invalid argument supplied for foreach()
you can serialize it then unserialize or json_encode then json_decode
if your files are not dynamic (aka config files) check this answer
That is a var_dumped array. To store an array in a file you can serialize it and then write it and when you read it from the file you then unserialize it to get the array back.
Array
(
[0] => Array
(
[sku] => 123123
)
)
$items = $file->getContents();
$items = str_replace(array('> Array','[',']'),array('> new Array',"'","'"),$items );
file_put_content("TMPFILENAME","<\?PHP\n return new $items;");
$items = include "TMPFILENAME";
Replace " ' if needed
If you need numeric key do some like first:
$items = preg_replace('#(?:\[([0-9]+)\])+#','$1',$items );
Still dirty!
Convert var_dump of array back to array variable
\? to ? !!! WYSIWYG...
Due to the lack of code, I will make a few assumptions.
These will be changed when the needed code is added.
There is no information about how that file was created.
The output looks like it came from either var_dump() or print_r().
I'm not entirely sure of which was used.
If these were used, forget the file.
If you want to recover this file, you have to manually convert it into actual working code (by adding quotes around the key names in the arrays), add return (with space after) to the file and include it.
To re-do the file, and for the next time you write it, you have several methods:
Use the function serialize():
This is easy to use!
Simply pass the variables and you are set.
Here's an example:
$text=serialize($variable);
Then you use unserialize() to extract the data.
Like this:
$data=unserialize($text);
Use json_encode() to save the data.
It works the same way:
$text=json_encode($data);
And use json_decode() to get the data back, like this:
$data=json_decode($text);
Notice that the JSON data can be used in many other languages, including Javascript!
Also, this method is faster than serialize().
Use var_export() to get valid PHP code in a string.
Like this:
$php=var_export($data);
//write the file like this, prepending '<?php return ' to it:
file_put_contents('file.php','<?php return '.$php);
Which will write something like:
return Array(1,2,3); //example code.
To read the file, simply use include or require:
$data=include 'file.php';
Yes, include can receive the array data!
This is, by far, the fastest method!
I have text file containing values like this:
varname:
{
varname2: value
varname3:
{
varname4: value
}
}
I need to get this somehow into php array like this:
array(
varname => array
(
varname2 => value
varname3 => array
(
varname4 => value
)
)
)
How can i do this?
I have tried looping through file and trying to make values like that but it gets very tricky when there is multiple level array. Spent many hours without luck...
I suggest you (if you can) to change your file format to a JSON format, that is very similar to your format now:
{"varname":{"varname2":"value","varname3":{"varname4":"value"}}}
Then you can read the file and use json_decode to obtain the array in a very simple form. Here I write the code for decode json to array and echo it:
$s = file_get_contents('datos.js');
$ar = json_decode($s, true);
print_r($ar);
It depends on how much of a hack you want it to be. If you have a true defined format and want to be strict you'd start with a lexer. See http://wezfurlong.org/blog/2006/nov/parser-and-lexer-generators-for-php/ or https://github.com/nikic/Phlexy
On the other hand you could also make it in two steps (depending on how complicated the now shown use cases are).
Replace all leading spaces and replace : \n{ with : { for easier parsing.
Write a recursive parsing function. In every line everything before : is the variable name, everything after the value. If the value is { to a recursion until } and use the result as the value.
I am working on a project in which I will get an array.
When I use print_r($arr) it looks like this:
Array
(
[0] => games,
[1] => wallpapers,
.....
)
What i want to do is that i want it's value to be in an array like array('games','wallpapers') and save it to a file called data.txt using file_put_contents.
I did it once myown using implode() but sometimes it gets error. Is there a good way?
You need to serialize it and save it to a file. You can do it as a comma-separated values using implode(), or as a json string using json_encode() or using serialize(). All three of those links have excellent documentation and examples.
If you still have troubles, please edit your question with more specific details and the code you've worked on so far.
Try this,
<?php
$a=array
(
0 => 'games',
1 => 'wallpapers'
);
$str= implode(',',$a);
file_put_contents('data.txt', $str);
?>
data.txt
games,wallpapers
To retrieve the values, use array_values(). To store this array to disk, first serialize(), then store the output anyway you like - file_put_contents is the simplest way I believe.