I am passing a string through a URL to another page whenever a link is clicked.
The original a tag and its href are created via a PHP while loop as follows:
<a href=".($row['secondary'] == 'true' ? "secondary_imgs.php?imgId=".$row['imgId']."
&imgTitle=".$row['imgTitle']."" : "new_arrivals_img/".$row['imgURL']."").">
Note: The a tag does contain other attributes but I removed them for simplicity.
The href is then appended, with the current window dimensions, using the following jQuery function:
$("a[href^='secondary_imgs.php']").click(function(){
var pageWidth = $(window).width();
var pageHeight = $(window).height();
var url = $(this).attr('href');
var idx = url.indexOf('&pageWidth=');
if (idx != -1) {
url = url.substr(0, idx);
}
url += '&pageWidth=' + pageWidth + '&pageHeight=' + pageHeight;
$(this).attr('href', url);
});
My question is, what method(s) of encoding the URL should I use in this case, seeing as it will need to be done with first PHP, then jQuery/JavaScript, and finally decoded via PHP?
Or will it need to be done in both PHP and jQuery/JavaScript? The original PHP $row['imgTitle'] will always have at least spaces in it, and so I know it needs to be done then for sure. But seeing as the appended values will always be a variable equalling a number, does that need to be encoded as well?
I know there are several methods of encoding/decoding URLs in each coding language, and my knowledge isn’t adequate enough to make the choice.
If someone could also provide an example of how I would perform each step, it would be much appreciated.
You should use
urlencode()in PHP to encode URI components.The equivalent function in javascript is
encodeURIComponent().PHP will decode parameters encoded like this automatically.
So, in you PHP:
And equivalently, in your javascript: