base64_encode() limitation in php - php

I am using the base64_encode for sending the numeric id to url, base64_encode($list_post['id']); up to 99 its working fine, but after 99 its produce wrong encoded string.
the last character in encoded string is = (equal sign), but when the number more than 99, for example 100 it don't show = (equal sign) at the end.

Take a look at how padding in base64 works: http://en.wikipedia.org/wiki/Base64#Padding
The padding (the "=" character) is not always needed and in some implementations is not even mandatory.
EDIT: ok from your comments I see that you are using the base64 encoded string in a URL like this:
http://example.com/path/OTC=
The base64 encoding includes chars that have a special meaning in URLs so you need to use a slightly modified function (https://stackoverflow.com/a/5835352/2737514):
function base64_url_encode($input) {
return strtr(base64_encode($input), '+/=', '-_,');
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_,', '+/='));
}
However, since your code works for some numbers, maybe there is a problem with the .htaccess not parsing the url correctly, or the PHP code that interpretes the URL. I can't help more than this without seeing some other code.

it seems working fine for me
Can you please test with following code
echo base64_encode(101);
echo base64_decode(base64_encode(101));
DEMO
Base64-encoded data takes about 33% more space than the original data.
So these numbers shouldnt be a problem

Related

php simple encode decode function using only (0-9 A-Z a-z)

I'm setting up a PHP email tracking system that uses url parameters to track link click throughs. Something like:
www.example.com?trackToken=10
I'm looking for a simple PHP encode / decode function I can put in place that will take a number (in this case 10) and convert in to strictly to number and letters. something like:
www.example.com?trackToken=7aj8nG93nDpw9M9Nk1
I have found several variations of encrypt / decrypt functions using mcrypt. However, the encrypted output always ends up containing strange characters. These strange characters make it hard for my email messages to be sent/delivered.
Does anyone know of a good encrypt function that only outputs numbers 0-9 and letters a-z or A-Z? Additionally, I'm looking for a decrypt function to complement the encrypt function so I can actually use it.
I'm not looking for something super secure here. Just a way to mask the actual tracking token so the user can't change it on their own.
Base64 should be fine in any modern system - and any system handling email in PHP fits the definition of "modern". There is absolutely no reason I can think of to limit to just alphanumerics. The only catch is that as a URL parameter you don't want to have a '+' or '/' in the string. There is base64url to solve this problem but that doesn't have a standard PHP function. You can easily replicate that by using base64_encode() and str_replace() and to decode str_replace followed by base64_decode():
$coded = str_replace('+','-',str_replace('/','_',base64_encode($original)));
$original = base64_decode(str_replace('_','/',str_replace('-','+',$coded)));

php convert foreign language chars to "string"

UPDATE: Please ignore this question, it appears that md5 is not
returning result because I pass the URL through filter_var($url,
FILTER_SANITIZE_URL) and looks like FILTER_SANITIZE URL doesn't work
for foreign characters.
I have a problem where I want to get a hash from URLs e.g
https://ko.wikipedia.org/wiki/추간판_탈출증
The URL is provided by user in a form with so I assume it's already UTF-8 since my website is UTF-8.
However the above cannot be used with md5() as it returns empty result. May I know what php function do I use to convert it to something like below where md5() can be used?
https://ko.wikipedia.org/wiki/%EC%B6%94%EA%B0%84%ED%8C%90_%ED%83%88%EC%B6%9C%EC%A6%9D
I tried iconv, htmlspecialchar, htmlentities and I cannot seems to be able to find the right function to convert the strings.
You can use directly md5 to Encode whole URL as Below :
echo md5('https://ko.wikipedia.org/wiki/추간판_탈출증');
Which gives output as :
26eb333445f4e154f8ecb76e7c2ac858
UPDATED :
As Per w3schools FILTER_SANITIZE_URL
The FILTER_SANITIZE_URL filter removes all illegal URL characters from
a string.
This filter allows all letters, digits and
$-_.+!*'(),{}|\^~[]`"><#%;/?:#&=
The function you are looking for is rawurlencode. However you will have to extract the part of the url you want to encode or the whole url will be encoded.
$encoded = rawurlencode('추간판_탈출증');
// value of $encoded is now '%EC%B6%94%EA%B0%84%ED%8C%90_%ED%83%88%EC%B6%9C%EC%A6%9D'
use urlencode(url) function for conversion
once check this url url encode functions are found here

How can I base64_encode and base64_decode string with html tags?

I have a problem with base64 decode
For example, I have this code:
else if($_POST['submit']==2){
$send = base64_encode($text_success);
wp_redirect( home_url('/sales-funnel/add-product?msg='.$send) ); exit;
}
I send encoded string to page, so that user can't simply read it from url.
$text_success contain html code, which is generated if $wpdb->query not contain errors:
`Darījums veiksmīgi pievienots!</br>Komentārs veiksmīgi pievienots!</br>Klients veiksmīgi pievienots!</br>Fāze ir pievienota! </br>`
In all online base64_decode it's works great, but my WordPress site return empty string when I'm trying to do:
if (isset($_GET['msg']) && !empty($_GET['msg'])){
$text = base64_decode($_GET['msg']);
echo $text;
}
But, $_GET['msg'] = RGFyxKtqdW1zIHZlaWtzbcSrZ2kgcGlldmllbm90cyE8L2JyPktvbWVudMSBcnMgdmVpa3NtxKtnaSBwaWV2aWVub3RzITwvYnI+S2xpZW50cyB2ZWlrc23Eq2dpIHBpZXZpZW5vdHMhPC9icj5GxIF6ZSBpciBwaWV2aWVub3RhISA8L2JyPg==
P.S. I tried to use it without html tags, all works great.
The problem is related to the fact that the base64 alphabet is not URL-safe. In this particular case, your base64-encoded string contains a +, which is interpreted as a space.
To solve this, you can either:
Use a URL-safe version of the base64 alphabet, i.e. replacing + with -, / with _, and trimming the trailing = paddding, as described in RFC4648. This answer includes a code sample for this approach.
URL-encode your content after base64 encoding, turning + into %2B, / into %2F, and = into %3D.
This should solve your problem, but it goes without saying that in an untrusted environment, giving users the ability to inject raw HTML into your site constitutes a serious security risk.

get values in url

I need to get values in the url as it is
ex:
http://www.example.com/index?url=1+LY2ePh1pjX4tjZ4+GS393Y2pjd16Cbq63T3tbfzMzd16CarA==
but vriable url give me value of "1 LY2ePh1pjX4tjZ4 GS393Y2pjd16Cbq63T3tbfzMzd16CarA=="
Even though i have expected "1+LY2ePh1pjX4tjZ4+GS393Y2pjd16Cbq63T3tbfzMzd16CarA=="
any one can help me for this or know the reason
You see, you need to encode certain characters if you need to send them in a URL. For further references, I suggest you should read this Page. It seems that the URL you are getting isn't being encoded properly. If the URL is coming from your site, then I would suggest you to encode it properly.
In PHP, there is a function called urlencode, which may help you with this task.
A short explanation
URLs can only be sent over internet using ASCII character set.If you want to send characters which is outside this set, you need to encode it.URL encoding replaces unsafe ASCII characters with % followed by two hexadecimal digits corresponding to the character values in the ISO-8859-1 character-set.
The client sending the request apparently isn't URL encoding the value correctly. You can re-encode it after it's being decoded like this:
urlencode($_GET["url"])
IT convert %2B to space
The parameter you sent is wrong, it should have been encoded like so..
<?php
echo '<a href="http://www.example.com/index?url=', urlencode('1+LY2ePh1pjX4tjZ4+GS393Y2pjd16Cbq63T3tbfzMzd16CarA=='), '">';
?>
i have added encoding correctly now,It convert == correctly, but + sign encode to %2B correctly but in decode process it convert to space
As it seems that you’re having a Base-64 value there: You can use the URL safe alphabet for Base-64 that uses - and _ instead of + and / respectively:
$base64 = "1+LY2ePh1pjX4tjZ4+GS393Y2pjd16Cbq63T3tbfzMzd16CarA==";
// plain Base-64 to URL safe Base-64
$base64_safe = strtr($base64, '+/', '-_');
// URL safe Base-64 to plain Base-64
$base64 = strtr($base64_safe, '-_', '+/');
And if you know the length of the data, you can also omit the = padding:
rtrim($base64, '=')

Passing base64 encoded strings in URL

Is it safe to pass raw base64 encoded strings via GET parameters?
There are additional base64 specs. (See the table here for specifics ). But essentially you need 65 chars to encode: 26 lowercase + 26 uppercase + 10 digits = 62.
You need two more ['+', '/'] and a padding char '='. But none of them are url friendly, so just use different chars for them and you're set. The standard ones from the chart above are ['-', '_'], but you could use other chars as long as you decoded them the same, and didn't need to share with others.
I'd recommend just writing your own helpers. Like these from the comments on the php manual page for base64_encode:
function base64_url_encode($input) {
return strtr(base64_encode($input), '+/=', '._-');
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '._-', '+/='));
}
No, you would need to url-encode it, since base64 strings can contain the "+", "=" and "/" characters which could alter the meaning of your data - look like a sub-folder.
Valid base64 characters are below.
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
#joeshmo Or instead of writing a helper function, you could just urlencode the base64 encoded string. This would do the exact same thing as your helper function, but without the need of two extra functions.
$str = 'Some String';
$encoded = urlencode( base64_encode( $str ) );
$decoded = base64_decode( urldecode( $encoded ) );
Introductory Note I'm inclined to post a few clarifications since some of the answers here were a little misleading (if not incorrect).
The answer is NO, you cannot simply pass a base64 encoded parameter within a URL query string since plus signs are converted to a SPACE inside the $_GET global array. In other words, if you sent test.php?myVar=stringwith+sign to
//test.php
print $_GET['myVar'];
the result would be:
stringwith sign
The easy way to solve this is to simply urlencode() your base64 string before adding it to the query string to escape the +, =, and / characters to %## codes.
For instance, urlencode("stringwith+sign") returns stringwith%2Bsign
When you process the action, PHP takes care of decoding the query string automatically when it populates the $_GET global.
For example, if I sent test.php?myVar=stringwith%2Bsign to
//test.php
print $_GET['myVar'];
the result would is:
stringwith+sign
You do not want to urldecode() the returned $_GET string as +'s will be converted to spaces.
In other words if I sent the same test.php?myVar=stringwith%2Bsign to
//test.php
$string = urldecode($_GET['myVar']);
print $string;
the result is an unexpected:
stringwith sign
It would be safe to rawurldecode() the input, however, it would be redundant and therefore unnecessary.
Yes and no.
The basic charset of base64 may in some cases collide with traditional conventions used in URLs. But many of base64 implementations allow you to change the charset to match URLs better or even come with one (like Python's urlsafe_b64encode()).
Another issue you may be facing is the limit of URL length or rather — lack of such limit. Because standards do not specify any maximum length, browsers, servers, libraries and other software working with HTTP protocol may define its' own limits.
Its a base64url encode you can try out, its just extension of joeshmo's code above.
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
I don't think that this is safe because e.g. the "=" character is used in raw base 64 and is also used in differentiating the parameters from the values in an HTTP GET.
If you have sodium extension installed and need to encode binary data, you can use sodium_bin2base64 function which allows you to select url safe variant.
for example encoding can be done like that:
$string = sodium_bin2base64($binData, SODIUM_BASE64_VARIANT_URLSAFE);
and decoding:
$result = sodium_base642bin($base64String, SODIUM_BASE64_VARIANT_URLSAFE);
For more info about usage, check out php docs:
https://www.php.net/manual/en/function.sodium-bin2base64.php
https://www.php.net/manual/en/function.sodium-base642bin.php
In theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.
In practice, things can get a bit trickier. For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".
For url safe encode, like base64.urlsafe_b64encode(...) in Python the code below, works to me for 100%
function base64UrlSafeEncode(string $input)
{
return str_replace(['+', '/'], ['-', '_'], base64_encode($input));
}

Categories