mitsuhiko / phpserialize Goto Github PK
View Code? Open in Web Editor NEWA PHP serializer implementation for Python
Home Page: http://pypi.python.org/pypi/phpserialize
License: Other
A PHP serializer implementation for Python
Home Page: http://pypi.python.org/pypi/phpserialize
License: Other
a port of the serialize and unserialize functions of php to python. This module implements the python serialization interface (eg: provides dumps, loads and similar functions).
text = a:2:{i:1;a:3:{s:4:"type";s:3:"php";s:3:"rel";s:2:"ge";s:7:"version";s:5:"4.0.5";}i:2;a:3:{s:4:"type";s:3:"pkg";s:3:"rel";s:3:"has";s:4:"name";s:4:"Date";}}\n
unserialize(text)`
The following deserialization works on python 2.7.x but not for Python 3.x (bytes-like-object is expected not str)
from io import BytesIO
text = '''a:2:{i:1;a:3:{s:4:"type";s:3:"php";s:3:"rel";s:2:"ge";s:7:"version";s:5:"4.0.5";}i:2;a:3:{s:4:"type";s:3:"pkg";s:3:"rel";s:3:"has";s:4:"name";s:4:"Date";}}\n'''
bytes_text = bytes(text, 'utf-8')
unserialize(bytes_text)
Am I missing something? Is there a better way of doing this for Python3?
The test test_dumps_dict
fails because the order of dictionary keys is arbitrary in Python, it's not guaranteed to be the same as the order in which one gives them at creation time. You would need to use OrderedDict
for that.
Also, the tests aren't included in the PyPI release tarball. It would be nice to have them included so one could download the release tarball and run the tests.
During packaging I also saw, that the required BSD LICENSE file is not in the source tarball on pypi.
Please add it! It's required for packaging in my case :)
fails with python2.5:
File "/usr/local/pythonenv/API/lib/python2.5/site-packages/phpserialize.py", line 359 s.write(b's:') ^ SyntaxError: invalid syntax
Ok let me say that the bot is actually great, and im not saying this to get your attention! It's really so good!
However I am facing an error that says a - bytes-like object is required, not 'str' on line return json.loads((response.content).replace(")]}'",""))[0][0][2].encode()
have any idea on how to fix this?
By the way if you ever need anything make sure to hmu on discord TOG6#6666!
Have a good day then ig?
`
Request Method: | GET |
---|---|
http://localhost:8000/ | |
2.2.2 | |
AttributeError | |
'str' object has no attribute 'read' | |
C:\xampp\htdocs\test\dbs\env\lib\site-packages\phpserialize.py in _unserialize, line 473 | |
C:\xampp\htdocs\test\dbs\env\Scripts\python.exe | |
3.7.3 | |
['C:\xampp\htdocs\test\dbs', 'C:\xampp\htdocs\test\dbs\env\Scripts\python37.zip', 'C:\xampp\htdocs\test\dbs\env\DLLs', 'C:\xampp\htdocs\test\dbs\env\lib', 'C:\xampp\htdocs\test\dbs\env\Scripts', 'c:\users\arjun soota\appdata\local\programs\python\python37-32\Lib', 'c:\users\arjun soota\appdata\local\programs\python\python37-32\DLLs', 'C:\xampp\htdocs\test\dbs\env', 'C:\xampp\htdocs\test\dbs\env\lib\site-packages'] | |
Thu, 20 Jun 2019 11:46:50 +0530 |
`
### CLIENTE
`import socket
import sys
cliente = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
host = "0.0.0.0"
port = 9999
frag =1024
addr = (host,port)
cliente.sendall('1234567')
print("conectado na porta:", port)
f=open('pato.jpg',"rb")
data = f.read(frag)
print("enviando arquivo...")
for i in data:
cliente.sendto(data,addr)
data = f.read(frag)
cliente.close()
f.close()
`
### SERVER
`import socket
import sys
import select
host="0.0.0.0"
port = 9999
server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
server.bind((host,port))
frag=1024
addr = (host,port)
while True:
msg = server.recv(1024)
if msg == '1234567':
server.sendall('ACK')
print("escutando na endereço:", addr[0], "na porta: ", addr[1])
f = open("recebido.jpg","wb")
data,addr = server.recvfrom(frag)
try:
while True:
f.write(data)
server.settimeout(3)
data,addr = server.recvfrom(frag)
except:
f.close()
server.close()
print ("Arquivo baixado")`
I'm trying to create a UDP socket, which has ACK and NACK, but is giving this error "a bytes-like object is required, not 'str'"
In a legacy system I've ran across some serialized php strings that included a resource (e.g.: database connection handle). The library failing with a ValueError ("unrecognized opcode" (r:96;)) was pretty unhelpful, since we were interested in the other serialized properties of the cart.
For the time being, I patched it in place to meet our needs (see below), but I wonder whether a more universally applicable solution could be added to the library. Some ideas:
@@ -507,7 +507,11 @@
if decode_strings:
name = name.decode(charset, errors)
return object_hook(name, dict(_load_array()))
- raise ValueError('unexpected opcode')
+ if type_ == b'r':
+ _expect(b':')
+ data = _read_until(b';')
+ return None # or int(data)?
+ raise ValueError('unexpected opcode - %s' % repr(type_))
return _unserialize()
I'm currently moving this package to Arch Linux' [community] repository as an optional dependency for another package.
During build I realized, that the pypi source tarball lacks the tests. Can you please include them, so they can be used?
Hi guys,
I'm running a little problem. I'm trying to build an experiment test but I stumble a lil problem.
practiceEndLookup = { "English" : practiceEndEng, "French" : codecs.decode(practiceEndFr,'utf-8')}
TypeError: decoding with 'utf-8' codec failed (TypeError: a bytes-like object is required, not 'str')
can someone assist me, how to fix this problem?
Trying to re-use some python 2 code in version 3 however hitting this snag (see attached code) any ideas?? Much appreciated!
--- connected to: 192.168.69.99
--- getting version information
Traceback (most recent call last):
File "/home/pi/Documents/prne/section6-CommunicatingWithNetworkDevices/show version-python3.py", line 83, in
device_version = get_version_info(session)
File "/home/pi/Documents/prne/section6-CommunicatingWithNetworkDevices/show version-python3.py", line 66, in get_version_info
version_output_parts = version_output_lines[1].split(',')
TypeError: a bytes-like object is required, not 'str'
I'm not sure if there are plans to support unserialization of PHP sessions, but I created a function that is pretty simple and works for my particular use case.
I have changes to make it work at:
https://github.com/msabramo/phpserialize/tree/python3.x
$ python -m pytest -x
===================================== test session starts ======================================
platform darwin -- Python 3.2.2 -- pytest-2.1.3
collected 10 items
tests/test_phpserialize.py ..........
================================== 10 passed in 0.21 seconds ===================================
Obviously, you don't want to pull these changes into master and break Python 2.x compatibility, which is why I didn't send a pull request (I didn't see a way to request that it be pulled into an upstream branch that doesn't exist yet...?).
Cheers,
Marc
seems that this library targets python2, and is long unmaintained
I'm implementing something similar for python3 at https://github.com/frankli0324/libphpserialize
I'm focusing mainly on serializing, but unserializing will be implemented at some point in the future
I was trying to unserialize below bytes:
b'a:1:{s:10:"Liberation";a:7:{s:4:"year";s:0:"";s:4:"make";s:0:"";s:5:"model";s:0:"";s:4:"body";s:0:"";s:12:"vehicleClass";s:0:"";s:6:"series";s:0:"";s:11:"all_details";O:8:"stdClass":4:{s:21:"Additional Error Text";s:86:"Invalid character(s): 9:E , 14:I , 15:O , 16:Z , 17:X;";s:10:"Error Code";s:7:"1,7,400";s:10:"Error Text";s:259:"1 - Check Digit (9th position) does not calculate properly; 7 - Manufacturer is not registered with NHTSA for sale or importation in the U.S. for use on U.S roads; Please contact the manufacturer directly for more information; 400 - Invalid Characters Present";s:13:"Suggested VIN";s:17:"2345678W!RTYU!!!!";}}}'
but I got this error
I'm using python 3.6 and then got this error:-
TypeError Traceback (most recent call last)
in ()
for name in names:
ace_pc, spw_pc, rpw_pc = get_avg_values(name)
in get_avg_values(name)
def get_avg_values(name):
data_url_final = get_values(name)
ace_total,service_against_total,service_against,service_won_total,service_total, data_table = get_sum_values(data_url_final)
ace, spw, rpw = cal_avg_values(ace_total,service_against_total,service_against,service_won_total,service_total)
print (name)
in get_values(name)
matchmx = r.text
matchmx = matchmx.encode('ascii','ignore')
matchmx_data = replace_all(matchmx=matchmx)
matchmx_data_final = eval(matchmx_data)
in replace_all(matchmx)
dictionary = {" ": "","\n":"",";": ""} #list of values to be removed
for i, j in dictionary.items():
matchmx = matchmx.replace(i, j)
matchmx_data = matchmx[matchmx.find("varmatchmx")+11:] # 11 = length of "varmatchmx="
return matchmx_data
TypeError: a bytes-like object is required, not 'str'
hi , how i solve the problem in line 4, i recieve an error (python):
`import subprocess
results = subprocess.check_output(["netsh", "wlan", "show", "network"])
results = results.replace("\r", "")
ls = results.split("\n")
ls = ls[4:]
ssids = [] #there we will store our ssids
x = 0
y = 0
while x < len(ls):
if x % 5 == 0:
ssids.append(ls[x])
x += 1
while y < len(ssids):
print (ssids[y])
y += 1
`
Hi,
Thanks for you library !
I am testing with simple examples, like this one
from StringIO import StringIO
stream = StringIO('a:2:{i:0;i:1;i:1;i:2;}')
print load(stream)
But it raises the following error:
ValueError: unexpected opcode
Any idea ?
Thank you very much!
Currently phpserialize throws ValueError('unexpected opcode')
in the case where it encounteres a reference in the serialized data of form r:<Index of variable to be referenced to>
. This limitation makes phpserialize able to only handle a subset of all PHP generated serialized data.
A nice way for folks to demo/test the module and useful for quickly inspecting a big
blob of data. Kind of like json.tool in the standard library.
Wanted to know if it's something that might be pull-worthy if I worked on it?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.