Every web developer should keep useful code snippets in a personal library for future reference. You can see the most useful pieces of coding and functions realizing effects they have through library functions from a list of several. Use of coding to make various functions performed is necessary when consistency is required and reachable with good searching on the web.
PHP Code Snippets That Can Help You with Your PHP Projects Sanitize database inputs When inserting data into your database, you have to be careful about SQL injections and other attempts to insert damaging data into a db. The function below is probably the most complete and efficient way to collect strings before using them in your database. function cleanInput($input) { $search = array( '@<script[^>]*?>.*?</script>@si', // Strip out javascript '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly '@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments ); $output = preg_replace($search, '', $input); return $output; } ?> <?php function sanitize($input) { if (is_array($input)) { foreach($input as $var=>$val) { $output[$var] = sanitize($val); } } else { if (get_magic_quotes_gpc()) { $input = stripslashes($input); } $input = cleanInput($input); $output = mysql_real_escape_string($input); } return $output; } Here are some examples of use: <?php $bad_string = "Hi! <script src='http://www.evilsite.com/bad_script.js'></script> It's a good day!"; $good_string = sanitize($bad_string); // $good_string returns "Hi! It\'s a good day!" // Also use for getting POST/GET variables $_POST = sanitize($_POST); $_GET = sanitize($_GET); ?> Calculate the distance between two points: A way used to calculate distance between the two points lists with their coding which follows. The function below uses the latitude and longitude of both locations, and calculates the distance between both the points in miles and metric units. function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) { $theta = $longitude1 - $longitude2; $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta))); $miles = acos($miles); $miles = rad2deg($miles); $miles = $miles * 60 * 1.1515; $feet = $miles * 5280; $yards = $feet / 3; $kilometers = $miles * 1.609344; $meters = $kilometers * 1000; return compact('miles','feet','yards','kilometers','meters'); } Example: $point1 = array('lat' => 40.770623, 'long' => -73.964367); $point2 = array('lat' => 40.758224, 'long' => -73.917404); $distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']); foreach ($distance as $unit => $value) { echo $unit.': '.number_format($value,4).'<br />'; } Useful PHP Code Snippets For developers Get all tweets of a specific hashtag Here is a quick and easy way to get all kinds of tweets of specific use from the useful cURL library. The following example retrieves all tweets with the #cat hashtag. function getTweets($hash_tag) { $url = 'http://search.twitter.com/search.atom?q='.urlencode($hash_tag) ; echo "<p>Connecting to <strong>$url</strong> ...</p>"; $ch = curl_init($url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE); $xml = curl_exec ($ch); curl_close ($ch); //If you want to see the response from Twitter, uncomment this next part out: //echo "<p>Response:</p>"; //echo "<pre>".htmlspecialchars($xml)."</pre>"; $affected = 0; $twelement = new SimpleXMLElement($xml); foreach ($twelement->entry as $entry) { $text = trim($entry->title); $author = trim($entry->author->name); $time = strtotime($entry->published); $id = $entry->id; echo "<p>Tweet from ".$author.": <strong>".$text."</strong> <em>Posted ".date('n/j/y g:i a',$time)."</em></p>"; } return true ; } getTweets('#cats'); Applying Even/Odd Classes When generating lists or tables using PHP, it is super useful to apply even/odd classes to each row of data in order to simplify CSS styling. Used inside a loop, classes named .example-class0 and .example-class1 alternating. Increasing the “2” number allow you to increment in thirds or fourths or whatever necessary: Email error logs to yourself Instead of generally displaying possible errors on your website using a custom error handler to email error logs to yourself. Here is a handy code snippet to do it. <?php // Our custom error handler function nettuts_error_handler($number, $message, $file, $line, $vars){ $email = " <p>An error ($number) occurred on line <strong>$line</strong> and in the <strong>file: $file.</strong> <p> $message </p>"; $email .= "<pre>" . print_r($vars, 1) . "</pre>"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Email the error to someone... error_log($email, 1, '[email protected]', $headers); // Make sure that you decide how to respond to errors (on the user's side) // Either echo an error message, or kill the entire project. Up to you... // The code below ensures that we only "die" if the error was more than // just a NOTICE. if ( ($number !== E_NOTICE) && ($number < 2048) ) { die("There was an error. Please try again later."); } } // We should use our custom function to handle errors. set_error_handler('nettuts_error_handler'); // Trigger an error... (var doesn't exist) echo $somevarthatdoesnotexist;
0 Comments
Leave a Reply. |