PHP How to extract variable from serialized mysql string? - php

Within a php file I'm trying to extract the user_name var in this string
user_name|s:11:"testaccount";user_email|s:27:"testaccount#testaccount.com";user_login_status|i:1;
I can't figure out what formatting this is though. I am using php mysqli to query the database with this function
$q = "SELECT `data` FROM `sessions` WHERE `id` = '".$this->dbc->real_escape_string($cookie)."' LIMIT 1";
where $cookie is a cookie of the client. Does anyone recognize the format of the string?

Name , email and status are separated by semi colon. Name and value separated by pipe. Value is in serialize form.
For eg. user_name|s:11:"testaccount";
Unserialise s:11:"testaccount"; you will get testaccount value

Figured it out. Used this function to do it https://gist.github.com/phred/1201412.
//
// This is the result of about an hour's delving into PHP's hairy-ass serialization internals.
// PHP provides a session_decode function, however, it's only useful for setting the contents of
// $_SESSION. Say, for instance, you want to decode the session strings that PHP stores in its
// session files -- session_decode gets you nowhere.
//
// There are a bunch of nasty little solutions on the manual page[1] that use pretty hairy regular
// expressions to get the job done, but I found a simple way to use PHP's unserialize and recurse
// through the string extracting all of the serialized bits along the way.
//
// It's not speedy (it calls unserialize AND serialize for each session element), but it's accurate
// because it uses PHP's internal serialized object parser. Fun trivia: PHP's serialized object
// parser is an ugly-ass little compiled regular expression engine. But hey, it works, let's not
// reinvent this wheel.
//
// [1]: http://www.php.net/manual/en/function.session-decode.php
//
define("SESSION_DELIM", "|");
function unserialize_session($session_data, $start_index=0, &$dict=null) {
isset($dict) or $dict = array();
$name_end = strpos($session_data, SESSION_DELIM, $start_index);
if ($name_end !== FALSE) {
$name = substr($session_data, $start_index, $name_end - $start_index);
$rest = substr($session_data, $name_end + 1);
$value = unserialize($rest); // PHP will unserialize up to "|" delimiter.
$dict[$name] = $value;
return unserialize_session($session_data, $name_end + 1 + strlen(serialize($value)), $dict);
}
return $dict;
}
$session_data = …; // A string from a PHP session store.
$session_dict = unserialize_session($session_data);

Related

How do i separate my array strings delimiter (|) using implode function of php

How do I separate my array strings delimiter (|) using the implode function of PHP something like the below String
|Java||PHP||Bootstrap||HTML||CSS|
Actually, I am using a double delimiter to differentiate tags like SQL and MySQL because LIKE "%sql%" will return MySQL results as well. Should be LIKE "%|sql|%"
What I have tried:
$array_service_offer = array();
if (isset($_POST['service_offer'])) {
foreach ($_POST['service_offer'] as $selectedOption) {
array_push($array_service_offer, $selectedOption);
}
//$service_offer = implode(',',$array_service_offer);
$service_offer = '|' . implode('||', $array_service_offer) . '|';
} else {
$service_offer = "";
}
First of all, according to #Qirel comment, I would also recommend to use $array_service_offer[] = $selectedOption; instead of array_push($array_service_offer, $selectedOption);
now for separation, there are several solutions.
One solution is that:
1- to remove first and last | character (it is like trimming)
2- to explode the trimmed string using || delimiter
for that you may use the following code:
$service_offer_trimmed = preg_replace("~(^\|)|(\|$)~", "", $service_offer);
$service_offer_array = explode('||', $service_offer_trimmed);
The other solution is to use straight forward preg_replace function to separate the string. the command follows:
$service_offer_array = preg_split("~(^\|)|(\|\|)|(\|$)~", $service_offer, 0, PREG_SPLIT_NO_EMPTY);
And one more professional solution is that to store your data in database in JSON format rather than delimited code and then when you need to search in your database you may use MySql JSON_CONTAINS function rather than LIKE command.
I have not personally made a performance check on both two solutions but if it not a big database, then it is not a big concern as well.
Therefore, you initial code to get the data and store it into the database will be:
$array_service_offer = array();
if (isset($_POST['service_offer'])) {
foreach ($_POST['service_offer'] as $selectedOption) {
$array_service_offer[] = $selectedOption;
}
}
// $json_service_offer will be saved to the database
$json_service_offer = json_encode($array_service_offer);
the manual on how to use JSON_CONTAINS is in the following link:
12.17.3 Functions That Search JSON Values

