Encode and store multiple variables in URL - php

I know this is possible and I researched it in many websites, but didn't find anything that could do exactly what I need.
I need to encode and store two parameters in URL and then retrieve it with $_GET method.
The parameters are not sensitive data. My purpose is mainly to obfuscate it, so the visitors can't read it without website accessing.
I have something like this:
site.com/?name=john&food=banana%20split
and I need it to become something like this:
site.com/g57HT90dw8lC5p
How can I do this? Thanks.
(Sorry for my bad english)
EDIT: I should explain it a bit more.
I know I'll have to use mod_rewrite and I got that part covered;
The second parameter is a complete sentence (with spaces, punctuation, etc.);
I need this to create a Christmas Card, so none of these parameters require secure methods. What I really need to store is just a name and a simple message.

This is wrong approach - you said it is not sensitive so you better fix your code it will not be hacked if someone send you crafted data. Obfuscating prevents average users from doing changes but noone skilled be fooled by this. Also many browsers GET is limited (so can be configured PHP and server) so this may hit the wall sooner than you want. But if you insist you want this approach, you can put all variables into json_array, and then encode using base64.
$myData = array('foo'=>1, 'bar'=>'hax0r');
$arg = base64_encode( json_encode($myData) );
http://site.com/secret=$arg
and back:
$myData = json_decode( base64_decode( $_GET['secret'] ) );
But again - this is wrong by design.

Append the two string values together; then use some encoding function like str_rot13 or whatever

You could just uuencode it.
On create
$converted = convert_uuencode('?name=john&food=banana');
// 6/VYA;64]:F]H;B9F;V]D/6)A;F%N80``
And on decoding
$query = $_SERVER['QUERY_STRING'];
// 6/VYA;64]:F]H;B9F;V]D/6)A;F%N80``
$real = convert_uudecode($query);
// ?name=john&food=banana
The point of uuencoding is to make data safe for network transmissions. It does not provide protection, but it will make them something else than clear text.

Try these PHP functions convert_uuencode and convert_uudecode
It is much safer than using only base64
function encrypt_decrypt ($data, $encrypt) {
if ($encrypt == true) {
$output = base64_encode (convert_uuencode ($data));
} else {
$output = convert_uudecode (base64_decode ($data));
}
return $output;
}
$enc_txt = encrypt_decrypt ("name=john&food=banana%20split", true);
echo $enc_txt."\n";
// PTtGJU05M1VKO1ZBTilGOU87VjBdOEYlTjg2WUEpMyhQPFchTDo3MGAKYAo=
echo encrypt_decrypt ($enc_txt, false);
// name=john&food=banana%20split

Look at PHPs Doc Base64Encode . just encode the string, and decode it when reading the query.

Related

eval() and base64_decode() again

As always, the bottom line of any discussion about using eval() is: it is better to avoid using it as much as possible wherever there's another approach because it is tricky and dangerous; this why I've never had interests reading about it, well until now..
I tried to encode a simple function through some website which uses eval(base64_decode()), it obfuscated this function:
<?php
echo 'Hello There!<hr />';
for( $i = 1; $i <= 10; $i++ ) {
echo( '5x'.$i.'='.(string)($i*5)."\n" . '<br />' );
}
?>
When I tested the encoded output on my local machine it worked exactly like it should, However I tried to decode it using two other websites ( ddecode , tools4noobs ) the result was a whole different thing, same thing if i replace eval() with print() >>
if(!function_exists("YiunIUY76bBhuhNYIO8")){
function YiunIUY76bBhuhNYIO8($g,$b=0){
$a=implode("\n",$g);$d=array(655,236,40);
if($b==0) $f=substr($a,$d[0],$d[1]);
elseif($b==1)$f=substr($a,$d[0]+$d[1],$d[2]);
else $f=trim(substr($a,$d[0]+$d[1]+$d[2]));
return($f);
}
}
What's going on here! did the decoding fail or the encoded data is something different than the one I entered in the first website - malicious code for example although it looks like the output represents some encoding mechanism, But if I am wrong how come it worked like it should, and if am right then such thing cannot be decoded?
Also, is it safe to use eval() in this way? considering I got the encoded string from a strange website. Or it is better to implement it by myself? even though the base64_encode() encodes same function into a different output which is if decoded it returns the same function.
Many thanks in advance.

