Im not really sure what im looking for but currently in my system i send a long url like this:
$name=1&option=2&field=4....
And its quite long. So if i have a list of values like:
name
option
field
can i put them into a string in which i can break at certain points eg by a slash or whatever.
And then encode the string so its completely random like, so i only have one field to send:
&data=JKHFGDKGLKJHFKDJHFKJDHFKHDF
Then finally i can decode the other side and break apart.
Is there a pre-built function to do this?
WHAT IT IS:
im sending data to paypal, but i have a few custom variables i wish to send, now for some reason my IPN isnt geting them, not sure why, but if i add one called custom it get to the IPN fine. So i thought if i just send one called custom in a random format and then decode?
You could simply Base64-encode your data.
$a = array('name' => '1', 'option' => '2', 'field' => '4');
$temp = json_encode($a); // convert array to string
$data = base64_encode($temp); // encode string
output:
"eyJuYW1lIjoiMSIsIm9wdGlvbiI6IjIiLCJmaWVsZCI6IjQifQ=="
To send this in an URL, you must encode it once more (like you must encode all data you would send in a URL)
$url = $url . "&data=" . urlencode($data)
The intermediary step through JSON ensures your data will kep its structure and will be easily decodeable on the receiving side.
On the downside: Your URL will be longer.
Use base64_encode and then base64_decode, this will solve your problem.
If you don't know what you are looking for we can't imagine that lol.
Anyway If i got you, you can do this, considering you have built your string:
$string ="$name=1&option=2&field=4";
You could pass it as a single param with:
$data = url_encode($string);
Other than url_encode you can use base64_encode
As the commenter (Bobby) says - consider using POST when you want to send larger sets of data and prevent your URL from becoming unmanageably long or ugly.
GET variables are handy for providing the user with a page they can bookmark directly which is desirable in some cases, such as on a search page with a query string and/or filters already filled in, so that the user can return to a search and check for new results periodically without having to reset all of their choices.
POST variables are better if you don't need that sort of functionality, you don't need to encode/decode them for URLs and they can't be bookmarked directly (which is also desirable in many cases).
To answer your original question though, if you really, really had to send the variable(s) on the URL and you wanted to just send one apparently random string, I suggest writing a couple of encode/decode functions of your own (since I assume the object of the excercise is not to encrypt it against tampering, just to make your URLs friendlier). This will be all the easier if there are restrictions to what the variables can be, and more difficult if they can be absolutely anything.
For example - if you have the following vars and possible settings:
var1 (apple, banana, orange)
var2 (car, motorbike, bicycle)
var3 (red, yellow, green)
Normally, you'd make a URL like:
http://www.mysite.com/page.php?var1=banana&var2=car&var3=green
If you assign the variables to numbers (for example) so that var1, var2 and var3 would be 1, 2 or 3 - then you could send over a URL like:
http://www.mysite.com/page.php?vars=213
Break it down at the other end into single numbers and convert those back into 'banana', 'car', and 'green'.
But seriously.... I'd look at POST first unless there is very specific reason why you would use this sort of approach - i've used it before for shortening a URL to make it more sharable on social media and forums.
Related
I am working on a PayPal payment system, I wanna send 2 values in the custom field. Therefor I used the urlencode(json_encode()) functionality. An example of how it looks without urlencoding.
$customData = array();
$customData['invoiceID'] = $invoiceID;
$customData['username'] = urlencode($_GET['username']);
$p->add_field('custom', urlencode(json_encode($customData)));
Output is:
%7B%22invoiceID%22%3A108674%2C%22username%22%3A%22Just%2Btesting%22%7D
Desired output when urldecoding and jsondecoding:
{"invoiceID":108674,"username":"Just testing"}
But it's giving me this after urldecoding and jsondecoding:
{"invoiceID":108674,"username":"Just+testing"}
The workaround for this issue is to urldecode the username itself as well once again. But why do I have to double urldecode just to get the value that I urlencoded with just one time running this function?
Seems like you are applying two times urlencode() to data so you need to apply two times urldecode() or remove one of them.
I think the "custom" field is used to identify your request on the other end, correct? So, that field is for your use and not for paypal. I think it's a good idea to encode it. But, if you want it to survive paypals back end you might want to use base64encode and base64decode.
As the question states, I need a way to encrypt a string (i.e. 'x=27&y=3&z=123456' into 'hUIgBG5664y65H2UIB') so that it can be passed via an html image source, like so:
<img src="returnpicture.php?stuff=hUIgBG5664y65H2UIB"/>
returnpicture.php will decrypt that back into 'x=27&y=3&z=123456' and parse it into three variables which will be used to pick an image and return it.
Problem is, everywhere I look, all I can find is stuff about hashing and encrypting super-sensitive information like credit cards and passwords. This info is not sensitive at all, I just don't want users to be able to tamper with it. Therefore, it shouldn't be excessively long. Also, the encryption (I'm guessing) must be alphanumeric, so as not to mess up the url with & or =. I'm doing this in php.
It's for a sort of game. The user shouldn't be able to mess with the variables, 'cause they'll see things they shouldn't yet.
For general understanding
When you include certain key-value pairs in your request url, PHP will load these values (accordingly) into the $_GET superglobal.
?x=12&y=13
Will result in
$_GET['x'] // contains 12
$_GET['y'] // contains 13
What you seem to be trying to do is to supply multiple key-value pairs within a key-value pair:
?stuff={more-key-value-pairs}
Simply be aware that PHP will not interpret key-value pairs in $_GET['stuff'].
Encoding/Decoding
Note: This is one possible solution out of many. Find the one that suits you most and apply it.
You can use base64_encode() to encode it, and base64_decode() to decode it.
Example:
echo '<img src="returnpicture.php?stuff=' . rawurlencode( base64_encode('x=27&y=3&z=123456') ) . '" />';
Usage of rawurlencode() assures proper url safe encoding of the base64-encoded string.
In your returnpicture.php you can use:
$decodedString = base64_decode( $_GET['stuff'] );
to get back your original string.
However, if you actually plan on sending a get-request like string (with variable assignments, such as ?x=12&y=13 and so on, then you need to apply further techniques to get that string parsed.
See this question for details on how it can be done
You could use a simple cipher, like a rolling XOR hash. This is very easy to implement, but enough of a nuisance to crack that people probably won't bother if the only benefit is something trivial, like the ability to get your server to serve images in non-standard sizes.
function scramble(key, text) {
return encodeURIComponent(text.replace(/[^\0]/g, function(x, i) {
var code = x.charCodeAt(0) ^ key.charCodeAt(i % key.length);
return String.fromCharCode(code);
}));
}
function descramble(key, text) {
return decodeURIComponent(text).replace(/[^\0]/g, function(x, i) {
var code = x.charCodeAt(0) ^ key.charCodeAt(i % key.length);
return String.fromCharCode(code);
});
}
If your key is "secretcode" and your text is "x=27&y=3&z=123456", then scramble(key, text) returns "%0BXQEC%0D%5E%5CB%1FNTQAQAU".
"Descrambling" that result with the same key gives the original text, "x=27&y=3&z=123456".
Note that you'd probably want to do this on the PHP side of things, the JavaScript code is just here as an example.
http://jsfiddle.net/m92rc/
I suggest that you can share information between your pages with $_SESSION vars, but, it only works if two pages are in same context server.
Approach 1. base64 encode
<img src="returnpicture.php?stuff=<?php echo base64_encode('x=27&y=3&z=123456'); ?>"/>
And get this as:
$data = base64_decode($_GET['stuff']);
Approach 2. $_SESSION variables
You should combine $_GET with $_POST without expose sensible information like:
$postfix = uniqid(); // Generate an UNIQUE id
$_SESSION['sensible_var1_'.$postfix] = "value";
$_SESSION['sensible_var2_'.$postfix] = "value";
$_SESSION['sensible_var3_'.$postfix] = "value";
And you can pass this information only with:
<img src="returnpicture.php?stuff=<?php echo $postfix; ?>"/>
And in your returnpicture.php file, you can retrive information as:
$sensible_var1 = $_SESSION['sensible_var1_'.$_GET['stuff']];
$sensible_var2 = $_SESSION['sensible_var2_'.$_GET['stuff']];
$sensible_var3 = $_SESSION['sensible_var3_'.$_GET['stuff']];
With this Symfony page, I am passing $_GET parameters in the URI like this:
http://www.mysite.com/article?page=4&sort=1
Once in my layout, there are certain links in the page that need to have the same query string in them.
Anyways, using Symfony's url_for() command I'm making URLs like so:
$url = url_for('article/index?.http_build_query($_GET));
That way it makes a new url using the $_GET variables. For some of the links I'm changing the $_GET values ahead of time, like $_GET['sort']=0; before generating the url. That's why I'm using this method.
Anyways, when I look at the generated URL, it now looks like this:
http://www.mysite.com/article?page=4&%3Bsort=1
The &%3B is the encoded form of & which is just an & character.
So the problem is that when I check for my $_GET parameters in my controller now, there is no longer a sort parameter that is passed. It's now called &%3Bsort... It's causing all sorts of issues.
Two questions:
How do I avoid this problem? Can I decode the $_GET parameter key values in my controller or something?
Why is symfony encoding a & character in the first place? It's a perfectly acceptable URI character. Heck, even the encoded value, &%3B contains a & !!!
I believe, it is because of output escaping is ON in your application. As a result, $_GET array is wrapped inside sfOutputEscaperArrayDecorator class. You can get a raw value using this: $_GET->getRawValue().
$url = url_for('article/index?.http_build_query($_GET->getRawValue()))
Or you can decode the result query using sfOutputEscaper::unescape
$url = url_for('article/index?.sfOutputEscaper::unescape(http_build_query($_GET)));
Hope this will be useful.
Best if you use Symfony's own method for getting the request parameters. For example, in templates, use:
$sf_request->getParameter('some_param');
If you must use $_GET, maybe try:
((( $sf_data->getRaw('_GET') )))
... to get past the output escaping. Not totally sure if that'll work as is.
I am looking to have a list of arguments passed across in an a URL.
$url['key1']=1;
$url['key2']=2;
$url['key3']=3;
$url['key4']=4;
$url['key5']=5;
$url['key6']=6;
$url['key7']=7;
Please Note I am trying to pass this in the URL in 1 GET variable. I know this would be better done by ?key1=1&key2=2&key3=3...etc but for reasons that are too complicated to try and explain they can't be in this format.
Any suggestions how I can convert this array into something that can be passed as 1 get var in a URL string?
Thanks in advance.
You can use json_encode() or serialize()
$myUrl = 'http://www.example.com/?myKey=' . urlencode(json_encode($url));
or
$myUrl = 'http://www.example.com/?myKey=' . urlencode(serialize($url));
Using json_encode will usually give you a shorter string, but very old PHP version might not have the json_decode function available to decode it again.
The final way would be to create your own custom encoding... it could be as simple a pipe-separated values: key1|1|key2|2|key3|3
This would give you the best option for a short URL, but is the most work.
Try http_build_query:
$url['key1']=1;
$url['key2']=2;
$url['key3']=3;
$url['key4']=4;
$url['key5']=5;
$url['key6']=6;
$url['key7']=7;
echo http_build_query($url);
//echos key1=1&key2=2&key3=3&key...
What it does is converting an array into a query string using the keys and automatically takes care of url-encoding.
EDIT:
Just read your additional requirement that it should be just one variable. So nevermind this answer.
If your problem was the proper encoding though you might want to give this another try.
Hope that helps.
The recommendation to use serialize() is fine. If space is an issue, then use a combination of bzcompress() and serialize().
However, there's a security considering that hasn't been brought up, and that's that the end user (who can see and edit this url) could manipulate the data within it. You may think it's difficult, but most of the PHP-attacking worms in the wild do this to some degree or another.
If letting the user directly manipulate any of the keys or values (or replacing it with an integer, or an object, or anything else), then you should protect your script (and your users) from this attack.
A simple solution is to simply use a shared secret. It can be anything; just so long as it's unique and truly secret (perhaps you should randomly generate it at install-time). Let's say you have in your config file something like this:
define('SECRET', 'unoqetbioqtnioqrntbioqt');
Then, you can digitally sign the serialized data created with: $s=serialize($m) using $k=sha1($s.SECRET) and make the url value $k.$s
Then, before you unserialize() do this:
$v=substr($input,0,40);
$s=substr($input,40);
if ($v != sha1($s.SECRET)) { die("invalid input"); }
$m=unserialize($s);
This way, you know that $m is the same as the original value that you serialized.
If you like, you can use the following drop-in replacements:
define('SECRET','buh9tnb1094tib014'); // make sure you pick something else
function secureserialize($o) {
$s=serialize($o);
return sha1($s.SECRET).$s;
}
function secureunserialize($i) {
$v=substr($i,0,40);$s=substr($i,40);
if ($v!=sha1($s.SECRET)){die("invalid input");}
return unserialize($s);
}
You could serialize them as key-value pairs when constructing the URL, putting the resultant serialized value in a single $_GET variable (e.g. data=sfsdfasdf98sdfasdf), then unserialize the $_GET["data"] variable. You'll need to use urlencode to make sure the resultant serialized values are URL-safe. Make sure you watch out for maximum URL lengths - 2083 characters in IE.
However, unless you really can't use key-value pairs in URLs (per your question), key1=foo&key2=bar... is definitely the way to go.
If you don't mind dropping the key names, you can use
http://example.com?url[]=1&url[]=2&url[]=3
EDIT Keeping the key names:
http://example.com?values[]=1&values[]=2&values[]=3&keys[]=1&keys[]=2&keys[]=3
Then in your PHP script:
$url = array_combine($_GET['keys'], $_GET['values']);
Could you solve your problem by saving the data as a HTML cookie? That way you don't have to modify the URL at all.
If you know the values in advance, you can set them from the server side when you send the user the page with your target link on it.
If you won't know the values until the user fills out a form it can still be done using JavascriptL When the user clicks the form submit you can set multiple cookies by making multiple javascript calls like:
document.cookie = 'key1=test; expires=Mon, 7 Sept 2009 23:47:11 UTC; path=/'
The security model might give you some trouble if you are trying to pass this data from one domain to another though.
I know the title isn't very clear. I'm new to PHP, so there might be name for this kind of thing, I'll try to explain as best as I can. Sometimes in a URL, when using PHP, there will be a question mark, followed by data. I'm sorry, I know this is very noobish, but I'm not sure what it's called to look for a tutorial or anything. Here is what I mean:
http://www.website.com/error_messages.php?error_id=0
How do you configure it to display different text depending on what the number is (in this example it's a number)
Could somebody please tell me what this is called and how I could do this? I've been working with PHP for a couple days and I'm lost. Thank you so very much for understanding that I am very new at this.
That "data" is the URL querystring, and it encodes the GET variables of that HTTP request.
Here's more info on query strings: http://en.wikipedia.org/wiki/Query_string
In PHP you access these with the $_GET "super-global" variable:
// http://www.website.com/error%5Fmessages.php?error%5Fid=0
// %5F is a urlencoded '_' character, which your webserver will most likely
// decode before it gets to PHP.
// So ?error%5Fid=0 reaches PHP as the 'error_id' GET variable
$error_id = $_GET['error_id'];
echo $error_id; // this will be 0
The querystring can encode multiple GET variables by separating them with the & character. For example:
?error_id=0&error_message=Something%20bad%20happened
error_id => "0"
error_message => "Something bad happened"
In that example you can also see that spaces are encoded as %20.
Here's more info on "percent encoding": http://en.wikipedia.org/wiki/Percent-encoding
The data after the question mark is called the "query string". It usually contains data in the following format:
param1=value1¶m2=value2
Ie, it is a list of key-value pairs, each pair separated with the ampersand character (&). In order to pass special characters in the values, they have to be encoded using URL-encoding format: Using the percent sign (%) followed by two hexadecimal characters representing the character code.
In PHP, parameters passed via the query string are automatically propagated to your script using the super-global variable $_GET:
echo $_GET['param1']; // will produce "value1" for the example above.
The raw, unprocessed query string can be retrieved by the QUERY_STRING server variable:
echo $_SERVER['QUERY_STRING'];
It's called the query string.
In PHP you can access its data via the superglobal $_GET
For example:
http://www.example.com/?hello=world
<?php
// Use htmlspecialchars to prevent cross-site scripting attacks (XSS)
echo htmlspecialchars($_GET['hello']);
?>
If you want to create a query string to append to a URL you can use http_build_query():
$str = http_build_query(array('hello' => 'world'));
As previously described, the data after the ? is the querystring (or GET data), and is accessed using the $_GET variable. The $_GET variable is an array containing the name=value pairs in the querystring.
Here is a breif description of $_GET and an example of it's usage:
http://www.w3schools.com/php/php_get.asp
Data can also be submited to a PHP script as POST data (found in the $_POST variable), which is used for passwords, etc, and is not stored in the URL. The $_REQUEST variable contains both POST and GET data. POST and GET data usually originates from being entered into a web form by a user (but GET data can also come directly from a link to an address, like in your example). More info about using web forms in PHP can be found here:
http://www.w3schools.com/php/php_forms.asp
its called "query string"
and you can retrieve it via $_SERVER["QUERY_STRING"]
or you can loop through $_GET
in this case the error_id, you can check it by something like this
echo $_GET['error_id'];
The term you are looking for is GET. So in php you need to access the GET variables in $_GET['variable_name'], e.g. in the example you gave $_GET['error_id'] will contain the value 0. You can then use this in your logic to echo back different information.
The bit after the question mark is called a Query String. The format is typically, although not necessarily always, key-value pairs, where the pairs are separated by an ampersand (&) and the value is separated from the name by an equals sign (=): ?var1=value1&var2=value2&.... Most web programming environments provide an easy way to access name-value pairs in this format. For example, in PHP, there is a superglobal, which is an associative array of these key-value-pairs. In your example, error_id would be accessible via:
$_GET['error_id']
The reason for the name "GET" is that query string variables are typically associated with a HTTP GET request. POST requests can contain GET variables too, whereas GET requests can't contain POST variables.
As to the rest of your question, you could approach the text issue in a number of ways, the simplest being switching on the error id:
$error_id = isset($_GET['error_id']) ? $_GET['error_id'] : 0;
switch($error_id) {
case 1:
echo "Error 1";
break;
default:
echo "Unknown Error";
break;
}
and more complex ways involve looking up the error message from a file, database or what have you.