I'm not much of a PHP expert. I'm encoding a URL with base64_encode.
I get quite a long encoded string with a lot of weird characters exactly as I want it to be.
Is there a way to trim this long line of characters to let's say 10 or 15 chars, so I can decode it later again?
I know there is trim() but that does not exactly what I want. I want a long encoded string to be rather short and later I want to decode it again.
Any ideas?
It's not possible to "shorten" any string without losing some data.
If you want to physically shorten an encoded string (with the end result being only part of that string), apply substr() but not on the encoded version: You need to decode it first, then re-encode the shortened version.
Another option is to compress a string. This may shorten it somewhat: Look into gzcompress(). Your mileage may vary, though: the compression rate will depend on what kind of data you have. With small input strings, the result can even be larger than the original.
If you want to reuse a variable in a multi-page process, and don't want to transport it through a link or a form, consider generating a short random key, and storing the data in the user's session:
$_SESSION[$randomKey] = "lllloooooooooooong data here";
You could pass on the random key, and always access the "long" data using $_SESSION[$randomKey]. You need to have a session initialized for this.
Related
I'm currently working with data I'd like to temporarily store in my database as encrypted data. I'm not worried about the database getting hacked into, I just want to ensure the people that had entered the data that it is not reachable by any other than themselves. (and me of course)
The data is not meant to be stored permanently in the database since I'm exporting it to a third party application using their API, but since they have a rate limit I need to store the data in our database until the limit is over and I can upload it. (Assuming the rate limit occurs)
The process:
The request I receive from the form is in an array, so to begin with I serialize() the array to get a long string which I will unserialize() later.
Then I want to use a method that lets me convert the string into numbers and back again without losing information.
The reason I want to turn the data into numbers is because I use the HashIds library, which only encodes numbers. To my knowledge it's an extra layer of security I'm happy to add.
Read more on HashIds here: http://hashids.org/
What I have tried:
I tried converting the string into hex numbers, and then the hex numbers into decimals. Unfortunately the number was too large, and i haven't had any luck using biginteger with it.
base64_encode() which is not going to turn the data into numbers, but then base_converting them is. But I couldn't figure out the base converting in php since apparently it's rather odd.
Conclusion:
How can I convert the data I'm receiving from a form request into a short encoded string which can be converted back into the data without too much hassle? I don't quite know all the options PHP offers yet.
UPDATE:
To conclude this thread, I ended up using OpenSSL to encrypt my serialized array. Only problem I ran into was if the request contained a file I wouldn't be able to serialize it and save the object to the database. I do still need a way around this, since the third party application expects the file to be a multipart/formdata object i can't just save the filepath to the database and upload that. But I guess I will have to figure out that one later.
That link http://hashids.org/ provides a pretty clear example. Lets assume that your integer is 15.
$hashids = new Hashids\Hashids('some random string for a salt. Make sure you use the same salt if you want to be able to decode');
$encoded = $hashids->encode(15);
print_r(['hashedId' => $encoded]);
$decoded = $hashids->decode($hashed);
print_r(['decoded' => $decoded]);
So the value of $decoded should equal 15
Update
Sorry - the hashids bit of your question threw me and as such, I misunderstood what you were asking. I will update my answer:
You should really be using https://secure.php.net/openssl_encrypt and https://secure.php.net/manual/en/function.openssl-decrypt.php
This question already has answers here:
What is base 64 encoding used for?
(19 answers)
Closed 8 years ago.
Hi my question is that does base64_encode does unique data every time we run the script?
Below is the code.
<?php
$id = 1;
echo base64_encode($id);
?>
If it does not provide the unique data every time then what is the point in encoding the string and passing in url. Does that make url safe??
Base64 encoding is not a method of encryption. It is used for encoding binary data into text, which makes it safer to transmit over the internet.
If you stream bits, some protocols may interpret it differently. Streaming text is much more reliable.
What is base 64 encoding used for?
If you need true encryption, you need to use something which hashes based on a salt you can hide from other users, such as the mcrypt library.
http://php.net/manual/en/book.mcrypt.php
base64-encoding does not provide unique data. Its purpose is to provide a compact representation of binary data in string form. In your example, you are encoding non-binary data, so it is not very practical. However, if you wanted to encode a string containing a newline and punctuation and pass it via the URL, you cannot send the binary data directly.
For example, if you had the string Hello, World!!\n there would be three punctuation marks, a space and a newline that all need to be URL-encoded. Doing that gives the result:
Hello%2C+World%21%21%0A
Which is 23 bytes long.
On the other hand if you were to base64-encode the same string, the result would be:
SGVsbG8sIFdvcmxkISEK
Which is 20 characters, or about 13% shorter. This adds up quickly if you've got a lot of non-alphanumeric characters or a large amount of data.
So the primary advantage of base64 encoding is its slightly more compact representation of certain data.
Base64 encoding is a way of representing data using only a limited set of characters. You use it when you need to store data in something such as a cookie that can't handle the data in its original format.
I let users write and then post what they have written to my MYSQL database, using PHP. I have been sending the strings as URLs and then $_GET['string'] in the php and then putting them in the database. I always have to take care of the spaces in the string by replacing them with %20. And then I had to replace all kinds of different characters on top of that in order for the URLs to work. This is a losing battle and the users expect their strings to be saved but if they contain a character I have not thought of, this will not be the case. I have even tried sending along the strings as NSData in a POST but that did not seem to save the strings either.
How can I be sure the users' strings will save, no matter what crazy characters they type?
Thanks,
R
Encode your data using NSUTF8StringEncoding before sending it to the server, and always use POST to send data to the server instead of GET. Also, it's a good idea to stop using ASCII altogether and to replace it with Unicode wherever you use strings. UTF-8 is a very convenient and compact Unicode encoding.
I have a PHP string type variable which may come encoded in Hexadecimal pattern or in Base64.
For example:
737461636b6f766572666c6f772e636f6d
c3RhY2tvdmVyZmxvdy5jb20=
Both lines mean stackoverflow.com, the problem is I do not know which one is going to be HEX or Base64 because of that I do not know which decoding method to apply.
Is it possible to determine the encoding method without knowing the encoded text? If yes, how to do it in php?
There is no way to know for sure whether the string is in Base64/HEX just by looking at it. You will have to include an additional bit with the string indicating which one it is, and then read that in your code and decode as required.
If, by chance the string contains a letter after 'F', you can be sure that it is Base64, but it may be Base64 even though it does not, so there is no way to be sure without some kind of header before the string telling you what the encoding is.
If you can guarantee only those two encodings the Base64 will end with an = and the Hex will only include [a-fA-F0-9].
This should not be too difficult. The valid set of characters for hex is [0-9a-f], while the valid set for Base64 is more like [a-zA-Z0-9\+/] possibly with one or two trailing = characters for padding. You should be able to use a regex to discriminate between one and the other.
Of course, there may be some instances where a string appears to be valid in both encodings, so there is no sure-fire way to test based just upon the string itself. Generally speaking, however, it would be fairly rare for a non-trivial input string encoded in Base64 to result in an output string that includes only valid hexadecimal characters and no padding characters. Fairly rare, but not impossible.
I have a website that uses the facebook, twitter, delicious share links. They contain a a url encoded url of the website that you wish to share. The problem is I then want to send the facebook/twitter/delicious url through a php redirect page.
Will it work to encode a url within an encoded url? Will there be side effects?
To simplify my question:
www.website.com/redirect.php?url=" URLENCODED (http://www.facbook.com/sharer.php?t='URLENCODED(title)'&u='URLENCODED(http://www.hotel.com)')
You can encode a string multiple times with the percent encoding and get the original value by decoding it the same amount of times:
$str = implode(range("\x00", "\xFF"));
var_dump($str === urldecode(urldecode(urldecode(urlencode(urlencode(urlencode($str)))))));
Here the value of $str is encoded three times and then decoded three times. The output of that repeated encoding and decoding is identical to the value of $str.
So try this:
'http://example.com/redirect.php?url='.urlencode('http://www.facbook.com/sharer.php?t='.urlencode('title').'&u='.urlencode('http://www.hotel.com'))
You should be able to recursively encode the URL as many times as you want. If you encode a character like / repeatedly you will get:
0: /
1: %3F
2: %%3F
3: %%%%3F
etc.
It's all right to add a second layer of URLEncoding. The idea of URLEncoding is to prevent the server from misinterpreting any special characters that may be present in a text string. However, the receiving script must expect an extra layer of urlencode(), and act accordingly.
Or if you know the string has been urlencoded, couldn't you simply pass it along as-is? No further urlencoding is necessary.
Or just urldecode the title and URL, then urlencode the whole string.
As mentioned earlier you can encode urls as much as you like but you should know the more times you encode url data the more it'll increase in length may be up two twice in length. which will be annoying for users if it is too long. also there may be a limitation on url length on some browsers.
Also on the server side there will be an overhead encoding and decoding the data.
In short you should really be sure you need it before encoding/decoding multiple times.