<?php
#[\ReturnTypeWillChange]
public function write($session_id, $session_data)
{
// If the two IDs don't match, we have a session_regenerate_id() call
// and we need to close the old handle and open a new one
if ($session_id !== $this->_session_id && ($this->close() === $this->_failure OR $this->read($session_id) === $this->_failure))
{
return $this->_failure;
}
if ( ! is_resource($this->_file_handle))
{
return $this->_failure;
}
elseif ($this->_fingerprint === md5($session_data))
{
return ( ! $this->_file_new && ! touch($this->_file_path.$session_id))
? $this->_failure
: $this->_success;
}
if ( ! $this->_file_new)
{
ftruncate($this->_file_handle, 0);
rewind($this->_file_handle);
}
if (($length = strlen($session_data)) > 0)
{
for ($written = 0; $written < $length; $written += $result)
{
if (($result = fwrite($this->_file_handle, substr($session_data, $written))) === FALSE)
{
break;
}
}
if ( ! is_int($result))
{
$this->_fingerprint = md5(substr($session_data, 0, $written));
log_message('error', 'Session: Unable to write data.');
return $this->_failure;
}
}
$this->_fingerprint = md5($session_data);
return $this->_success;
}
Message: syntax error, unexpected token "break"
What am I doing wrong here? Is there perhaps a problem somewhere else that could make this "unexpected break" error show up?
Related
So, I want to check the users-input, if it contains some of these characters:
" ' < >
I hope someone can show me a better way with less code
Thanks!
I used preg_match, but i just managed it with 4 nested if's.
/*Checks if the given value is valid*/
private function checkValidInput($input)
{
/*If there is no " */
if(preg_match('/"/', $input) == false)
{
/*If there is no ' */
if(preg_match("/'/", $input) == false)
{
/*If there is no <*/
if(preg_match("/</", $input) == false)
{
/*If there is no >*/
if(preg_match("/>/", $input) == false)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
You could create a regex class
preg_match('#["\'<>]#', $input);
Edit:
If you need to check for all characters then use strpos() with for loop
function checkInput($val) {
$contains = true;
$required = "<>a";
for($i = 0, $count = strlen($required); $i < $count ; ++$i) {
$contains = $contains && false !== strpos($val, $required[$i]);
}
return $contains;
}
var_dump(checkInput('abcd<>a')); // true
var_dump(checkInput('abcd>a')); // false, doesn't contain <
Why am I getting the following error in PHP?
<?php
require_once('validation_functions.php');
$errors = array();
//$username = trim($_POST["username"]);
$username = trim("");
if(!has_presence($username))
{
$errors['username'] = "Username can't be left blank";
}
?>
<?php echo form_errors($errors); ?>
This is the following problem:
Parse error: syntax error, unexpected ')' in C:\wamp\www\sandbox\validation_functions.php on line 20
This is the file validation_functions.php detailed above
<?php
function has_presence($value)
{
//IF $value is SET AND value is NOT EXACTLY EQUAL TO "" RETURN TRUE
return (isset($value) && $value !== ""); //RETURNS BOOLEAN
}
function has_max_length($value, $max)
{
//IF $value is LESS THAN OR EQUAL TO $max Return TRUE
return (strlen($value) <= $max)); //RETURNS BOOLEAN
}
function has_inclusion_in($value, $set)
{
//IF $value is INCLUDED in $set RETURN TRUE
return in_array($value, $set); //RETURNS BOOLEAN
}
function form_errors($errors = array())
{
$output = "";
if(!empty($errors))
{
$output = "<div class= \"error\">";
$output .= "Please Fix The Following Errors:";
$output .= "<ul>";
foreach($errors as $key => $error)
{
$output .= "<li> {$error} </li>";
}
$output .= "</ul>";
$output .= "</div>";
}
return $output;
}
?>
This is included in the code referenced above. It's a simple error but I can't seem to understand what's causing it.
You have an extra bracket in the marked line
function has_max_length($value, $max)
{
//IF $value is LESS THAN OR EQUAL TO $max Return TRUE
>>>>>>>>> return (strlen($value) <= $max)); //<<<< here is a extra bracket, remove the last one!
Should be like this:
return (strlen($value) <= $max)
correct way: return (strlen($value) <= $max);
function has_max_length($value, $max)
{
//IF $value is LESS THAN OR EQUAL TO $max Return TRUE
return (strlen($value) <= $max); //RETURNS BOOLEAN
}
I am implementing my own StringTokenizer class in php, because the strtok function can only handle one opened tokenizer at the same time.
With
Hello;this;is;a;text
it works perfectly.
The output is:
**Hello**
**this**
**is**
**a**
**text**
But with
Hello;this;is;a;text;
it outputs:
**Hello**
**this**
**is**
**a**
**text**
****
****
<endless loop>
But I except the following output:
**Hello**
**this**
**is**
**a**
**text**
****
See my code below and please correct me:
class StringTokenizer
{
private $_str;
private $_chToken;
private $_iPosToken = 0;
private $_bInit;
public function __construct($str, $chToken)
{
if (empty($str) && empty($chToken))
{
throw new Exception('String and the token char variables cannot be empty.');
}
elseif(empty($chToken) && !empty($str))
{
throw new Exception('Missing parameter: Token char cannot be empty.');
}
elseif(!empty($chToken) && empty($str))
{
throw new Exception('Missing parameter: String cannot be empty.');
}
elseif(!empty($chToken) && !empty($str) && is_string($str) && strlen($chToken) >= 0)
{
$this->_str = $str;
$this->_chToken = $chToken;
$this->_bInit = true;
}
else
{
throw new Exception('TypeError: Illegal call to __construct from class StringTokenizer.');
}
}
public function next()
{
if ($this->_iPosToken === false)
{
return false;
}
if ($this->_bInit === true && (strlen($this->_str) - 1) > $this->_iPosToken)
{
$iCh1stPos = strpos($this->_str, $this->_chToken, $this->_iPosToken) + 1;
$this->_iPosToken = $iCh1stPos;
$this->_bInit = false;
return substr($this->_str, 0, $this->_iPosToken - 1);
}
elseif ($this->_bInit === false && (strlen($this->_str) - 1) > $this->_iPosToken)
{
$iCh1stPos = $this->_iPosToken;
$iCh2ndPos = strpos($this->_str, $this->_chToken, $this->_iPosToken);
if ($iCh2ndPos === false)
{
$this->_iPosToken = false;
return substr($this->_str, $iCh1stPos);
}
else
{
$this->_iPosToken = $iCh2ndPos + 1;
return substr($this->_str, $iCh1stPos, $iCh2ndPos - $iCh1stPos);
}
}
}
public function hasNext()
{
return strpos($this->_str, $this->chToken, $this->_iPosToken) === false ? false : true;
}
}
$strText = 'Hello;this;is;a;text';
$tokenizer = new StringTokenizer($strText, ';');
$tok = $tokenizer->Next();
while ($tok !== false)
{
echo '**' . $tok . '**' . PHP_EOL;
$tok = $tokenizer->next();
}
exit(0);
The problem with the third condition in the next() is this. String length is 26 and the last character match is 26 which you represent with the _iPosToken. so the condition in the 3rd if is false and the block never executes for the last semicolon.
A function in php returns NULL not FALSE by default.source
and the while never terminates at the bottom of the code.
So you have two options here. change the condition in the 3rd if to (strlen($this->_str)) >= $this->_iPosToken
OR
add a 4th condtion which returns false, as shown below.
public function next()
{
if ($this->_iPosToken === false)
{
return false;
}
if ($this->_bInit === true && (strlen($this->_str) - 1) > $this->_iPosToken)
{
$iCh1stPos = strpos($this->_str, $this->_chToken, $this->_iPosToken) + 1;
$this->_iPosToken = $iCh1stPos;
$this->_bInit = false;
return substr($this->_str, 0, $this->_iPosToken - 1);
}
elseif ($this->_bInit === false && (strlen($this->_str)-1 ) > $this->_iPosToken)
{
$iCh1stPos = $this->_iPosToken;
echo $this->_iPosToken;
$iCh2ndPos = strpos($this->_str, $this->_chToken, $this->_iPosToken);
if ($iCh2ndPos === FALSE) // You can chuck this if block. I put a echo here and //it never executed.
{
$this->_iPosToken = false;
return substr($this->_str, $iCh1stPos);
}
else
{
$this->_iPosToken = $iCh2ndPos + 1;
return substr($this->_str, $iCh1stPos, $iCh2ndPos - $iCh1stPos);
}
}
else return false;
}
Why do you like reinvent the wheel ?
You can use explode function, and then implements Iterator pattern in this tokenizer, i think it's an good approach.
http://php.net/explode
http://br1.php.net/Iterator
Example
<?php
class StringTokenizer implements Iterator
{
private $tokens = [];
private $position = 0;
public function __construct($string, $separator)
{
$this->tokens = explode($separator, $string);
}
public function rewind()
{
$this->position = 0;
}
public function current()
{
return $this->tokens[$this->position];
}
public function next()
{
++ $this->position;
}
public function key()
{
return $this->position;
}
public function valid()
{
return isset($this->tokens[$this->position]);
}
}
And using it:
$tokenizer = new StringTokenizer('h;e;l;l;o;', ';');
while($tokenizer->valid()) {
printf('**%s**', $tokenizer->current());
$tokenizer->next();
}
I'm developing on a server using an old version of PHP (4.3.9), and I'm trying to convert an XML string into a JSON string. This is easy in PHP5, but a lot tougher with PHP4.
I've tried:
Zend JSON.php
require_once 'Zend/Json.php';
echo Zend_Json::encode($sxml);
Error:
PHP Parse error: parse error, unexpected T_CONST, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}'
simplexml44
$impl = new IsterXmlSimpleXMLImpl;
$NDFDxmltemp = $impl->load_file($NDFDstring);
$NDFDxml = $NDFDxmltemp->asXML();
Error:
WARNING isterxmlexpatnonvalid->parse(): nothing to read
xml_parse
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "_start_element", "_end_element");
xml_set_character_data_handler($xml_parser, "_character_data");
xml_parse($xml_parser, $NDFDstring);
Error:
PHP Warning: xml_parse(): Unable to call handler _character_data() in ...
PHP Warning: xml_parse(): Unable to call handler _end_element() in ...
Does anyone have any other alternatives to simplexml_file_load() and new simpleXMLelement in PHP4?
Upgrading PHP is not an option in this particular case, so do not bother bringing it up. Yes, I know its old.
NOTE: This is the XML I'm trying to parse into a multidimensional array OR json.
http://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php?lat=40&lon=-120&product=time-series&begin=2013-10-30T00:00:00&end=2013-11-06T00:00:00&maxt=maxt&mint=mint&rh=rh&wx=wx&wspd=wspd&wdir=wdir&icons=icons&wgust=wgust&pop12=pop12&maxrh=maxrh&minrh=minrh&qpf=qpf&snow=snow&temp=temp&wwa=wwa
XML are quite easy to parse by yourself, anyway here is exists xml_parse in php 4 and domxml_open_file
and here is json for php4 and another one
according parsing xml:
if you know the structure of xml file, you can go even with RegExp, as XML is strict format (I mean all tags must be closed, all attributes in quotes, all special symbols always escaped)
if you parse arbitrary xml file, here is student sample, which works with php4, do not understand all XML features, but can give you "brute-force" like idea:
<?php
define("LWG_XML_ELEMENT_NULL", "0");
define("LWG_XML_ELEMENT_NODE", "1");
function EntitiesToString($str)
{
$s = $str;
$s = eregi_replace(""", "\"", $s);
$s = eregi_replace("<", "<", $s);
$s = eregi_replace(">", ">", $s);
$s = eregi_replace("&", "&", $s);
return $s;
}
class CLWG_dom_attribute
{
var $name;
var $value;
function CLWG_dom_attribute()
{
$name = "";
$value = "";
}
}
class CLWG_dom_node
{
var $m_Attributes;
var $m_Childs;
var $m_nAttributesCount;
var $m_nChildsCount;
var $type;
var $tagname;
var $content;
function CLWG_dom_node()
{
$this->m_Attributes = array();
$this->m_Childs = array();
$this->m_nAttributesCount = 0;
$this->m_nChildsCount = 0;
$this->type = LWG_XML_ELEMENT_NULL;
$this->tagname = "";
$this->content = "";
}
function get_attribute($attr_name)
{
//echo "<message>Get Attribute: ".$attr_name." ";
for ($i=0; $i<sizeof($this->m_Attributes); $i++)
if ($this->m_Attributes[$i]->name == $attr_name)
{
//echo $this->m_Attributes[$i]->value . "</message>\n";
return $this->m_Attributes[$i]->value;
}
//echo "[empty]</message>\n";
return "";
}
function get_content()
{
//echo "<message>Get Content: ".$this->content . "</message>\n";
return $this->content;
}
function attributes()
{
return $this->m_Attributes;
}
function child_nodes()
{
return $this->m_Childs;
}
function loadXML($str, &$i)
{
//echo "<debug>DEBUG: LoadXML (".$i.": ".$str[$i].")</debug>\n";
$str_len = strlen($str);
//echo "<debug>DEBUG: start searching for tag (".$i.": ".$str[$i].")</debug>\n";
while ( ($i<$str_len) && ($str[$i] != "<") )
$i++;
if ($i == $str_len) return FALSE;
$i++;
while ( ($i<strlen($str)) && ($str[$i] != " ") && ($str[$i] != "/") && ($str[$i] != ">") )
$this->tagname .= $str[$i++];
//echo "<debug>DEBUG: Tag: " . $this->tagname . "</debug>\n";
if ($i == $str_len) return FALSE;
switch ($str[$i])
{
case " ": // attributes comming
{
//echo "<debug>DEBUG: Tag: start searching attributes</debug>\n";
$i++;
$cnt = sizeof($this->m_Attributes);
while ( ($i<strlen($str)) && ($str[$i] != "/") && ($str[$i] != ">") )
{
$this->m_Attributes[$cnt] = new CLWG_dom_attribute;
while ( ($i<strlen($str)) && ($str[$i] != "=") )
$this->m_Attributes[$cnt]->name .= $str[$i++];
if ($i == $str_len) return FALSE;
$i++;
while ( ($i<strlen($str)) && ($str[$i] != "\"") )
$i++;
if ($i == $str_len) return FALSE;
$i++;
while ( ($i<strlen($str)) && ($str[$i] != "\"") )
$this->m_Attributes[$cnt]->value .= $str[$i++];
$this->m_Attributes[$cnt]->value = EntitiesToString($this->m_Attributes[$cnt]->value);
//echo "<debug>DEBUG: Tag: Attribute: '".$this->m_Attributes[$cnt]->name."' = '".$this->m_Attributes[$cnt]->value."'</debug>\n";
if ($i == $str_len) return FALSE;
$i++;
if ($i == $str_len) return FALSE;
while ( ($i<strlen($str)) && ($str[$i] == " ") )
$i++;
$cnt++;
}
if ($i == $str_len) return FALSE;
switch ($str[$i])
{
case "/":
{
//echo "<debug>DEBUG: self closing tag with attributes (".$this->tagname.")</debug>\n";
$i++;
if ($i == $str_len) return FALSE;
if ($str[$i] != ">") return FALSE;
$i++;
return TRUE;
break;
}
case ">";
{
//echo "<debug>DEBUG: end of attributes (".$this->tagname.")</debug>\n";
$i++;
break;
}
}
break;
}
case "/": // self closing tag
{
//echo "<debug>DEBUG: self closing tag (".$this->tagname.")</debug>\n";
$i++;
if ($i == $str_len) return FALSE;
if ($str[$i] != ">") return FALSE;
$i++;
return TRUE;
break;
}
case ">": // end of begin of node
{
//echo "<debug>DEBUG: end of begin of node</debug>\n";
$i++;
break;
}
}
if ($i == $str_len) return FALSE;
$b = 1;
while ( ($i<$str_len) && ($b) )
{
//echo "<debug>DEBUG: searching for content</debug>\n";
while ( ($i<strlen($str)) && ($str[$i] != "<") )
$this->content .= $str[$i++];
//echo "<debug>DEBUG: content: ".$this->content."</debug>\n";
if ($i == $str_len) return FALSE;
$i++;
if ($i == $str_len) return FALSE;
if ($str[$i] != "/") // new child
{
$cnt = sizeof($this->m_Childs);
//echo "<debug>DEBUG: Create new child (" . $cnt . ")</debug>\n";
$this->m_Childs[$cnt] = new CLWG_dom_node;
$this->m_Childs[$cnt]->type = LWG_XML_ELEMENT_NODE;
$i--;
if ($this->m_Childs[$cnt]->loadXML($str, $i) === FALSE)
return FALSE;
}
else
$b = 0;
}
$i++;
$close_tag = "";
while ( ($i<strlen($str)) && ($str[$i] != ">") )
$close_tag .= $str[$i++];
//echo "<debug>DEBUG: close tag: ".$close_tag." - ".$this->tagname."</debug>\n";
if ($i == $str_len) return FALSE;
$i++;
$this->content = EntitiesToString($this->content);
//echo "<debug>DEBUG: content: ".$this->content."</debug>\n";
return ($close_tag == $this->tagname);
}
}
class CLWG_dom_xml
{
var $m_Root;
function CLWG_dom_xml()
{
$this->m_Root = 0;
}
function document_element()
{
return $this->m_Root;
}
function loadXML($xml_string)
{
// check xml tag
if (eregi("<\\?xml", $xml_string))
{
// check xml version
$xml_version = array();
if ( (eregi("<\\?xml version=\"([0-9\\.]+)\".*\\?>", $xml_string, $xml_version)) && ($xml_version[1] == 1.0) )
{
// initialize root
$this->m_Root = new CLWG_dom_node;
$i = 0;
return $this->m_Root->loadXML(eregi_replace("<\\?xml.*\\?>", "", $xml_string), $i);
}
else
{
echo "<error>Cannot find version attribute in xml tag</error>";
return FALSE;
}
}
else
{
echo "<error>Cannot find xml tag</error>";
return FALSE;
}
}
}
function lwg_domxml_open_mem($xml_string)
{
global $lwg_xml;
$lwg_xml = new CLWG_dom_xml;
if ($lwg_xml->loadXML($xml_string))
return $lwg_xml;
else
return 0;
}
?>
PHP4 has no support for ArrayAccess nor does it have the needed __get(), __set() and __toString() magic methods which effectively prevents you from creating an object mimicking that feature of SimpleXMLElement.
Also I'd say creating an in-memory structure yourself which is done by Simplexml is not going to work out well with PHP 4 because of it's limitation of the OOP-object-model and garbage collection. Especially as I would prefer something like the Flyweight pattern here.
Which brings me to the point that you're probably more looking for an event or pull-based XML parser.
Take a look at the XML Parser Functions which are the PHP 4 way to parse XML with PHP. You find it well explained in years old PHP training materials also with examples and what not.
What's the best way to determine whether or not a string is the result of the serialize() function?
https://www.php.net/manual/en/function.serialize
I'd say, try to unserialize it ;-)
Quoting the manual :
In case the passed string is not
unserializeable, FALSE is returned and
E_NOTICE is issued.
So, you have to check if the return value is false or not (with === or !==, to be sure not to have any problem with 0 or null or anything that equals to false, I'd say).
Just beware the notice : you might want/need to use the # operator.
For instance :
$str = 'hjkl';
$data = #unserialize($str);
if ($data !== false) {
echo "ok";
} else {
echo "not ok";
}
Will get you :
not ok
EDIT : Oh, and like #Peter said (thanks to him!), you might run into trouble if you are trying to unserialize the representation of a boolean false :-(
So, checking that your serialized string is not equal to "b:0;" might be helpful too ; something like this should do the trick, I suppose :
$data = #unserialize($str);
if ($str === 'b:0;' || $data !== false) {
echo "ok";
} else {
echo "not ok";
}
testing that special case before trying to unserialize would be an optimization -- but probably not that usefull, if you don't often have a false serialized value.
From WordPress core functions:
<?php
function is_serialized( $data, $strict = true ) {
// If it isn't a string, it isn't serialized.
if ( ! is_string( $data ) ) {
return false;
}
$data = trim( $data );
if ( 'N;' === $data ) {
return true;
}
if ( strlen( $data ) < 4 ) {
return false;
}
if ( ':' !== $data[1] ) {
return false;
}
if ( $strict ) {
$lastc = substr( $data, -1 );
if ( ';' !== $lastc && '}' !== $lastc ) {
return false;
}
} else {
$semicolon = strpos( $data, ';' );
$brace = strpos( $data, '}' );
// Either ; or } must exist.
if ( false === $semicolon && false === $brace ) {
return false;
}
// But neither must be in the first X characters.
if ( false !== $semicolon && $semicolon < 3 ) {
return false;
}
if ( false !== $brace && $brace < 4 ) {
return false;
}
}
$token = $data[0];
switch ( $token ) {
case 's':
if ( $strict ) {
if ( '"' !== substr( $data, -2, 1 ) ) {
return false;
}
} elseif ( false === strpos( $data, '"' ) ) {
return false;
}
// Or else fall through.
case 'a':
case 'O':
return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
case 'b':
case 'i':
case 'd':
$end = $strict ? '$' : '';
return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data );
}
return false;
}
Optimizing Pascal MARTIN's response
/**
* Check if a string is serialized
* #param string $string
*/
public static function is_serial($string) {
return (#unserialize($string) !== false);
}
If the $string is a serialized false value, ie $string = 'b:0;'
SoN9ne's function returns false, it's wrong
so the function would be
/**
* Check if a string is serialized
*
* #param string $string
*
* #return bool
*/
function is_serialized_string($string)
{
return ($string == 'b:0;' || #unserialize($string) !== false);
}
Despite Pascal MARTIN's excellent answer, I was curious if you could approach this another way, so I did this just as a mental exercise
<?php
ini_set( 'display_errors', 1 );
ini_set( 'track_errors', 1 );
error_reporting( E_ALL );
$valueToUnserialize = serialize( false );
//$valueToUnserialize = "a"; # uncomment this for another test
$unserialized = #unserialize( $valueToUnserialize );
if ( FALSE === $unserialized && isset( $php_errormsg ) && strpos( $php_errormsg, 'unserialize' ) !== FALSE )
{
echo 'Value could not be unserialized<br>';
echo $valueToUnserialize;
} else {
echo 'Value was unserialized!<br>';
var_dump( $unserialized );
}
And it actually works. The only caveat is that it will likely break if you have a registered error handler because of how $php_errormsg works.
$data = #unserialize($str);
if($data !== false || $str === 'b:0;')
echo 'ok';
else
echo "not ok";
Correctly handles the case of serialize(false). :)
build in to a function
function isSerialized($value)
{
return preg_match('^([adObis]:|N;)^', $value);
}
There is WordPress solution: (detail is here)
function is_serialized($data, $strict = true)
{
// if it isn't a string, it isn't serialized.
if (!is_string($data)) {
return false;
}
$data = trim($data);
if ('N;' == $data) {
return true;
}
if (strlen($data) < 4) {
return false;
}
if (':' !== $data[1]) {
return false;
}
if ($strict) {
$lastc = substr($data, -1);
if (';' !== $lastc && '}' !== $lastc) {
return false;
}
} else {
$semicolon = strpos($data, ';');
$brace = strpos($data, '}');
// Either ; or } must exist.
if (false === $semicolon && false === $brace)
return false;
// But neither must be in the first X characters.
if (false !== $semicolon && $semicolon < 3)
return false;
if (false !== $brace && $brace < 4)
return false;
}
$token = $data[0];
switch ($token) {
case 's' :
if ($strict) {
if ('"' !== substr($data, -2, 1)) {
return false;
}
} elseif (false === strpos($data, '"')) {
return false;
}
// or else fall through
case 'a' :
case 'O' :
return (bool)preg_match("/^{$token}:[0-9]+:/s", $data);
case 'b' :
case 'i' :
case 'd' :
$end = $strict ? '$' : '';
return (bool)preg_match("/^{$token}:[0-9.E-]+;$end/", $data);
}
return false;
}
/**
* some people will look down on this little puppy
*/
function isSerialized($s){
if(
stristr($s, '{' ) != false &&
stristr($s, '}' ) != false &&
stristr($s, ';' ) != false &&
stristr($s, ':' ) != false
){
return true;
}else{
return false;
}
}
This works fine for me
<?php
function is_serialized($data){
return (is_string($data) && preg_match("#^((N;)|((a|O|s):[0-9]+:.*[;}])|((b|i|d):[0-9.E-]+;))$#um", $data));
}
?>
I would just try to unserialize it. This is how i would solve it
public static function is_serialized($string)
{
try {
unserialize($string);
} catch (\Exception $e) {
return false;
}
return true;
}
Or more like a helper function
function is_serialized($string) {
try {
unserialize($string);
} catch (\Exception $e) {
return false;
}
return true;
}
The mentionned WordPress function does not really detect arrays (a:1:{42} is considered to be serialized) and falsely returns true on escaped strings like a:1:{s:3:\"foo\";s:3:\"bar\";} (although unserialize does not work)
If you use the #unserialize way on the other side WordPress for example adds an ugly margin at the top of the backend when using define('WP_DEBUG', true);
A working solution that solves both problems and circumvents the stfu-operator is:
function __is_serialized($var)
{
if (!is_string($var) || $var == '') {
return false;
}
set_error_handler(function ($errno, $errstr) {});
$unserialized = unserialize($var);
restore_error_handler();
if ($var !== 'b:0;' && $unserialized === false) {
return false;
}
return true;
}
see the wordpress function is_serialized
function is_serialized( $data, $strict = true ) {
// If it isn't a string, it isn't serialized.
if ( ! is_string( $data ) ) {
return false;
}
$data = trim( $data );
if ( 'N;' === $data ) {
return true;
}
if ( strlen( $data ) < 4 ) {
return false;
}
if ( ':' !== $data[1] ) {
return false;
}
if ( $strict ) {
$lastc = substr( $data, -1 );
if ( ';' !== $lastc && '}' !== $lastc ) {
return false;
}
} else {
$semicolon = strpos( $data, ';' );
$brace = strpos( $data, '}' );
// Either ; or } must exist.
if ( false === $semicolon && false === $brace ) {
return false;
}
// But neither must be in the first X characters.
if ( false !== $semicolon && $semicolon < 3 ) {
return false;
}
if ( false !== $brace && $brace < 4 ) {
return false;
}
}
$token = $data[0];
switch ( $token ) {
case 's':
if ( $strict ) {
if ( '"' !== substr( $data, -2, 1 ) ) {
return false;
}
} elseif ( false === strpos( $data, '"' ) ) {
return false;
}
// Or else fall through.
case 'a':
case 'O':
return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
case 'b':
case 'i':
case 'd':
$end = $strict ? '$' : '';
return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data );
}
return false;
}