php – Escaping PHP

Escaping PHP
It was recently posted in the forums that a JavaScript function was rendering an error when it was called within a PHP if() statement. The reason is usually clearly known – said function wasn’t PHP, it was JavaScript. The problem is, most new PHP users won’t know how to use one of PHP’s most useful attributes – you can return to HTML at any time.

That being said, let’s take a look at this user’s specific problem. They wanted to check if the user had filled out their e-mail address, and if they had, send a javascript alert with the e-mail they submitted. Take a look at the original code, which would look normal to anyone who didn’t know that alert() is a javascript function:

Example:

function check_emailaddr($cemail) {
if (!empty($cemail)) {
alert( “<?=$cemail?>” );
}
}

The problem he ran into, obviously, was that he was calling to an undefined function. New PHP users will quickly become frustrated by this fact – even if they know it’s not a PHP function, how do they make it work if it’s in an if() statement, necessitating the use of PHP? Here’s how:

Example:

function check_emailaddr($cemail) {
if (!empty($cemail)) { ?>
<script><!–
alert(“<?php echo $cemail; ?>”);
–></script>
<?php ;
}
}

The solution was to escape PHP, and execute the script function outside of PHP. To make sure we run into no subsequent PHP problems or errors, we come back into PHP when we’re done with the javascript, end the line with the semicolon, finish the if statement and the function definition.

People might now be saying “Oh, so what? We’ve solved a simple issue with a specific solution! Where does that land me?” I beg to differ in the specificity of the solution – you can apply this to all sorts of things. Let’s take a look at a few possible uses on the next page.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: