Encode url by Javascript - php

Friends, I am currently using the below function to encode my data and send them through GET method... I am using ajax to send and php to receive them...
function urlencode(a){
a=encodeURIComponent(a);
a=a.replace(/\\/g,'%5C');
a=a.replace(/!/g,'%21');
a=a.replace(/'/g,'%27');
a=a.replace(/\(/g,'%28');
a=a.replace(/\)/g,'%29');
a=a.replace(/\*/g,'%2A');
a=a.replace(/~/g,'%7E');
a=a.replace(/%20/g,'+');
a=a.replace(/%26amp%3B/gi,'%26');
a=a.replace(/%26lt%3B/gi,'%3C');
a=a.replace(/%26gt%3B/gi,'%3E');
a=a.replace(/%26nbsp%3B/gi,'%C2%A0');
return a;
}
after passing the string through encodeURIComponent(), I used extra replace() method so that the function encode the string for my link as similar as php...
Now my question is do anyone know any shorter or easy alternative way to do the same thing...
I place this question only for learning purpose... no jQuery please...

Using escape() instead of encodeURIComponent will eliminate at least some of the replace()'s you're using. E.g:
function urlencode(a){
return escape(a);
.replace(/\*/g,'%2A');
.replace(/%20/g,'+');
.replace(/%26amp%3B/gi,'%26');
.replace(/%26lt%3B/gi,'%3C');
.replace(/%26gt%3B/gi,'%3E');
.replace(/%26nbsp%3B/gi,'%C2%A0');
}

If you are sending GET requests from JS to PHP, you should use
encodeURIComponent(), for each parameter, on the javascript side
nothing on the PHP side (because $_GET is already urldecode()d; read the notes section in its linked documentation)
If you have to url-encode things in PHP, use urlencode(), which is guaranteed to be compatible with the corresponding urldecode().
If you want to learn how to do it "by yourself", read the source-code in the corresponding libraries to make sure you do not miss any scenario... it is generally a bad idea to re-implement library functions.

Related

How can fix the syntax of a cut-off JSON string by adding characters?

I am having JSON strings that sometimes get cut off in my database. Unsurprisingly, they cannot be parsed by the PHP function json_decode(). Instead of returning null, I want the function to return the value that are still readable. For this, I need to add "]} chars and possibly even : in order to produce valid JSON again.
E.g.
{"a":"b","c":"d
should become
{"a":"b","c":"d"}
This sounds complex. Are there any solution to this except writing a full-blown JSON parser?
Are there libraries or functions for that?
PHP doesn't have any built-in functions to do this.
I've searched for "PHP fix broken JSON automatically" and found an opensource library which tries to accomplish this task.
Please take a look: https://github.com/adhocore/php-json-fixer

PHP or JQuery function for finding a string containing another string

So I'm busy building a site and trying to test out a sort of filter for certain words but trying to determine which is the best function to use and through what language. I've done a bit of research and in PHP I can use the strpos() function so for example:-
if (strpos($checkstring, 'geordie') !== false) {
$checkstring = 'invalid name';
}
I'm unsure as to whether there is a decent JQuery function that could be used to achieve the same thing. Basically I want to be able to block my friends from using my name or nickname so it would include any and all variations of 'geordie' including lowercase and uppercase as well as getting past it using 'GeoRdie' or something to that affect but also want to stop variations which would be my full nickname 'geordie dave' or 'geordie ****' or even 'geordie dave is a ****'.
I realise that this is probably a bit of a complicated one but there must be a way using perhaps an array of names?
Any help on a function to use would be great and if anyone could possibly give me an example of code that could be used would also be beneficial.
You should probably do it in javascript and in php (client side and server side). The javascript eqivalent of strpos is indexOf. If you only check with javscript, someone could forge a post packet and it would still be accepted by the server. If you are only going to check in one place, make it server side, but for user-friendly-ness, both is preferred.
I think that you should also use PHP strtolower function on $checkstring variable.
In JavaScript, you can use String#indexOf(String) to match exact strings, or RegExp#test(String) for more complicated matching.
if (str.indexOf("geordie") !== -1) {
// `str` contains "geordie" *exactly* (doesn't catch "Geordie" or similar)
}
if (/geordie/i.test(str)) {
// `str` contains "geordie", case-insensitive
}
And I'll second what Alfie said: You can't just do this on the client, because client requests can be spoofed. Client-side validation is purely for making a nice user experience; server-side validation is always required.

Sanitizing global arrays in PHP

I'm trying to find the best way to sanitize requests in PHP.
From what I've read I learned that GET variables should be sanitized only when they're being displayed, not at the beginning of the "request flow". Post variables (which don't come from the database) either.
I can see several problems here:
Of course I can create functions sanitizing these variables, and by calling something like Class::post('name'), or Class::get('name') everything will be safe. But what if a person who will use my code in the future will forget about it and use casual $_POST['name'] instead of my function? Can I provide, or should I provide a bit of security here?
There is never a one-size-fits-all sanitization. "Sanitization" means you manipulate a value to conform to certain properties. For example, you cast something that's supposed to be a number to a number. Or you strip <script> tags out of supposed HTML. What and how exactly to sanitize depends on what the value is supposed to be and whether you need to sanitize at all. Sanitizing HTML for whitelisted tags is really complex, for instance.
Therefore, there's no magic Class::sanitize which fits everything at once. Anybody using your code needs to think about what they're trying to do anyway. If they just blindly use $_POST values as is, they have already failed and need to turn in their programmer card.
What you always need to do is to escape based on the context. But since that depends on the context, you only do it where necessary. You don't blindly escape all all $_POST values, because you have no idea what you're escaping for. See The Great Escapism (Or: What You Need To Know To Work With Text Within Text) for more background information on the whole topic.
The variables are basically "sanitized" when PHP reads them. Meaning if I were to submit
"; exec("some evil command"); $blah="
Then it won't be a problem as far as PHP is concerned - you will get that literal string.
However, when passing it on from PHP to something else, it's important to make sure that "something else" won't misinterpret the string. So, if it's going into a MySQL database then you need to escape it according to MySQL rules (or use prepared statements, which will do this for you). If it's going into HTML, you need to encode < as < as a minimum. If it's going into JavaScript, then you need to JSON-encode it, and so on.
You can do something like this... Not foolproof, but it works..
foreach($_POST as $key => $val)
{
//do sanitization
$val = Class::sanitize($val);
$_POST[$key] = $val;
}
Edit: You'd want to put this as close to the header as you can get. I usually put mine in the controller so it's executed from the __construct() automagically.
Replace the $_POST array with a sanitizer object which is beheaving like an array.

is there a way to compress a GET string so it won't be so long?

I need to compress a string so it is shorter for a GET method form. Is there any way to compress a string and it will be decrypted later? That way...
?error=LOTS OF STUFFLOTS OF STUFFLOTS OF STUFFLOTS OF STUFFLOTS OF STUFF
is shorter in some sort of key
?error=somekey
so I can get back the result later. Not using MySQL preferably.
Anyone know a good method for this?
Update: To clarify, I am using a GET because this is a cross site include and a POST will not be accepted into the variable scope of the HTTP included file.
If you're using PHP, the easiest way to send an error message is with the $_SESSION. Simply say session_start(); at the top of the pages, and say $_SESSION['error'] = "TEXT";. Then isset($_SESSION['error']);.
Of course, you could always use $_POST.
I'd use POST instead... Or, come up with your own key mapping (error=1 would map to a long wordy error - like Col. Shrapnel's example).
You could also use a hash table. http://en.wikipedia.org/wiki/Hash_function
Easiest way to make your GET string shorter. Use POST.
(Update: Again, if you control how the form is sent, use POST. Use it. Don't use GET. To be clear, if you can use POST.)
But perhpas you need to pass this data as a regular old link. In that case I guess you could try php's compression functions. Some of the operate directly on strings.
For example, gzcompress() and gzuncompress() could be used to compress/uncompress a string. From the php manual:
<?php
$compressed = gzcompress('Compress me', 9);
$uncompressed = gzuncompress($compressed);
echo $uncompressed;
?>
Of course you'll have to run it through urlencode() and urldecode() - which since I'm sure the compression algorithms will output binary data, may not really save you anything.
Or it may not work at all. Would be interesting to try.
Update: Tested, it's crazy, but it did make your example string smaller.
Not really 'on-the-fly', You might be able to Gzip and then base64 encode, (but base64 encoding increases the size, I just don't know how much)
But really, if you are exceeding the GET size, you should probably just switch to POST.

Replacing javascript functions using PHP

I want to use PHP to replace javascript functions in HTML documents. For example:
original:
function my_function(hey) {
do stuff
}
new:
function new_function(hi) {
do different stuff
}
I was thinking of using regular expressions with the ereg_replace function, but I'm not sure if this is the best approach. The code in each function is pretty long... plus regex looks very daunting to me at the moment. Any suggestions?
This is the kind of thing that perl is built for. Spend a day learning how to slurp in files and take a good look at the many regex tools out there, and you'll have yourself a script that you can modify to use in the future, if need be, but is otherwise throwaway, which is good, since you probably wrote it crappily, being your first one and all.
Looks like you trying to do something pointless. Put a new function and call it. Just do no use the old one, once you anyway want to replace the entire body with it's name.

Categories