What is this encoding, and how do I decode it?

I recently obtained a Wordpress theme and cannot figure out what all of this encoding is that contains a massive number of underscores. I have figured out WHAT it does, but I have't figured out how to decode it quicker than one-by-one. Can you
1) tell me what the encoding is? AND
2) how to decode it, quicker?
function aj_________e() {
global $_GET, $wt___q;
$dw________e = rk_______g();
$xt____________m = pc__p();
$zq_______o = iw__________h();
$ci______m = "full";
if ($_GET["wp_cache_cl"] == "197ab5deb39daad8baacae1bdd5a8852") {
if ($zq_______o == "file") {
$rd_________v = $dw________e["dir_upload"]["path"]."/".$xt____________m.".jpg";
if ($wt___q($rd_________v)) {
#unlink($rd_________v);
$ci______m = "deleted";
}
}
$uk___s = array(
"s" => $ci______m,
"t" => time(),
"v" => WP_ID
);
echo "<!--";
foreach ($uk___s AS $ce_____________t => $ik__________m) echo " [$ce_____________t:$ik__________m]";
echo " -->";
}
}
Wordpress is obfucated. You can't read them so easy. About this : http://en.wikipedia.org/wiki/Obfuscation
I think the original author ran this code through some kind of an obfuscator. Perhaps contact them for a clean version?
This code periodically replaces some file contents with updated advertising controlled by the theme supplier. Obfuscated code generally gets its pound of flesh by advertising, including advertising you don't want. (Okay, this code doesn't do that part of the thing - but you have only presented a snippet of the code here.)
The bit you missed out is stuff like this, which assigns the value base64_decode to a variable conveniently named $csGIYFfb. Once you know the values all of the strings, you can read the code:
$HnSjwuR='e';
$JBzO='s';
$CiCHjis='6';
$APNhIK='d';
$TWmEOd='d';
$jygti='_';
$PuGIIg='4';
$nyyif='e';
$mgtv='o';
$AJAsO='a';
$LRRqTj='e';
$KCHbUS='b';
$DjstEZ='c';
$csGIYFfb=$KCHbUS.$AJAsO.$JBzO.$LRRqTj.$CiCHjis.$PuGIIg.$jygti.$TWmEOd.$HnSjwuR.$DjstEZ.$mgtv.$APNhIK.$nyyif;
Just to be clear here, the code you have supplied is hardly obfuscated -- it is merely uglified, with possibly meaningful variable and function names replaced by random strings containing large swathes of underscores. The part of the code you did not present defines the meaning of these functions, which happen to use curl to fill your system with possibly unwanted advertising.

string delimiter ajax call

