Delphi/Cpp Equivalent to RawURLEncode in PHP - php

I was looking for a equivalent function to PHP RawURLEncode (and Decode) in cpp builder (or delphi).
I use the following string to test: _%_&_+_=_ _"_'_a_b_c_d_e_f_g_h_ (I wish to encode only var values, not a entire URL)
The rawurlencode returns: _%25_%26_%2B_%3D_%20_%22_%27_a_b_c_d_e_f_g_h_
I have tried without success:
TIdURI::ParamsEncode: _%25_&_+_=_%20_%22_'_a_b_c_d_e_f_g_h_
TIdURI::PathEncode: _%25_&_%2B_=_%20_%22_'_a_b_c_d_e_f_g_h_
TIdURI::URLEncode: Error: No Protocol (Needs full path)
HTTPApp::HTMLEncode: _%_& amp;_+_=_ _& quot;_'_a_b_c_d_e_f_g_h_ (space added after "&")
Wininet::WinHTTPEncode: Function not found in unit
IdGlobal::URLEncode: Function not found in unit
SynaCode::URLEncode: Unit not found in XE2

PHP's RawURLEncode is an implementation of RFC 3986. My websearch for that yields this Delphi unit which claims to implement RFC 3986.
I tested it on your input:
{$APPTYPE CONSOLE}
uses
System.SysUtils,
UURIEncode in 'UURIEncode.pas';
begin
Writeln(URIEncode('_%_&_+_=_ _"_''_a_b_c_d_e_f_g_h_'));
Readln;
end.
The output was:
_%25_%26_%2B_%3D_%20_%22_%27_a_b_c_d_e_f_g_h_
The key to my successful websearch was found in the PHP documentation for RawURLEncode where is states:
URL-encode according to RFC 3986

Related

Is FL_ENC_RAW a valid flag for ZipArchive::addFromString?

I have a "string" variable that contains binary jpeg data. I want to add this jpeg to a zip file. According to the documentation the $flags parameter is a
Bitmask consisting of ZipArchive::FL_OVERWRITE, ZipArchive::FL_ENC_GUESS, ZipArchive::FL_ENC_UTF_8, ZipArchive::FL_ENC_CP437.
ZipArchive::FL_ENC_GUESS would probably work, but it sounds like that is going to try to heuristically guess encoding based on the contents of my variable. If I want to be explicit, should I set $flags to ZipArchive::FL_ENC_UTF_8 or ZipArchive::FL_ENC_CP437? Between the 2, ZipArchive::FL_ENC_UTF_8 seems like the better choice.
ZipArchive::FL_ENC_RAW seems like what I should really be using, but according to the docs this is not a valid flag for this particular function. Is this an omission? As best I can tell it's not listed as a valid flag for any function.
ZipArchive::addFromString is calling zip_file_add under the hood. If we take a look at the documentation for that function in libzip we find more descriptive explanations for what each of the flags is doing:
ZIP_FL_ENC_UTF_8: Interpret name as UTF-8.
ZIP_FL_ENC_CP437: Interpret name as code page 437 (CP-437).
ZipArchive::FL_ENC_UTF_8 and ZipArchive::FL_ENC_CP437 affect how the filename (aka the $name parameter) is interpreted, not the data inside the file itself. The contents of the file are processed the same regardless of if the data is UTF-8, CP-437, binary data, or anything else.
This is confirmed in the php tests for this library where these 4 lines
$zip->addEmptyDir(chr(0x82), ZipArchive::FL_ENC_CP437);
$zip->addEmptyDir('è', ZipArchive::FL_ENC_UTF_8);
$zip->addFromString(chr(0x91), __FILE__, ZipArchive::FL_ENC_CP437);
$zip->addFromString('€', __FILE__, ZipArchive::FL_ENC_UTF_8);
are expected to produce files with the following names
é (corresponding to page 437 character hex:82 dec:130)
è
æ (corresponding to page 437 character hex:91 dec:145)
€

htmlspecialchars only works in some environments

i'm testing the exact same functionality in two different environments, one is a local development environment, and the other is a staging server. they have the exact same code.
when I do a curl request to each endpoint containing the functionality, I get two different results:
Local (php 5.4)
//this was the desired output
<p><span>Awesome water shooting power</span></p>
Staging (php 5.3)
//none of the html chars are changed.
<p><span>Awesome water shooting power</span></p>
the actual string of text is being run through htmlspecialchars in the following way:
htmlspecialchars( $req->get('description') )
Should I be specifically using all of the other arguments in this htmlspecialchars method in order to make it behave the same way in any environment? or is there something at the php.ini level that could be happening?
in the php documentation for htmlspecialchars:
Encoding: Defines encoding used in conversion. If omitted, the default value for this argument is ISO-8859-1 in versions of PHP prior
to 5.4.0, and UTF-8 from PHP 5.4.0 onwards.
so, based on that, I tried setting the fields explicitly, so they would not default to different things silently.
htmlspecialchars( $string , ENT_COMPAT, 'UTF-8' );
now the output is the same between the two different environments.