PHP Function and variables stored in a string in a database

I need to store data within a database, when I get the data from the database I need functions and variables in the string to be worked out as such.
Example
$str = "<p>Dear {$this->name},</p>"
I then store this in the database, and when I retrieve the string and run it through
eval("\$detail= \"$detail\";");
then the variable gets populated with the name. This is exactly what I needed and works fine.
The problem is I want to run a function with this variable as the parameter.
example. I would like to ucwords the variable.
I have tried:
$str = "<p>Dear {ucwords($this->name)},</p>" //just echoed {ucword(->name)},
$str = "<p>Dear {ucwords($this->name)},</p>" //Fatal error: Function name must be a string,
Am I going in the right direction?
Is this at all possible?
You don't need to keep PHP code in database. This is a bad practice and also can lead to security vulnerabilities.
Instead store in database string like this:
<p>Dear [name],</p>
And when you retrieve it you can just do:
$stringFromDb = str_replace("[name]", $this->name, $stringFromDb);
or
$stringFromDb = str_replace("[name]", ucwords($this->name), $stringFromDb);
Other common approach is to use sprintf. So you need to store in database string with %s as placeholders for values.
Example:
<p>Dear %s,</p>
and replace with
$stringFromDb = sprintf($stringFromDb, ucwords($this->name));
What you seem to be looking for is a simple templating language.
It's been a long while since I've written PHP (and I suddenly remember why...), but here's something I whipped up.
It should support both objects ($a->name) and arrays ($a["name"]) as input objects.
You can add new filters (name -> function name mapping) in $valid_filters.
$valid_filters = array("title" => "ucfirst", "upper" => "strtoupper");
function _apply_template_helper($match) {
global $_apply_template_data, $valid_filters;
$var = $match[1];
$filter = $valid_filters[trim($match[2], ':')];
$value = is_array($_apply_template_data) ? $_apply_template_data[$var] : $_apply_template_data->$var;
if($filter && !empty($value)) $value = call_user_func($filter, $value);
return !empty($value) ? $value : $match[0];
}
function apply_template($template, $data) {
global $_apply_template_data;
$_apply_template_data = $data;
$result = preg_replace_callback('/\{\{(.+?)(:.+?)?\}\}/', "_apply_template_helper", $template);
$_apply_template_data = null;
return $result;
}
How to use it:
$template = "Hello {{name:title}}, you have been selected to win {{amount}}, {{salutation:upper}}";
echo apply_template($template, array("name"=>"john", "amount" => '$500,000', "salutation" => "congratulations"));
The result:
Hello John, you have been selected to win $500,000, CONGRATULATIONS
I have found the following works,
If i contain the function within the class itself then it can be called using the following code
<p>Dear {\$this->properCase(\$this->rl_account->name)},</p>
But i would like to be able to do this now without having the database have the code as Alex Amiryan mentions earlier.

PHP json_encode a debug_backtrace() with resource types

Currently, I have a logger which logs errors together with a backtrace.
The logger serializes the backtrace to JSON via json_encode().
Let's look at some hypothetical code...
<?php
error_reporting(-1); // show all errors
function test($b){
echo json_encode(debug_backtrace()); // take a backtrace snapshot
}
$c = imagecreate(50,50); // create a resource...
test($c); // ...and pass to function
?>
If you run the code above, we will see something like:
Warning: json_encode() [function.json-encode]: type is unsupported, encoded as null in /code/ch6gVw on line 5
[{"file":"/code/ch6gVw","line":8,"function":"test","args":[null]}]
We can notice two things going on here:
The logger itself is causing a warning! Bad bad bad!
The logged data tells us we passed a null to the function?!?!
So, my proposed solution is something like:
foreach($trace as $i=>$v)
if(is_resource($v))
$trace[$i] = (string)$v.' ('.get_resource_type($v).')';
The result would look like Resource id #1 (gd)
This, however, may cause some grave issues.
We need to somehow track which arrays we looped through so as to avoid ending up in infinite loops with arrays referencing themselves ($GLOBALS tend to cause this mess).
We would also have to convert resources of object properties, but objects, unlike arrays, are not a copy of the original thing, hence changing the property changes the live object. On the other hand, how safe is it to clone() the object?
Won't such a loop severely slow down the server (backtraces tend to be large, no)?
I ended up with the following function:
function clean_trace($branch){
if(is_object($branch)){
// object
$props = array();
$branch = clone($branch); // doesn't clone cause some issues?
foreach($props as $k=>$v)
$branch->$k = clean_trace($v);
}elseif(is_array($branch)){
// array
foreach($branch as $k=>$v)
$branch[$k] = clean_trace($v);
}elseif(is_resource($branch)){
// resource
$branch = (string)$branch.' ('.get_resource_type($branch).')';
}elseif(is_string($branch)){
// string (ensure it is UTF-8, see: https://bugs.php.net/bug.php?id=47130)
$branch = utf8_encode($branch);
}
// other (hopefully serializable) stuff
return $branch;
}
You can see it in action here. However, I'm not convinced:
It is quite slow (iterating over lots of data)
It is quite memory intensive (data needs to be copied to not mess the original)
It is not safe in case where arrays/objects reference themselves
Example: $a = array(); $a['ref'] = &$a; (PHP does this to some internal variables)
I'm concerned that cloning objects may have some serious side-effects (consider the magic method __clone(), an invitation to wreck havoc).
So you are trying to store the backtrace as a data structure that can be used to pretty-print the results later on?
If that isn't needed I'd just store $result = print_r(debug_backtrace(), true) and be done with it.
If not my first shot would be something like:
<?php
error_reporting(-1);
function test($b){
echo json_encode(clean(debug_backtrace()));
}
$c = fopen("/tmp/foo", "w");
test($c);
function clean($trace) {
array_walk_recursive($trace, function(&$element) {
if(is_object(&$element)) {
// work around unrealizable elements and preserve typing
$element = array(get_class($element), (object)$element);
} else if(is_resource($element)) {
$element = get_resource_type($element) . '#' .(int)$element;
}
});
return $trace;
}
It's just a rough sketch but I'm not aware of any project that stores backtracks for later inspection in a non textual or already processed format and looking around the mature frameworks didn't bring anything up

Searching within JSON with PHP for server side implementation of autocomplete jQuery plugin

I am trying to use jQuery Autocomplete Plugin in my PHP web application.
I have a JSON file on the server that has the data for the search. It looks like this:
{
"_E161": {
"keggId":"rn:R05223",
"abbrev":"ADOCBLS",
"name":"Adenosylcobalamin 5'-phosphate synthase",
"equation":"agdpcbi[c] + rdmbzi[c] -> h[c] + adocbl[c] + gmp[c] ",
},
"_E163": {
....
}
}
I would like to go through this JSON file (has 3500 entries) with PHP script that gets search term from the jQuery autocomplete plugin. Then return the entries that contain search term back to client side to populate autocomplete.
What would be a better way to implement this? My first guess is to loop through the JSON file and use strpos() But I suspect that might be slow?
You can make use on preg_grep (Return array entries that match the pattern),
// sanitize, and perform some processing to ensure is a valid regex pattern
$pattern = ...;
$json = json_decode( ... );
$arr = array();
foreach ($json as $key=>$arr)
{
$arr[$key] = $arr['name'];
}
$matches = preg_grep("/$pattern/i", $arr);
// $matches will hold the matches
// and you refer back to the $json using associate key

Create unique alpha numeric string for an input string/url?

I want to create a less than or equal to 10 character unique string for an input string which could be a url
http://stackoverflow.com/questions/ask
OR an alpha numeric string
programming124
but the result should be unique for every input...Is their any function or class that you use for your projects in php... Thanks...
If you want a unique and random string, you can use the following function to create a random string:
function randString($length) {
$charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$str = '';
while ($length-- > 0) {
$str .= $charset[rand() % 62];
}
return $str;
}
After you have generated a new string, look up your database if that string already exists. If so, repeat that step until you’ve generated a unique string. Then store that new string in the database:
do {
$randString = randString(10);
// look up your database if $randString already exists and store the result in $exists
} while ($exists);
// store new random string in database
The simplest function available in php is uniqid. It is a little longer that you had mentioned, and wont work well with load balancing, but if you are doing something super simple, it should work alright.

Categories