Jefrey

Serialize/unserialize in AutoIt (PHP compatible)

7 posts in this topic

#1 ·  Posted (edited)

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
1 person likes this

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 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 Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

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

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

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 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 Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

@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

Share this post


Link to post
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 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 Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites

I have a good practice in $SD, i you need, ask. I share.


Visit my repository

Share this post


Link to post
Share on other sites

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


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

Share this post


Link to post
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

  • Similar Content

    • zenocon
      By zenocon
      Hi, After scouring the forums for many hours, I'm trying to compile the most up to date / recent information on the options available for integrating with JavaScript / DOM -- as it relates to scraping + automation of web pages.
      It's my understanding there is IE.au3 script for automation of IE through a COM interface.  But I believe this only works with IE and won't work with Edge, correct?  Is there a COM interface that works with Edge, or any other options for integrating with Edge (other than IUIAuatomation?)
      I know there was also a FF.au3 UDF, but Mozilla abandoned the support for their mozrepl in favor of Web Extensions, and my understanding is that the FF.au3 UDF no longer works, is that correct?
      There was also a Chrome.au3 UDF, but my read on the forums indicate that this also broke many Chrome releases past.
      Which leaves IUIAutomation which I have been using to automate / scrape Windows apps, but when I am trying it on a website, it is not as useful.  For example, if I know the exact DOM id / class, I can get at it and do whatever I need to in JavaScript very simply.  With IUIAutomation, the DOM properties are not available, and most tags / elements in DOM have no useful defining characteristics to be able to get at them reliably (if they are targetable at all).  Some things might be able to be done with IUIAutomation, but I see it's value in targeting website automation / scraping as fairly limited.
      At this point, it seems like my best option is to use IE.au3, but that forces users on IE, which is probably a showstopper.
      Is there another way to bridge into the DOM?  I have written Web Extensions for Chrome and Firefox before.  They can communicate with external processes via AJAX or messaging.  I'm wondering if I can build what I need in a WebExtension and then trigger it from AutoIT Script, and gather up the results somewhere.
      I know there was the ISimpleDOM.au3 and some Microsoft Accessability scripts, but they seem to only be partially supported in browsers, and I didn't have a lot of luck getting those examples to run correctly.
    • Miliardsto
      By Miliardsto
      Hello. Im trying to make my scripts safe - unnable to decompile. I search for obfuscators and other security methods but the search has come to nothing.
      Then one guy gave that idea below. If I rightly understood this idea lets we talk about example program with this secutiy method.
      Program have two parts, first is only login gui and the second part is the main program Second part (main program) is uploaded on ftp server lets say that on http://xxx/autoit/main_program.au3 So we have the first gui with login, we put correctly login and pass and this is the moment when code from http://xxx/autoit/main_program.au3 will be downloaded and executed Finally main program will be appear This is the similiar way like new games are protected by cracking.
      I have few questions in this moment about this:
      Is something like that even possible to do with the autoit? First part of program (login gui) must have somewhere given that link to download the rest of code - http://xxx/autoit/main_program.au3 to make it execute. As we know this first part of program is easy able to hack and retrieve this web url http://xxx/autoit/main_program.au3 where located is main part of program. Is the way to encrypt or secure it? If only code will be stored in .php we know it cannot be previewed. So it could for example get code from .php file instead of .au3 I know that methods works in other languages (I dont know exactly how) thats becouse I only speculates, maybe something may looks different in these solution? Other way would be compiling second part of code on web server (there are available web autoit servers) maybe this way is possible? Tell me anything U know about this ideas and if its even possible to achieve.
      Thanks for ur any response, advice or thoughts
       

       
       
    • Shirdish_chakravarthi
      By Shirdish_chakravarthi
      in need the path/text present int above shown input box to be copied or retrieved into a variable .. how can i do that?
       
      Thanks
       
    • badcoder123
      By badcoder123
      Anyone know how to access the information circled in the photo?
       

    • AndreyS
      By AndreyS
      Dear developers and creators of the language, please explain to me why when pressing the combination Crtl + Shift + C from the 5th or the 10th time "sticks / sinks" Ctrl or Shift? And then you need to press Ctrl or Shift again to reset their triggering. I only need to use hot keys like in the example!
      The code is a small example. Its essence is that when a user in the editor selects any number and presses a combination, then it increases by 1. 
      Dim $x HotKeySet("+^c","Calc") While 1 Sleep(10000) WEnd Func Calc() Send("^c") Sleep(50) $x=ClipGet()+1 ClipPut($x) Send("^v") EndFunc I thought that in my program some kind of glitch was searching for a reason for a long time. And it turned out that apparently somehow the work of some functions used in the example is not compatible. 
      Tell me, please, what is the problem?