create a dynamic php file and define an array - php

I need to update some static site data periodically, so i am thinking of keeping it in a format easily and readily available on the server.
I am thinking of creating a php file that can be included in the code, so preparing the data gets separate from the browser requests.
i fetch the data from the db, so i have an array right now in key value format.
now i want to create a php file, that just defines that array.
the key and value will be string based values, and the data is in swedish.
is there a way to directly dump the array to a file, and then just include the file without any preprocessing. I want the file in the following output :
$array = array ();
$array ["key"] = "value";
$array ["key"] = "value";
$array ["key"] = "value";
$array ["key"] = "value";

I would also recommend looking at var_export as you won't have to serialize and encode to use it.
For example (untested):
<?php
$array = array('key' => 'v');
$exported = var_export($array, TRUE);
file_put_contents('/path/to/file', '<?php $var = ' . $exported . '; ?>');
?>
and then you can read it back in via:
<?php
include '/path/to/file';
// and now you have access to $var
// of course you may want to change the name of the $var variable as it
// will be brought into global scope (and might conflict)
?>

Use PHP's serialize and base64_encode functions and write the result to file.
When you want to use the data: simply read the file, decode and unserialize:
<?php
// dump data
$array = array("key"=>"value");
file_put_contents("test_data.txt", base64_encode(serialize($array)));
// retrieve data
$string = file_get_contents("test_data.txt");
$data = unserialize(base64_decode($string)));
var_dump($data);
Encoding the array in base64 will allow you to safely write binary data to the file (eg. extended character sets).

You can directly write the code into the file fwrite($handle, "$array = array();"); then doing an eval() on the file content you're reading back. It'll work, but its dangerous because if any malicious code is put into the text file, it will be executed.
I recommend you take a look at serialization: http://php.net/manual/en/function.serialize.php and write serialized data that you unserialize back into an array. It's much safer.

Related

Pass an array from a php script to another

I call another script with curl, This script returns (echo()) a value.
The return value could be anything, array, string, etc.
I can do the transfer with json_encode() and json_decode(), But is there any other better way (Without use JSON or $_SESSION['varName'])?
You may use PHP's own serialize function. It's native, can encode simple objects, and is less ambiguous than JSON.
Sample code:
// page.php
echo serialize($data);
And:
// receiver.php
$data = file_get_contents('http://example.com/page.php');
if ($data) $data = unserialize($data);

send an Array from Android to PHP Script over HTTP and get the data

I would like to send an integer array with 30 values Integer[] temp = new Integer[30] over HTTP (POST) to PHP an get the data in PHP again. How can I do that? I know how to send a single value, like a string, but not how to send an array.
One way is to serialize the array in the way the php serialize command does it.
After receiving the string value(by the method you currently use), you can use the unserialize command to get the array in your php code.
Here is a litle php example to demonstrate the workflow.
$arr = array(1,2,3,4,5,6);
$stringArr = serialize($arr);
echo $stringArr;
echo "<br/>";
$arr2 = unserialize($stringArr);
if ($arr === $arr2)
{
echo "arrays are equal";
}
The output of the script is:
a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}
arrays are equal
The main difficulty is to construct the resulting string for complex structures (in your case, it is pretty straight forward for an array of integers).
This fact results in the second approach.
One can use a serialization API or another notation than used by the php example.
As stated by the others, JSON is one of the widespread notations.
PHP also provides a possibility to serialize and unserialize json objects.
Simply use json_decode and look at the example in the manual.

Read and Write PHP Array in MYSQL