So a PHP file returns a string ( to an ajax call ) like this :
$output = $sessID."###".$sessEmail."###".$sessFirstName."###".$sessLanguage."###".$sessRememberMe;
and in javascript i do :
if (reply.indexOf("###") >= 0) {
arrayReply = reply.split("###");
user.ID = arrayReply[0];
user.Email = arrayReply[1];
user.FirstName = arrayReply[2];
user.Language = arrayReply[3];
user.RememberMe = arrayReply[4];
}
a problem can arise when parts of reply contain the the delimiter i use "###". What can I do in such a situation? Making the delimiter more complex/rare is not a solution in my opinion.
PS: I did try JSON but it's WAY SLOWER server side.
FINAL EDIT:
server side JSON is slower, and the same for client side, however it's not going to be a bottleneck ( 430ms for 100.000 calls ) and plus there is no need as Jules said below to re-invent the wheel. There was one more solution: bin2hex() in php [which reduced the time from 430ms to 240] and then get back the string in javascript with a hex2string function, however not worth the effort. JSON it is. Thank you all!
If as you say encoding as JSON is slower than you could try the following,
$output = '"' . some_kind_of_escape_function($sessID).'","'.some_kind_of_escape_function($sessEmail).'","'.some_kind_of_escape_function($sessFirstName).'","'.some_kind_of_escape_function($sessLanguage).'","'.$sessRememberMe.'"';
and of course replace some_kind_of_escape_function with the appropriate php function (e.g. addslashes or mysql_real_escape_string) it has been a while since I've done PHP development so choose the one that best suits your needs
Then it's a simple case of splitting by the comma and removing the quotes
One option is to use JSON object instead.
For PHP (using json_encode):
$output = json_encode(array(
"sessid" => $sessID,
"sessEmail" => $sessEmail,
"sessFirstName" => $sessFirstName,
"sessLanguage" => $sessLanguage,
"sessRememberMe" => $sessRememberMe
));
For JS (using jQuery method):
$.getJSON("/path/to/script.php", function(reply) {
user.ID = reply.sessid;
user.Email = reply.sessEmail;
user.FirstName = reply.sessFirstName;
user.Language = reply.sessLanguage;
user.RememberMe = reply.sessRememberMe;
});
Otherwise, you can use any other delimiter that possibly won't be found in the fields (or you can replace it throughout the fields). One of the examples is to use symbol of newline (\n).
Why develop your own format if there is already one?
use Json:
$output = json_encode(array('sessionID'=>$sessID,'sessionEmail'=>sessEmail,'sessionFirstName'=>$sessFirstName,'sessLanguage'=>$sessLanguage,'sessRememberMe'=>$sessRememberMe));
And for the Javsascript Side see
http://www.javascriptkit.com/dhtmltutors/ajaxgetpost4.shtml
or if your using JQuery etc. your Framework is much likely to have some kind of inbuild functionality such as http://api.jquery.com/jQuery.getJSON/
However if you want to use your ###-Delimiter i'd suggest you reduce it to just "#", for the sake of simplicity and space. After that introduce what is called an escape charater such as "\" So in a prepass you'll parse your input and replace all occurences of # with #, vice versa in the output. You can then Split your String using a special Regex, which only splits by # and not by "#"
You can use json.
http://php.net/manual/en/function.json-encode.php
How to JSON decode array elements in JavaScript?

using a base64 encoded string in url with codeigniter

I have an encrypted, base64 encoded array that I need to put into a url and insert into emails we send to clients to enable them to be identified (uniquely) - the problem is that base64_encode() often appends an = symbol or two after it's string of characters, which by default is disallowed by CI.
Here's an example:
http://example.com/cec/pay_invoice/VXpkUmJnMWxYRFZWTEZSd0RXZFRaMVZnQWowR2N3TTdEVzRDZGdCbkQycFFaZ0JpQmd4V09RRmdWbkVMYXdZbUJ6OEdZQVJ1QlNJTU9Bb3RWenNFSmxaaFVXcFZaMXQxQXpWV1BRQThVVEpUT0ZFZ0RRbGNabFV6VkNFTlpsTWxWV29DTmdackEzQU5Nd0lpQURNUGNGQS9BRFlHWTFacUFTWldOZ3M5QmpRSGJBWTlCREVGWkF4V0NtQlhiZ1IzVm1CUk9sVm5XMllEWlZaaEFHeFJZMU51VVdNTmJsdzNWVzlVT0EwZw==
Now I understand I can allow the = sign in config.php, but I don't fully understand the security implications in doing so (it must have been disabled for a reason right?)
Does anyone know why it might be a bad idea to allow the = symbol in URLs?
Thanks!
John.
Not sure why = is disallowed, but you could also leave off the equals signs.
$base_64 = base64_encode($data);
$url_param = rtrim($base_64, '=');
// and later:
$base_64 = $url_param . str_repeat('=', strlen($url_param) % 4);
$data = base64_decode($base_64);
The base64 spec only allows = signs at the end of the string, and they are used purely as padding, there is no chance of data loss.
Edit: It's possible that it doesn't allow this as a compatibility option. There's no reason that I can think of from a security perspective, but there's a possibility that it may mess with query string parsing somewhere in the tool chain.
Please add the character "=" to $config['permitted_uri_chars'] in your config.php file you can find that file at application/config folder
Originally there are no any harmful characters in the url at all. But there are not experienced developers or bad-written software that helps some characters to become evil.
As of = - I don't see any issues with using it in urls
Instead of updating config file you can use urlencode and urldecode function of native php.
$str=base64_encode('test');
$url_to_be_send=urlencode($str);
//send it via url
//now on reciveing side
//assuming value passed via get is stored in $encoded_str
$decoded_str=base64_decode(urldecode($encoded_str));

