Jump to content

Serialize/unserialize in AutoIt (PHP compatible)


Jefrey
 Share

Recommended Posts

Hey

I made this to convert data to PHP's serialize() function return format.

This is for those who, somewhy [?], can't use JSON, for example.

Just two simple functions: Serialize() and Unserialize(). Data may be all accepted types in PHP (array, float, int, string), except objects.

Examples (included in package):
 

#include 'serialize.au3'

Dim $otherArray[4] = ["hai", "halo", "apa", "kabar"]
Dim $aArray[7] = ['test', 'lol', 'cool', 'amazing', 123, $otherArray, 2.50]

$sSerialized = Serialize($aArray)
MsgBox(0, "", $sSerialized)

It will show:

a:7:{i:0;s:4:"test";i:1;s:3:"lol";i:2;s:4:"cool";i:3;s:7:"amazing";i:4;i:123;i:5;a:4:{i:0;s:3:"hai";i:1;s:4:"halo";i:2;s:3:"apa";i:3;s:5:"kabar";}i:6;d:2.5;}

Now, if we want to do the contrary, which is, converting from serialized string back to original data:

#include 'serialize.au3'

#include <Array.au3> ; Needed only to use _ArrayDisplay. Not required to use serialize.

$aUnserialized = Unserialize('a:7:{i:0;s:4:"test";i:1;s:3:"lol";i:2;s:4:"cool";i:3;s:7:"amazing";i:4;i:123;i:5;a:4:{i:0;s:3:"hai";i:1;s:4:"halo";i:2;s:3:"apa";i:3;s:5:"kabar";}i:6;d:2.5;}')

_ArrayDisplay($aUnserialized)
_ArrayDisplay($aUnserialized[6])

As _ArrayDisplay doesn't support multidimensional array (and, in the previous example, we converted a multidimensional array to serialized data), we must use it twice. So we will see:

2015_07_18_02h05_56.png

Please notice the differences between AutoIt and PHP's approach of arrays. It is different. Be careful, mainly when getting arrays from PHP and putting into AutoIt. I really recommend using only integer array keys, or switching to JSON.

License: CC BY 4.0

Download: https://www.autoitscript.com/forum/files/file/348-unserialize-in-autoit-php-compatible/ 

Edited by Jefrey

My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path GUICtrlStaticMarquee static text scrolling Random stuff Super Mario beep sound your ears will hurt

 

Link to comment
Share on other sites

This is awesome. I did something similar (just a little bit) last year, but at the time wasn't really aware of PHP. A couple of points to make about the UDF:

  • Don't use Dim, as it can have massive consequences with those who declare $ret as a Global variable
  • Be explicit with scope (see warnings from running Au3Check)
  • Provide the download using a non-proprietary compression format. I am cool with rar as I use 7-Zip) as not everybody will be able to "unrar"
  • If you're using the SciTE4utoIt3 package, place this (see below) at the top and see the "warnings" in the code. It's what we use for the official AutoIt UDFs
  • Look at using Switch...EndSwitch instead of If...ElseIf...ElseIf. It's what I would use in PHP
  • I have found a bug in your code with using { inside  a string
#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
; Search Au3Check in the help file to see what it all means

Bug:

#include <Array.au3> ; Needed only to use _ArrayDisplay. Not required to use
#include 'Serialize.au3'

Local $aOne = ["hai", "ARRAY", "apa", "kabar"]
Local $aArray = ['test', 'lol', '{cool', 'amazing', 123, $aOne, 2.50]

Local $sSerialized = Serialize($aArray)
LOcal $aUnserialized = Unserialize($sSerialized)

MsgBox($MB_SYSTEMMODAL, "", $sSerialized)
_ArrayDisplay($aUnserialized)
_ArrayDisplay($aUnserialized[6])

Settings INI - My approach with basic datatypes

One thing to ponder over

Local $bIsTrue = False

; There is no block scope in AutoIt
If $bIsTrue Then
    Local $sSomething = 'Something'
EndIf

; $sSomething is not declared as $bIsTrue didn't "fire"
ConsoleWrite($sSomething & @CRLF)

; Better way would be

Local $bIsTrue = False
Local $sSomething = ''
If $bIsTrue Then
    $sSomething = 'Something'
EndIf

; $sSomething is not declared as $bIsTrue didn't "fire"
ConsoleWrite($sSomething & @CRLF)

Thanks for posting

Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Thanks for the points, @guinness! I'm already on it and soon I'll be uploading a patch!

  • Don't use Dim, as it can have massive consequences with those who declare $ret as a Global variable OK
  • Be explicit with scope (see warnings from running Au3Check) OK
  • If you're using the SciTE4utoIt3 package, place this (see below) at the top and see the "warnings" in the code. It's what we use for the official AutoIt UDFs OK
  • Look at using Switch...EndSwitch instead of If...ElseIf...ElseIf. It's what I would use in PHP OK
  • I have found a bug in your code with using { inside  a string on it
  • Provide the download using a non-proprietary compression format. I am cool with rar as I use 7-Zip) as not everybody will be able to "unrar" soon

(Patch will be provided when all these items are done)

Edited by Jefrey

My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path GUICtrlStaticMarquee static text scrolling Random stuff Super Mario beep sound your ears will hurt

 

Link to comment
Share on other sites

@Jefrey, good work!

Every form of communication between different platforms is very welcome!

But using JSON would be easier? Like this? https://github.com/ez2sugul/stopwatch_client/blob/master/JSMN.au3

The notation is very similar how PHP write in sessions, is corretly?

Work with object, is easy: Scripting.Dictionary.

 

Edited by Luigi

Visit my repository

Link to comment
Share on other sites

@Jefrey, good work!

Every form of communication between different platforms is very welcome!

But using JSON would be easier? Like this? https://github.com/ez2sugul/stopwatch_client/blob/master/JSMN.au3

The notation is very similar how PHP write in sessions, is corretly?

Work with object, is easy: Scripting.Dictionary.

 

Hi, Luigi!

I really think JSON would be easier. I also have a JSON udf (which is also linked on the original post). But, well, everything is possible. If someone must interact with a MySQL database to change settings on some system which adopts serialize() as data storage format, so this UDF will be useful. At the moment I'm fixing the bug pointed by guiness.

I'll take a look on Scripting.Dictionary. Seems easy and useful. Thanks!

My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path GUICtrlStaticMarquee static text scrolling Random stuff Super Mario beep sound your ears will hurt

 

Link to comment
Share on other sites

An example of Scripting.Dictionary can be found in the Settings INI I mentioned above

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...