I want to save a PHP associative array from a PHP varible to a MYSQL database, then later access the stored value (within the MYSQL database) and use it within PHP as an associative array.
$arr = array("abc"=>"ss","aaa"=>"ddd");
now i want to save
array("abc"=>"ss","aaa"=>"ddd");
to the database and again want to retrive it and assign it to variable.
I tried to use the serialize function, but it only saved the word "Array" into database.
One way to do this is to serialize it into a string before insert, and then deserialize it into array after fetching. There are different ways to do that, but if your arrays are simple, JSON is an acceptable serialization format.
You could json_encode on the way in:
$str = json_encode($arr);
// Insert $str into db
Then json_decode later:
// Got $str from db
$arr = json_decode($str);
Another method is serialize:
$str = serialize($arr);
// Insert $str into db
And unserialize:
// Got $str from db
$arr = unserialize($str);
This will allow more possibilities for what you can serialize than json_encode and json_decode, but it will be harder to inspect the database manually to see what's in there.
So both methods have advantages and disadvantages. There are other serialization/marshal formats out there too.
As Ben said, you need to serialize your array before storing it in the database then unserialize it when you read it back. If 'Array' is being written to your database then you are probably not saving the results of serialize() to the variable that you are writing.
<?php
function store()
{
$arr = array("abc"=>"ss","aaa"=>"ddd");
$serialized = serialize($arr);
// Store $serialized to the database
}
function retrieve()
{
// Retrieve $serialized from the database
$arr = unserialize($serialized);
}

,what is the use and benefit of Serialize() function in php

I know its Generates a storable representation of a value and used to access the objects across the php files but what if i dont use this function while storing the objects.
Let's say you have some post data, but your database/persistent storage can't be modified to store the new post data in separate fields.
You could serialize your $_POST array and store it in the persistent storage you've got. It's useful for generating user-based CRUD applications. I've found the necessity of storing the POST as a "payload" of sorts quite invaluable at times.
Knowing you can do something, doesn't mean you have to use it everywhere.
That is easly explained by reading the official PHP page that states:
Generates a storable representation of a value
This is useful for storing or passing PHP values around without losing their type and structure.
Basically you can serialize an object write the string in a file and on another request you can simply read the file and unserialize it to have the final object loaded.
When you want to store or send data in a "safe" format, preserving PHP type and structure.
For example, you have an UTF-8 string with Japanese text. Or a multidimensional array. You can save it to a text file or insert into a database.
$array = array( 'key' => 'value', 'other_key' => 'other_value');
file_put_contents( 'array.txt', serialize( $array ) );
When you want to use the stored data, you may use the "unserialize" function:
$contents = file_get_contents( 'array.txt' );
$array = unserialize( $contents );
You can serialize values of any PHP type, including objects, but except the "resource" type (database connections, file handlers, etc.)
When you unserialize an object, you must ensure to have loaded its class previously.
More at the PHP manual: http://php.net/serialize
To serialize means converting runtime variables into consistent form.
Often this is a simple string or XML representation of the code segment.
Usage:
<?php
$user = new UserObjectFromDatabase();
$data = serialize($user);
http_reqeust_send($to = "some remote server", $data);
// the remote server can now use unserialize($data) to re-construct the user object
?>
If you want to communicate a PHP variable (array, class, string, etc) to another script/a database/write it in a file, you serialize it. Suppose you have a little script that you want to run multiple times, and you need a place to keep some data between script runs. Here is a sketch of what you do:
if(file_exists($thefile)) {
$data = unserialize(readfile($thefile));
} else {
$data = array(); // or anything
}
// do something with data
$f = fopen($thefile);
fwrite($f, serialize($data));
fclose($f)
You can store a PHP structure in a file, session or even database. I use it for caching query results in a file or in memcache.

outputting all array values to file with php

Im working with a foreign API and im trying to get a fix on what all its sending to my file with the GET method.
How can i output something like print_r($_GET) to a file so i can read what all its sending?
If you have a hash, both of the listen solutions won't give you the keys. So here's a way to get your output formatted by print_r:
$var = print_r($your_array, 1);
file_put_contents("your_file.txt",$var);
The second option of print_r is boolean, and when set to true, captures the output.
It sounds like you need a log to store the $_GET variables being submitted to your script, for debug purposes. I'd do something like this appending values to the end of the file, so the file is not overwritten every request:
file_put_contents('path_to_log.txt', print_r($_GET, true), FILE_APPEND);
Writing to a file:
You could use file_put_contents() to create the file with your output. This function will accept a string, or an array, which releases you of the burden to convert your array into a writable-format.
file_put_contents("myget.txt", $_GET);
As stated in the comments, this option isn't ideal for multidimensional arrays. However, the next solution is.
Maintaining format:
If you'd like to maintain the print_r() formatting, simply set the second parameter to true to return the value into a variable rather than outputting it immediately:
$output = print_r($_GET, true);
file_put_contents("myget.txt", $output);

Categories