PHP HTML Entities

I want to display on screen data send by the user,
remembering it can contain dangerous code, it is the best to clean this data with html entities.
Is there a better way to do html entities, besides this:
$name = clean($name, 40);
$email = clean($email, 40);
$comment = clean($comment, 40);
and this:
$data = array("name", "email," "comment")
function confHtmlEnt($data)
{
return htmlentities($data, ENT_QUOTES, 'UTF-8');
}
$cleanPost = array_map('confHtmlEnt', $_POST);
if so, how, and how does my wannabe structure
for html entities look?
Thank you for not flaming the newb :-).
"Clean POST", the only problem is you might not know in what context will your data appear. I have a Chat server now that works via browser client and a desktop client and both need data in a different way. So make sure you save the data as "raw" as possible into the DB and then worry about filtering it on output.
Do not encode everything in $_POST/$_GET. HTML-escaping is an output-encoding issue, not an input-checking one.
Call htmlentities (or, usually better, htmlspecialchars) only at the point where you're taking some plain text and concatenating or echoing it into an HTML page. That applies whether the text you are using comes from a submitted parameter, or from the database, or somewhere else completely. Call mysql_real_escape_string only at the point you insert plain text into an SQL string literal.
It's tempting to shove all that escaping stuff in its own box at the top of the script and then forget about it. But text preparation really doesn't work like that, and if you pretend it does you'll find your database irreparably full of double-encoded crud, backslashes on your HTML page and security holes you didn't spot because you were taking data from a source other than the (encoded) parameters.
You can make the burden of remembering to mysql_real_escape_string go away by using mysqli's parameterised queries or another higher-level data access layer. You can make the burden of typing htmlspecialchars every time less bothersome by defining a shorter-named function for it, eg.:
<?php
function h($s) {
echo(htmlspecialchars($s, ENT_QUOTES));
}
?>
<h1> Blah blah </h1>
<p>
Blah blah <?php h($title); ?> blah.
</p>
or using a different templating engine that encodes HTML by default.
If you wish to convert the five special HTML characters to their equivalent entities, use the following method:
function filter_HTML($mixed)
{
return is_array($mixed)
? array_map('filter_HTML',$mixed)
: htmlspecialchars($mixed,ENT_QUOTES);
}
That would work for both UTF-8 or single-byte encoded string.
But if the string is UTF-8 encoded, make sure to filter out any invalid characters sequence, prior to using the filter_HTML() function:
function make_valid_UTF8($str)
{
return iconv('UTF-8','UTF-8//IGNORE',$str)
}
Also see: http://www.phpwact.org/php/i18n/charsets#character_sets_character_encoding_issues
You need to clean every element bevor displaying it. I do it usually with a function and an array like your secound example.
If you use a framework with a template engine, there is quite likely a possibility to auto-encode strings. Apart from that, what's simpler than calling a function and getting the entity-"encoded" string back?
Check out the filter libraries in php, in particular filter_input_array.
filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);

Categories