Search code examples
phpkohana

unserialize in php not return any value


I am unserializing below string but its not returning anything.

a:57:{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:10:"Abcdubai";s:5:";}


Solution

  • The data you're unserializing is wrong

    a:57{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:10:"Abcdubai";s:5:";}
    

    if you try to unserialize it with error reporting E_ALL you will see a notice

    $data = 'a:57{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:10:"Abcdubai";s:5:";}';
    
    var_dump($data);
    

    you will get

    Notice: unserialize(): Error
    

    because

    • a:57 is the array length and from the data you have it's clearly not 57.

    • s: points to the length of string s:10:"Abcdubai" the string Abcdubai is not 10 in length it's 8 so you need to change that to s:8:"Abcdubai"

    • Finally you have s:5:"; at the end for the same reason s:5 means a string with 5 characters in length and it's empty with a one double quote

      <?php
      // this the valid data
       $data = 'a:4:{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:8:"Abcdubai";}';
      
      $data = unserialize($data);
      
      // accessing the valid serialized data
      echo $data['THEME_NAME'];
      echo $data['PUBLIC_ADS_LIMIT'];
      echo $data['PUBLIC_EDIT_LIMIT'];
      echo $data['SITENAME']; 
      

    you can try this method to solve formatting issues

       function fixUnserializeFormatting($data){
           // fix string length (will fix s:)
           $data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $data);
           // remove empty matches with one double qoute
           $data = preg_replace('/s\:+[0-9]+\:";/i', '', $data);
    
           // trying to get the right array length
           $strings = substr_count($data,';') / 2;        
           // fixing array length
           $data = preg_replace('/^a:+[0-9]+:/i', "a:{$strings}:", $data);
    
           // finally returning the formatted data
           return $data;    
       }
    

    Usage

       $data = 'a:57:{s:10:"THEME_NAME";s:5:"green";s:16:"PUBLIC_ADS_LIMIT";s:1:"5";s:17:"PUBLIC_EDIT_LIMIT";s:1:"5";s:8:"SITENAME";s:10:"Abcdubai";s:5:";}';
    
       $data = fixUnserializeFormatting($data);
    
       var_dump(unserialize($data));