views:

78

answers:

2

What series of steps would be reqired to safely encode and pass a string from a html href using javascript to construct the link to a php program.

in javascript set up URL

// encodes a URI component.
path = "mypgm.php?from=" + encodeURIComponent(myvar) ;

in php:

// get passed variables
$myvar = isset($_GET['myvar']) ? ($_GET['myvar']) : ''; 

// decode - (make the string  readable)
$myvar = (rawurldecode($myvar));

// converts characters to HTML entities (reduce risk of attack)
$myvar = htmlentities($myvar);

// maybe custom sanitize program as well?
// see [http://stackoverflow.com/questions/2668854/php-sanitizing-strings-to-make-them-url-and-filename-safe][1]
$myvar = sanitize($myvar);
A: 

I think the first two lines should be fine. You would use htmlentities if and when you have to output it as text.

Matthew Flaschen
A: 

Looking at your code, all you really need is this:

$myvar = !empty($_GET['myvar']) ? $_GET['myvar'] : '';

Beyond that, PHP automatically URL decodes. I personally prefer to do my htmlentities() or htmlspecialchars() when I go to output data, i.e.:

<?php echo htmlentities($mydata); ?>

The only other time you specifically need to escape or sanitize data is if you're building a SQL query:

$data = mysql_real_escape_string($mydata);
$query = "SELECT * FROM table WHERE stuff = '$mydata'";

That will prevent SQL injection. Unless you're formatting user input or performing validation, it's not absolutely necessary to do any other kind of sanitization.

Hope this helps!

mattbasta