objective-c to PHP websafe encoding; uuencode?

I am sending strings from my objective-c app to a PHP script over HTTP. I need to websafe these strings.
I am currently encoding with Google Toolbox for Mac GTMStringEncoding rfc4648Base64WebsafeStringEncoding and decoding with base64_decode() on the PHP end. Works great 99% of the time.
Unfortunately, this encoding is not entirely websafe as it includes some web-interpreted characters ("/" and "-"). The regular GTMStringEncoding rfc4648Base64StringEncoding also includes web-interpreted characters.
Is uuencoding the data the way to go? I see that PHP already has uudecode support, will I have top roll my own on the objective-c side?
If not uuencode, then what?
OK, it seems that PHP did not default support Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet." This function allows PHP to handle the 4 out-lier chars before base64_decode:
function base64url_decode($base64url) {
$base64 = strtr($base64url, '-_', '+/');
$plainText = base64_decode($base64);
return ($plainText);
}
My thanks to the anonymous "Tom" who posted it on PHP.net 6 years ago.

Python unserialize PHP session

I have been trying to unserialize PHP session data in Python by using phpserialize and a serek's modules(got it from Unserialize PHP data in python), but it seems like impossible to me.
Both modules expect PHP session data to be like:
a:2:{s:3:"Usr";s:5:"AxL11";s:2:"Id";s:1:"2";}
But the data stored in the session file is:
Id|s:1:"2";Usr|s:5:"AxL11";
Any help would be very much appreciated.
The default algorithm used for PHP session serialization is not the one used by serialize, but another internal broken format called php, which
cannot store numeric index nor string index contains special characters (| and !) in $_SESSION.
The correct solution is to change the crippled default session serialization format to the one supported by Armin Ronacher's original phpserialize library, or even to serialize and deserialize as JSON, by changing the session.serialize_handler INI setting.
I decided to use the former for maximal compatibility on the PHP side by using
ini_set('session.serialize_handler', 'php_serialize')
which makes the new sessions compatible with standard phpserialize.
After reaching page 3 on Google, I found a fork of the original application phpserialize that worked with the string that I provided:
>>> loads('Id|s:1:"2";Usr|s:5:"AxL11";')
{'Id': '2', 'Usr': 'AxL11'}
This is how I do it in a stupid way:
At first, convert Id|s:1:"2";Usr|s:5:"AxL11"; to a query string Id=2&Usr=AxL11& then use parse_qs:
import sys
import re
if sys.version_info >= (3, 0):
from urllib.parse import parse_qs, quote
else:
from urlparse import parse_qs
from urllib import quote
def parse_php_session(path):
with open(path, 'r') as sess:
return parse_qs(
re.sub(r'\|s:([0-9]+):"?(.*?)(?=[^;|]+\|s:[0-9]+:|$)',
lambda m : '=' + quote(m.group(2)[:int(m.group(1))]) + '&',
sess.read().rstrip().rstrip(';') + ';')
)
print(parse_php_session('/session-save-path/sess_0123456789abcdef'))
# {'Id': ['2'], 'Usr': ['AxL11']}
It used to work without replacing ; to & (both are allowed). But since Python 3.10 the default separator for parse_qs is &

Mime / Base 64 encoding

I need a way to encode a string to Mime/Base64 in Delphi 7 and PHP
These two encoders must be compatible :)
The Indy-Project provides base64 encoder/decoder classes. You can find the documentation here.
For PHP, you can use the PHP-internal functions base64_encode and base64_decode.
The unit EncdDecd has been included since Delphi 6; below are the Mime compatible base64 functions it contains.
This cached post from FlexVN (the original post is not always on-line) explains how to do the base64 thing between PHP and Delphi using the EncdDecd unit.
unit EncdDecd;
interface
uses Classes, SysUtils;
procedure EncodeStream(Input, Output: TStream);
procedure DecodeStream(Input, Output: TStream);
function EncodeString(const Input: string): string;
function DecodeString(const Input: string): string;
function DecodeBase64(const Input: AnsiString): TBytes;
function EncodeBase64(const Input: Pointer; Size: Integer): AnsiString;

Categories