Quantcast

FYIndOut

Archive for the ‘Programming’ Category

Passing PHP Variables to External JavaScript Files

Wednesday, October 14th, 2009

Over the years, web development has morphed from static web pages that included content and style in one file, to large complex web applications that pull information from databases while adjoining multitudes of PHP, JavaScript, and CSS files. A developer’s Rubik’s cube is getting all of these different platforms that make up a modern day web page (MySQL, PHP, JavaScript and the DOM) to all talk to each other seamlessly, while keeping security in mind.

Typically, when a developer needs their JavaScript to access a variable contained within PHP, it requires an AJAX call to the PHP script which would return the variable(s) in JSON format. This method can sometimes be undesirable as it posses security vulnerabilities. Also, if the AJAX call is made on the page load, it’s just one more HTTP request slowing down the load speed of your site. There’s also the method of placing needed variables in a hidden input and then retrieving them from the DOM with JavaScript, but with the advent of Firebug, no hidden input is safe from malicious users these days. So how can we tackle these issues while still seamlessly integrating PHP and JavaScript? Easy. Have PHP parse your JavaScript files.

Create a .htaccess file in your JavaScript directory and add this line:

  1. AddHandler application/x-httpd-php js

This tells the PHP parser to read files that have a ‘js’ file extension. Now you can simply set and unset $_SESSION variables to pass values to the JavaScript. For example:

PassPHPVarToJS.php

  1. <?php
  2. $myVariableThatJavaScriptNeeds = 42;
  3. $_SESSION['myJavaScriptVar'] = $myVariableThatJavaScriptNeeds;
  4. ?>
  5. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
  6. “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
  7. <html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
  8. <head>
  9. <meta http-equiv=”Content-Type” content=”text/html;charset=utf-8″ />
  10. <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
  11. <script type=”text/javascript” src=”js/index.js”></script>
  12. <title>PHP to JavaScript variable passing</title>
  13. </head>
  14. <body>
  15. Test
  16. </body>
  17. </html>

/js/PassPHPVarToJS.js

  1. <?php
  2. // Start PHP session
  3. ?>
  4. $(document).ready(function(){
  5. // Echo the session variable
  6. var varFromPHP = <?php echo $_SESSION[‘myJavaScriptVar’]; ?>;
  7. // Test
  8. alert(‘This value is from PHP: ’ + varFromPHP);
  9. <?php
  10. // Unset the session variable
  11. unset($_SESSION[‘myJavaScriptVar’]);
  12. ?>
  13. });

This will securely alert the PHP variable to the user while avoiding using an additional HTTP request.

But what about passing arrays and objects? Not a problem. Example:

PassPHPObjectToJS.php

  1. <?php
  2. $myObjectThatJavaScriptNeeds = array({
  3. ’someValue’ => “Bears”,
  4. ’someOtherValue’ => “Beets”,
  5. ’someNestedArray’ => array({
  6. ‘someNestedArrayValue’ => “Battlestar Galactica”
  7. })
  8. });
  9. $_SESSION['myJavaScriptVar'] = $ myObjectThatJavaScriptNeeds;
  10. ?>
  11. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
  12. “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
  13. <html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
  14. <head>
  15. <meta http-equiv=”Content-Type” content=”text/html;charset=utf-8″ />
  16. <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
  17. <script type=”text/javascript” src=”js/index.js”></script>
  18. <title>PHP to JavaScript variable passing</title>
  19. </head>
  20. <body>
  21. Test
  22. </body>
  23. </html>

/js/PassPHPObjectToJS.js

  1. <?php
  2. // Start PHP session
  3. ?>
  4. $(document).ready(function(){
  5. // Echo the session variable
  6. var objectFromPHP = <?php echo json_encode($_SESSION[‘myJavaScriptVar’]); ?>;
  7. // Test
  8. alert(‘This value is from PHP: ’ + objectFromPHP.someNestedArray. someNestedArrayValue);
  9. <?php
  10. // Unset the session variable
  11. unset($_SESSION[‘myJavaScriptVar’]);
  12. ?>
  13. });

PHP 5.2 and higher have built in JSON functions, so you can easily convert PHP variables to JSON. If you’re running on a lower version of PHP there are solutions out there that you can include in your page to achieve the same output.

That’s it! Your site just instantly became more secure while promoting low coupling and high cohesion. Now some might point out that this slows down your execution time due to the fact that PHP is now parsing extra files it normally wouldn’t parse, but I would argue that the extra parsing time is negligible, and that its quicker than making an unsafe and unnecessary AJAX call.

Spread the word:
  • Facebook
  • Twitter
  • LinkedIn
  • Digg
  • del.icio.us
  • Mixx
  • Google Bookmarks
  • email
  • Print
  • Reddit
  • Sphinn
  • Technorati

Text to SEO

Thursday, June 11th, 2009
SEO

