,what is the use and benefit of Serialize() function in php - 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.

Related

PHP: Good way to reconstruct associative array from base64_decode

I want to base64_encode the parameters I send over the url.
Send:
<?php
$product = array("productID"=>"13776", "name"=>"something", "availability"=>"1000");
$url_details = "?id=" . base64_encode(http_build_query($product));
?>
Details
Receive:
<?php
$details = base64_decode($_GET["id"]);
// $product = what is the best way to reconstruct the array from $details?
?>
<p>
Name: <?php echo $products["name"]; ?>
...
</p>
The encoding destroys the array, is there a convenient way to make an associative array out of the string again?
(the encoded url is not sensitive information, but I still do not want it to be flat out readable in the url. If there is a better way to pass this data between pages than what I am doing, let me know)
parse_str is the inverse of http_build_query, so to recover your data:
parse_str(base64_decode($_GET["id"]), $details);
Note that parse_str is harmful if called with only one argument.
And as an aside, you may not want to put this kind of information into the URL to begin with, since it can be easily disclosed to third parties, via the Referrer header, for instance.
You can serialize() your array:
<?php
$product = array("productID"=>"13776", "name"=>"something", "availability"=>"1000");
$url_details = base64_encode(serialize($product));
And then, on your end page unserialize() it:
<?php
$details = unserialize(base64_decode($url_details));
Demo
However you need to be careful and do thorough checking of what you're receiving, since unserialize() will execute arbitrary code sent by the client. For example, I can serialize() my own array, then base64_encode() it, and pass it to the URL in the id parameter, and I can do pretty nasty stuff. So definitely check what you're getting in the request!
From the manual:
Warning
Do not pass untrusted user input to unserialize() regardless of the
options value of allowed_classes. Unserialization can result in code
being loaded and executed due to object instantiation and autoloading,
and a malicious user may be able to exploit this. Use a safe, standard
data interchange format such as JSON (via json_decode() and
json_encode()) if you need to pass serialized data to the user.
Here's a comprehensive article on the matter. Give it a read!
As the manual says, you can also probably accomplish what you're trying to do with json_encode() and json_decode(), though the same warning remains, check that what you're getting is what you're supposed to get and sanitize it.

What is the substring equivalent in PHP

I am getting JSON files but each file has a code/ID with it, in the beginning
i am trying to make a standard way to crop the strings no matter how the code/ID changes.
so these are 2 JSON files:
a:12{/*JSON DATA HERE*/}
a:130 {/*JSON DATA HERE*/}
a:1 {/*JSON DATA HERE*/}
i did not find a way to locate the first occurrence of "{" and include it in the new string that will also include the rest of the JSON string.
in JAVA it would go something like that, but i need it in php:
String myjson = "a:130{/*JSON here*/}";
String newjson = myjson.substring(myjson.indexOf("{"), myjson.length());
how can i do that in php?
This really seems to be a PHP serialized array (through serialize / unserialize) and not JSON.
PHP uses a:<count>{...} to indicate a serialized array in its format.
If you can trust the data (i.e. not user submitted but generated by a trusted application), don't parse it yourself and use unserialize instead.
The reason why you never should use unserialize on user submitted data that you can't verify independently is that it is able to create objects of a user specific selection, and if the object defines __wakeup, it might be able to coerce the object into performing any operation the attacker want. This is also why there is a large warning on the unserialize manual page.

PHP Unserialize data for use in array - sub standard characters in string

I am using a jQuery plugin of nestable forms and storing the order of these in a database using serialize (achieved through JS). Once I retrieve this data from the database I need to be able to unserialize it so that each piece of data can be used.
An example of the data serialized and stored is
[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]
The number of ID's stored in each serialized data varies and the JS plugin adds the [ and ] brackets around the serialization.
I have used http://www.unserialize.com/ to test an unserialization of the data and it proves successful using print_r. I have tried replicating this with the following code:
<?php
print_r(unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]'));
?>
but I get an error. I am guessing that I need to use something similar to strip_tags to remove the brackets, but am unsure. The error given is as follows
Notice: unserialize(): Error at offset 0 of 70 bytes
Once I have the unserialized data I need to be able to use each ID as a variable and I am assuming to do so I need to do something as:
<?php
$array = unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]');
foreach($array as $key => $val)
{
// Do something here, use each individial ID however
// e.g database insert using $val['id']; to get H592736029375 then K235098273598 and finally B039571208517
}
?>
Is anyone able to offer any help as to how to strip the serialized data correctly to have the ID's ready in an array to then be used in the foreach function?
Much appreciated.
PHP's serialize() and unserialize() functions are PHP specific, not for communicating with other languages.
It looks like your JS serialize function is actually generating JSON though, so on the PHP side, use json_decode() rather than unserialize.
Here's a fiddle
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $index=>$data){
echo "$index) {$data['id']}\n";
}
Outputs:
0) H592736029375
1) K235098273598
2) B039571208517

create a dynamic php file and define an array

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.

PHP passing variables between more function

I have about 30 variables that I need to pass to 3 functions e.g.
displayform() - where some form data is pulled out from DB and some needs to be entered into the form.
checkform() - which checks if all data is entered properly.
errors() - this will display errors (if any)
processform()- this process all data and store them to DB
Now I am using GLOBAL $variable; to pass those variables between functions, but than I have to declare each variable as global at the function begin and that results in a big file, so I just want to know is there a way to declare variables as globals (preferably only once) so that all functions can use them ?
You can try putting all the variables into an associative array and just passing this array between functions, like:
$omgArray = array();
$omgArray['lolVar1'] = lolVar1;
$omgArray['wowVar3'] = wowVar3;
yeaaaFunction($omgArray);
function yeaaaFunction($omgArray){
echo $omgArray['lolVar1'] . $omgArray['wowVar3'];
}
30 variables? Apart from 30 variables being horrible to maintain, having 30 global variables is even worse. You will go crazy one day...
Use an array and pass the array to the functions as argument:
$vars = array(
'var1' => 'value1',
'var2' => 'value2',
///...
);
displayform($vars);
//etc.
Learn more about arrays.
I have a similar scenario where I wrote a class lib for form handling similar to yours. I store all form data into a single array internally in the form class.
When moving form data outside the class I serialize the array into JSON format. The advantage of the JSON format (over PHP's own serialized format) is that it handles nested arrays very well. You can also convert the character set for all the form fields in one call.
In my application I store all form data as a JSON string in the database. But I guess it all depends on your needs.
You may want to read about Registry pattern, depending on your data, it may be useful or not.

Categories