In our last release, our development team implemented SEO friendly URLs. This allowed us to change our URL’s from something like http://fyindout.com/research/Research.php?Id=361 to http://www.fyindout.com/research/title/Study_Cash_Flow_Margins_Declining . This is huge for search engine optimization and having FYIndOut’s vendors list higher on search engines like Google and Yahoo. It was no easy task. We ran into a few roadblocks until we finally (hopefully) got it right. This post outlines how we convert any text string to an SEO-friendly representation.

Replace spaces with underscores

Initially we thought “Okay, we’ll just replace all spaces with underscores”:

<?php
   $research_title = “Awesome piece of research!”;
   $seo_research_title = str_replace(“ “, “_”, $research_title);
   echo $seo_research_title;
   // ‘Awesome_piece_of_research!’
?>

This worked for about 50% of our text research titles. The first error we ran into was a title that had an ampersand (&) in it:

<?php
   $research_title = “Erberts & Gerberts have great sandwiches.”;
   $seo_research_title = str_replace(“ “, “_”, $research_title);
   echo $seo_research_title;
   // ‘Erberts_&_Gerberts_have_great_sandwiches.’
?>

The problem here is that ampersands are used as request variable delimiters. So in our code, that research title would show up as “Erberts_”. Again, this not what we’re looking for. So we started replacing all ampersands with underscores:

<?php
   $research_title = “Erberts & Gerberts have great sandwiches.”;
   $seo_research_title = str_replace(“&“, “_”, str_replace(“ “, “_”, $research_title));
   echo $seo_research_title;
   // ‘Erberts___Gerberts_have_great_sandwiches.’
?>

This fixed all occurrences of ampersands in research titles. This still didn’t solve all of our problems though. We’d still get database matching errors for colons, semi-colons, and a slew of other symbols. We considered using browser escape codes, but that would defeat the purpose of SEO in the first place. So the final fix was to throw out anything that wasn’t a letter, number or space. Regular expressions to the rescue:

Get rid of all the symbols

<?php
   $research_title = “Microsoft launches new search engine ‘Bing’!!!”;

   // Matches anything that’s not a digit, space, or letter
   $symbols = "/[^\d\s\w]/";

   // Matches 1 or more spaces
   $spaces = "/[\s]+/";

   // Replace all symbols with spaces
   $research_title = preg_replace($symbols, " ", $research_title);

   echo $research_title
   // ‘Microsoft launches new search engine  Bing    ’

   // Trim whitespace from the beginning and end
   $research_title = trim($research_title);

   echo $research_title
   // ‘Microsoft launches new search engine  Bing’

   // Replace all occurrences of one or more spaces with a single underscore
   $research_title = preg_replace($spaces, "_", $research_title)

   echo $research_title
   // ‘Microsoft_launches_new_search_engine_Bing’
?>

This is our final product. Let me walk you through it.

The first regex pattern, $symbols, uses negated character classes. ‘\d’ matches any digit, ‘\s’ matches any white space, and ‘\w’ matches any word character. The caret (^) preceding these character classes negates them all. Wrap that all in square brackets and then again in forward slashes and you there have a regex that will match anything that’s not a letter, number, or space.

The second regex pattern, $spaces, again uses character classes to match one or more spaces. ‘\s’ matches a space, so you wrap that in square brackets and add a plus (+) sign at the end so it matches one or more spaces. Wrap that in forward slashes and you’re done.

Finally, we return the string after replacing the symbols with spaces, trimming whitespace from the front and back, and then replacing one or more spaces with a single underscore.

Why trim whitespace?

The reason we have to trim whitespace is to eliminate underscores from appearing at the beginning and end of the text. If we used the title ‘Awesome piece of research!!!’ without trimming whitespace, it would result in ‘Awesome_piece_of_research_’. Trimming in between the regex’s eliminates those underscores from appearing.

Make it a function call

<?php
   function stringToSEO($string) {

      // Matches anything that’s not a digit, space, or letter
      $symbols = "/[^\d\s\w]/";

      // Matches 1 or more spaces
      $spaces = "/[\s]+/";

      // Replace, trim, replace, return
      return preg_replace($spaces, "_", trim(preg_replace($symbols, " ", $string)));
   }
?>

This is in fact the same function we use to generate SEO friendly titles. Feel free to use it in your web development, and if you have any suggestions or optimizations, post a comment or shoot me an email at ralph.holzmann@fyindout.com or a tweet at twitter.com/ralphholzmann.

Edit Bonus: JavaScript Version

function stringToSEO (text) {

   var symbols = /[^\d\s\w]/gi;
   var trim = /^\s+|\s+$/g;
   var spaces = /[\s]+/gi;

   return text.replace(symbols, " ").replace(trim, "").replace(spaces, "_");
}
Spread the word:
  • Facebook
  • Twitter
  • LinkedIn
  • Digg
  • del.icio.us
  • Mixx
  • Google Bookmarks
  • email
  • Print
  • Reddit
  • Sphinn
  • Technorati