• Create an account
    *
    *
    *
    *
    *
    Fields marked with an asterisk (*) are required.
  • Thursday, Apr 17

    Last update01:38:05 PM

    • Installing Magento via SSH With The Full Download

      Following code used version 1.6.0.0, make sure to change the version number if you want to install a different version number:

      wget http://www.magentocommerce.com/downloads/assets/1.6.0.0/magento-1.6.0.0.tar.gz
      tar -zxvf magento-1.6.0.0.tar.gz
      mv magento/* magento/.htaccess .
      chmod -R o+w media var
      chmod o+w app/etc
      
      To delete magento folder and tar file:
      rm -rf magento/ magento-1.6.0.0.tar.gz
      

      Read More...
    • A basic Joomla 1.5 CSS file

      Following are the classes used in Joomla 1.5 template CSS.

      .article_separator{}
      .adminform{}
      .author{}
      .bannerfooter{}
      .bannergroup{}
      .bannerheader{}
      .banneritem{}
      .blog{}
      .blog_more{}
      .blogsection{}
      .breadcrumbs{}
      .button{}
      .buttonheading{}
      .clr{clear:both}
      .componentheading, .contentheading{}
      .content_email{}
      .content_rating{}
      .content_vote{}
      .contentdecription{}
      .contentpagetitle{}
      .contentpane{}
      .contentpaneopen{}
      .contenttoc{}
      .createdate{}
      .created-date{}
      .date{}
      .input{}
      .inputbox{}
      .intro{}
      .latestnews{}
      .loclink{}
      a.mainlevel:link, a.mainlevel:active, a.mainlevel:visited{}
      a.mainlevel:hover{}
      .message{}
      .metadata{}
      .modifydate{}
      .module{}
      .moduletable{}
      .mosimage{}
      .mosimage_caption{}
      .mostread{}
      .newsfeed{}
      .outline{}
      .pagenav{}
      .pagenav_next{}
      .pagenav_prev{}
      .pagenavbar{}
      .pagenavcounter{}
      .pathway{}
      .pollstableboarder{}
      .read{}
      .search{}
      .searchintro{}
      .sections{}
      .sectiontable_footer{}
      .sectiontableentry{}
      .sectiontablefooter{}
      .sectiontableheader{}
      .small{}
      .smalldark{}
      a.sublevel:link, a.sublevel:active, a.sublevel:visited{}
      a.sublevel:hover{}
      .title{}
      .wrapper{}
      

      Read More...
    • A basic Joomla 1.5 template xml file

      New Joomla template developers know every time when they start a template they need to write all the xml from scratch. Well here is a very basic xml file that can be used as start or reference.

      Read More...
    • A function to generate unique id's and keys

      Following function will generate id's/keys without using MD5 or SHA1.

      function uniqueKey($length = '32') {
        $uniquekey ='';
        $code = array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z'));
        mt_srand((double)microtime()*1000000);
        if($length > 1024): $length = '1024'; endif;
        for ($i = 1; $i <= $length; $i++) {
          $swap = mt_rand(0,count($code)-1);
          $uniquekey .= $code[$swap];
        }
        return $uniquekey;
      }
      PHP function uniqid() to generate Unique ID's. It will create prefixed unique identifier based on current time in microseconds. This function will return (13 + prefix length) characters long identifier. If 'lcg' is true then it will return (prefix length + 23) characters. This function will generate shorter strings than md5(), which will also save you some space. Syntax: string uniqid ( string prefix [, bool lcg])
      // generate unique string
      echo uniqid();
      // prints 4bd67c947233e
      
      // generate another unique string
      echo uniqid();
      // prints 4bd67c9472340
      
      Make guessing very difficult:
      $uniqueID = md5 (uniqid (rand(), true));
      To reduce the chances of getting a duplicate, you can pass a prefix, or the second parameter to increase entropy:
      // with prefix  
      echo uniqid('foo_');  
      // prints 
      foo_4bd67d6cd8b8f 
        
      // with more entropy  
      echo uniqid('',true);  
      // prints 
      4bd67d6cd8b926.12135106 
        
      // both  
      echo uniqid('bar_',true);  
      // prints 
      bar_4bd67da367b650.43684647 
       
      MD5 Function to generate Unique ID's Can also use md5() function for this, even though it's not exactly meant for this purpose:
      // generate unique string  
      echo md5(time() . mt_rand(1,1000000));
      

      Read More...
    • Arbitrary Number of Arguments in a Function

      How to create a function that accepts any number of arguments? We can use func_get_args. It returns an array comprising a function's argument list. // note empty argument list function foo() { // func_get_args will return an array of all passed arguments $args = func_get_args(); // Now we can loop through array and find arguments foreach ($args as $k => $v) { echo "arg".($k+1).": $v\n"; } } // Now lets see what outputs we get foo(); /* prints nothing */ foo('hello'); // prints arg1: hello foo('hello', 'world', 'again'); // prints arg1: hello, arg2: world, arg3: again

      Read More...
    • Art Board and Crop in Illustrator

      In your Illustrator print settings there is an option under 'Setup' to crop the print to the: Artboard, Artwork Bounding Box (basically everything in the file) or a specified 'Crop Area'. If you want to crop everything in your artboard do following: You can just mask out everything by making a box the size of the artboard and putting it at the top, selecting all and then doing a CMD+7 to crop it.

      Read More...
    • Auto Loading classes in Joomla

      If you use JLoader to load classes, Joomla will store list of class names and their corresponding files. This way it will automate the registration of classes if there are multiple classes.

      JLoader::register("className",JPATH_PLUGINS.DS."content".DS."itpsocialbuttons".DS."class_file.php");
      $myObject = new className($link, $options);
      $myUrl = $myObject->getUrl();
      
      Following makes a list of all files in /classes and registers them with JLoader. {/codecitation} Example 6: $classpath = dirname(__FILE__).DS.'classes'; foreach( JFolder::files($classpath) as $file ) { JLoader::register(JFile::stripExt($file),$classpath.DS.$file); } {/codecitation}

      Read More...
    • Breezing form data vairiables

      Joomla's Breezing Form data variables:

      // fallback if no template exists
      
      if ($this->record_id != '')
      $body .= BFText::_('PROCESS_RECORDSAVEDID')." ".$this->record_id.nl().nl();
      $body .=
      BFText::_('PROCESS_FORMID').": ".$this->form.nl().
      BFText::_('PROCESS_FORMTITLE').": ".$this->formrow->title.nl().
      BFText::_('PROCESS_FORMNAME').": ".$this->formrow->name.nl().nl().
      BFText::_('PROCESS_SUBMITTEDAT').": ".$this->submitted.nl().
      BFText::_('PROCESS_SUBMITTERIP').": ".$this->ip.nl().
      BFText::_('PROCESS_PROVIDER').": ".$this->provider.nl().
      BFText::_('PROCESS_BROWSER').": ".$this->browser.nl().
      BFText::_('PROCESS_OPSYS').": ".$this->opsys.nl().nl();
      if (count($this->maildata)) foreach ($this->maildata as $data)
      $body .= $data[_FF_DATA_TITLE].": ".$data[_FF_DATA_VALUE].nl();
      }
      
      $attachment = NULL;
      if ($this->formrow->emailxml>0) {
      $attachment = $this->expxml();
      if ($this->status != _FF_STATUS_OK) return;
      } // if
      
      for($i = 0; $i < $recipientsSize;$i++){
      $this->sendMail($from, $fromname, $recipients[$i], $subject, $body, $attachment, $isHtml);
      }
      echo "test";
      } // sendEmailNotification
      

      Read More...
    • Cake PHP .ctp files syntax highlighting in Netbeans

      Netbeans by default does not detect or highlight Cake PHP ctp files. .ctp files are cakephp files which is similar to .php files but with the file extension of .ctp. To enable syntax highlighting for Cake PHP files you can go to Tools > Options > Miscellaneous > Files Then click on new button next to File Extension field. Enter ctp in popup box for New File Extension Press on and then select PHP Files (text/x0php5) in Associated File Type field. Press OK. Now go to your Netbeans and close and open file again. It should have the correct syntax highlighting. Same steps could be used to associated other types of file extensions for PHP, JavaScript etc.

      Read More...
    • Calling a plugin from a Component or another Plugin

      You can use a plugins functions from another plugin or component using following codes. These are for Joomla 1.5

      $Plugin =& JPluginHelper::getPlugin('system', 'saleslogix');
      $dispatcher =& JDispatcher::getInstance();
      $plg = array("type"=>"system","name"=>"saleslogix","params"=>$Plugin->params);                  
      $saleslogixPlg = new plgSystemSaleslogix( $dispatcher, $plg );
      //$resultHere = $saleslogixPlg->myFunction();
      
      OR
      JPluginHelper::importPlugin('system');
      $app = &JFactory::getApplication();
      $app->triggerEvent('onAfterInitialise');
      

      Read More...
    • Calling plugin method inside custom component in Joomla 1.7

      You can call a plugin method inside a component and pass it data.

      $data = array('param1' => $items, 'param1' => $location, ....); // Plugin parammeters
      JPluginHelper::importPlugin('myplugins', 'plugin_name'); // Load plugin
      
      $dispatcher = JDispatcher::getInstance();
      
      $result = $dispatcher->trigger('getMyFunction', $data);
      
      $this->items = $result[0];
      
      You can have all your custom plugin in a group and give it a name for example "myplugins". All the component needs to do is invoke the plugin, pass data and handle response.

      Read More...
    • Checking view permissions

      To check view permissions, you have to check whether the "access" field is within the viewing access levels for which the user is allowed to see.

      $user = JFactory::getUser();
      $groups = $user->getAuthorisedViewLevels();
      $allowed = in_array($item->access, $groups);
      
      via query:
      $user = JFactory::getUser();
      $groups = implode(',', $user->getAuthorisedViewLevels());
      $query->where('a.access IN ('.$groups.')');
      

      Read More...
    • chmod directories/files using command line

      //Following command will set the permission for all directories only:
      find . -type d -exec chmod 755 {} \;
      
      //Following command will set the permission for all files only:
      find . -type f -exec chmod 644 {} \;
      
      //To only apply chmod to files with names matching a specified pattern:
      find . -type f -name '*.htm*' -exec chmod 644 {} \;
      
      //To restrict to an owner you can also do:
      find . -type d -user fileowner -exec chmod 0755 {} \;
      
      //Changing files of only a specific type/extension is:
      find ./ -name *.pdf -exec chmod 755 {} \;
      

      Read More...
    • Create New user in Joomla

      <?php
      function CreateNewUser($name, $username, $email, $password, $registerDate = NULL, $usertype = 'Registered', $block = '0', $sendEmail = '1', $gid = '18') {
              global $db;
      
              $db = & JFactory::getDBO();
              jimport('joomla.user.helper');
      
              //Make the joomla password hash
              $salt = JUserHelper::genRandomPassword(32);
              $crypt = JUserHelper::getCryptedPassword($password, $salt);
              $joomlapassword = $crypt . ':' . $salt;
      
              //Table #__users
              //Informations about the user
              $user = new stdClass;
              $user->id = NULL;
              $user->name = $name;
              $user->username = $username;
              $user->email = $email;
              $user->password = $joomlapassword;
              $user->registerDate = registerDate;
              $user->usertype = $usertype;
              $user->block = $block;
              $user->sendEmail = $sendEmail;
              $user->gid = $gid;
      
              if (!$db->insertObject('#__users', $user, 'id')) {
                  echo $db->stderr();
                  return false;
              }
      
      
              //Table #__core_acl_aro
              //Discover what is the last value of value in #__core_acl_aro
              $query = "SELECT value FROM #__core_acl_aro ORDER BY id DESC LIMIT 1";
              $db->setQuery($query);
              $coreaclarolastvalue = $db->loadResult();
      
              $coreaclaro = new stdClass;
              $coreaclaro->id = NULL;
              $coreaclaro->section_value = 'users';
              $coreaclaro->value = $coreaclarolastvalue + 1;
              $coreaclaro->order_value = NULL;
              $coreaclaro->name = $name;
              $coreaclaro->hidden = NULL;
      
              if (!$db->insertObject('#__core_acl_aro', $coreaclaro, 'id')) {
                  echo $db->stderr();
                  return false;
              }
      
              //Table #__core_acl_groups_aro_map
              $coreaclmap = new stdClass;
              $coreaclmap->group_id = $gid;
              $coreaclmap->section_value = NULL;
              $coreaclmap->aro_id = $coreaclaro->id; // maybe just $user->id ?
      
              if (!$db->insertObject('#__core_acl_groups_aro_map', $coreaclmap)) {
                  echo $db->stderr();
                  return false;
              }
      
              $CreateNewUserInfo = array($user->id, $user->name, $user->username, $user->email);
              return $CreateNewUserInfo;
      }
      
      Implementation
      
      //This exemple will take data from one post, for example
      $username = JRequest::getVar('username');
      $name = JRequest::getvar('name');
      $email = JRequest::getVar('email');
      $password = JRequest::getVar('password');
      
      //This code will call your funcion, then register with your data
      $NewUserInfo = CreateNewUser($name, $username, $email, $password, $registerDate);
      

      Read More...
    • Creating zip archives in PHP

      PHP comes with a ZipArchive class that lets us create and manipulate .zip files.

      Creating a Zip file using PHP

      Following code will create master.zip with files containing master.css, new.css, layout.css
      $zip = new ZipArchive(); // creates ZipArchive object
       
      $ow = 1;
      $file= "master.zip";
      if($zip->open($file,$ow?ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE)===TRUE) {
         // Following will add master.css to zip file
         $zip->addFile("master.css"); 
         
         // This means old.css will be added as new.css
         $zip->addFile("old.css", "new.css");
         
         // Following will close the zip file
         $zip->close();
         
         $zip->addFile("layout.css");
       }
      

      Extracting a Zip file using PHP

      $zip = new ZipArchive(); // creates ZipArchive object
      
      // Open master.zip for extracting all files
       if ($zip->open("master.zip") === TRUE) {
         $zip->extractTo("/path/to/folder/"); // Extract all files to given path
         $zip->close();
       }
      
      // Open master.zip for extracting single files
       if ($zip->open("master.zip") === TRUE) {
         $zip->extractTo("/path/to/folder/","layout.css"); // Only extracts layout.css to given path
         $zip->close();
       }
      
      // Open master.zip for extracting multiple files
       if ($zip->open("master.zip") === TRUE) {
         $files = array("layout.css","master.css"); // Only extracts layout.css and master.css to given path
         $zip->extractTo("/path/to/folder/",$files);
         $zip->close();
       }
      

      Read More...
    • CSS Classes to input tags

      Input elements can be targeted by assigning tags to the same input types. It is possible that we want to style input elements as text input fields, text areas and select boxes to have different widths while button input elements to have a different style.

      <input type="text" class="text" />
      <input type="checkbox" class="checkbox" />
      <input type="radio" class="radio" />
      <input type="button" class="button" />
      
      Can also use multiple classes:
      <input type="password" class="password text" />
      Now using following in css we can target each type separately. [css]input[type="button"] { border:2px solid #ccc; padding:3px}[/css]

      Read More...
    • CSS with PHP using PHP variables

      Recently one of my client asked me to add the functionality for users of their custom Content Management System(CMS) to give them more control over layouts etc. Using CSS in PHP makes it really easy to have styling flexibility. Following steps are involved to write CSS via PHP. Create CSS file as a PHP file Set its content type using the following code

      header("Content-type: text/css; charset: UTF-8");
      Create PHP variables as you would normally in other PHP code. You can also bring variable data from database etc.
      <?php
      $myVariable = '#000000';
      $myLeftColHeight = '500px';
      ?>
      
      Outside your PHP tags you can write all of normal CSS code. Where ever you need to write the variable value just echo that variable not PHP way. [css]#myLeftCol {height:; color:;}[/css] Final Code for stylesheet.php:
      header("Content-type: text/css; charset: UTF-8");
      $myVariable = '#000000';
      $myLeftColHeight = '500px';
      ?>
      #myLeftCol {height:; color:;}
      

      Read More...
    • CURLOPT_FOLLOWLOCATION warning message

      While developing a twitter extension I came across following warning message on my Ubuntu development server.

      Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set.
      
      After doing some research I found that curl follow location option tells curl to follow a redirect header or not. If the environment in the php.ini is running php in safe mode or an open base dir is set, the CURLOPT_FOLLOWLOCATION will end up raising a warning message on the page. Solution:
      $ch = curl_init();
      if(!ini_get('safe_mode') && !ini_get("open_basedir")) {
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
      }
      ...
      $response = curl_exec($ch); // response of a page with a redirect
      if(ini_get('safe_mode') || ini_get("open_basedir") != false) {
      curl_setopt($ch, CURLOPT_URL, "http://url-of-the-redirected-response.com");
      $response = curl_exec($ch);
      }
      

      Read More...
    • Custom parameter optgroup for Joomla 1.5

      In this post we will walk you through the steps on how to create a custom parameter for Joomla 1.5 websites. The parameter we will create will be optgroup that shows as a dropdown box with groups of select options separated with headings. optgroups Custom Parameter

      <?php
      // no direct access
      defined('_JEXEC') or die('Restricted access');
      
      class JElementOgtypes extends JElement {
      	var	$_name = 'Ogtypes';
      	function fetchElement($name, $value, &$node, $control_name) {
              $ctrl = $control_name . '[' . $name . ']';
             
              // Option group arrays
              $activities     = array('activity'=>'activity', 'sport'=>'sport');
              $businesses     = array('bar'=>'bar', 'company'=>'company', 'cafe'=>'cafe', 'hotel'=>'hotel', 'restaurant'=>'restaurant');
              $groups         = array('cause'=>'barcause', 'sports_league'=>'sports_league', 'sports_team'=>'sports_team');
              $organisations  = array('band'=>'band', 'government'=>'government', 'non_profit'=>'non_profit', 'school'=>'school', 'university'=>'university');
              $people         = array('actor'=>'actor', 'athlete'=>'athlete', 'author'=>'author', 'director'=>'director', 'musician'=>'musician', 'politician'=>'politician', 'public_figure'=>'public_figure');
              $places         = array('city'=>'city', 'country'=>'country', 'landmark'=>'landmark', 'state_province'=>'state_province');
              $products       = array('album'=>'album', 'book'=>'book', 'drink'=>'drink', 'food'=>'food', 'game'=>'game', 'product'=>'product', 'song'=>'song', 'movie'=>'movie', 'tv_show'=>'tv_show', 'upc'=>'upc', 'isbn'=>'isbn');
              $websites       = array('blog'=>'blog', 'website'=>'website', 'article'=>'article');
      
              
              $options = array(); // Empty array to add options into
              $options[] = JHTML :: _('select.option', '', JText::_('SELECT_OG_TYPE')); // Initial option
              $options[] = JHTML::_('select.optgroup', 'Activities'); // optgroup option to add group of items
              foreach($activities as $key => $text) { // loop through items
                  $options[] = JHTML::_('select.option', $key, $text);
              }
              $options[] = JHTML::_('select.option', '</OPTGROUP>'); // Close OptGroup
      
              $options[] = JHTML::_('select.optgroup', 'Businesses');
              foreach($businesses as $key => $text) {
                  $options[] = JHTML::_('select.option', $key, $text);
              }
              $options[] = JHTML::_('select.option', '</OPTGROUP>');
      
              $options[] = JHTML::_('select.optgroup', 'Groups');
              foreach($groups as $key => $text) {
                  $options[] = JHTML::_('select.option', $key, $text);
              }
              $options[] = JHTML::_('select.option', '</OPTGROUP>');
              
              $options[] = JHTML::_('select.optgroup', 'Organisations');
              foreach($organisations as $key => $text) {
                  $options[] = JHTML::_('select.option', $key, $text);
              }
              $options[] = JHTML::_('select.option', '</OPTGROUP>');
              
              $options[] = JHTML::_('select.optgroup', 'People');
              foreach($people as $key => $text) {
                  $options[] = JHTML::_('select.option', $key, $text);
              }
              $options[] = JHTML::_('select.option', '</OPTGROUP>');
              
              $options[] = JHTML::_('select.optgroup', 'Places');
              foreach($places as $key => $text) {
                  $options[] = JHTML::_('select.option', $key, $text);
              }
              $options[] = JHTML::_('select.option', '</OPTGROUP>');
              
              $options[] = JHTML::_('select.optgroup', 'Products');
              foreach($products as $key => $text) {
                  $options[] = JHTML::_('select.option', $key, $text);
              }
              $options[] = JHTML::_('select.option', '</OPTGROUP>');
              
              $options[] = JHTML::_('select.optgroup', 'Websites');
              foreach($websites as $key => $text) {
                  $options[] = JHTML::_('select.option', $key, $text);
              }
              $options[] = JHTML::_('select.option', '</OPTGROUP>');
              
              $select = JHTML::_(
               'select.genericlist', // Select element
               $options,             // Options that we created above
               $ctrl,                // The name select element in HTML
               'size="5" ',          // Extra parameters to add for select element
               'value',              // The name of the object variable for the option value
               'text',               // The name of the object variable for the option text
               $value,               // The key that is selected (accepts an array or a string)
               false                 // Flag to translate the option results
              );
      
              return $select;
      	}
      }
      ?>
      

      Read More...
    • Exlude/Separate SVN folders

      Subversion created hidden .svn folders in all the directories to keep track of changes. These folders can become a headache when it comes to copy a project from one directory to another. These folders can also become a security issue. There are many ways solve this problem. 1. Use export feature of Eclipse and it will not export any of the .svn folders. 2. Use copy commands on Win or Linux

      tar --exclude='.svn' -c -f - /path/to/sourcedir/* | (cd /path/to/destdir ; tar xfp -)
      rsync -r --exclude=.svn /home/user/progname/ /home/user/progname.copy
      
      3. Robocopy 4. Ignore files and folders from repository

      Read More...
    • Finding Domain Name from URL in PHP

      Following are various functions to find domain name in URL using PHP.

      function getDomain( $inputURL ) {
      $arrayURL = explode( '.', $inputURL );
      $i = count( $arrayURL ) - 1;
      if( strlen( $arrayURL[ $i ] ) <= 2 && strlen( $arrayURL[ $i - 1 ] ) &lt= 2 ) {
      $cleanURL = $arrayURL[ $i - 2 ] . '.' .$arrayURL[ $i - 1 ] . '.' . $arrayURL[ $i ];
      } else {
      $cleanURL = $arrayURL[ $i - 1 ] . '.' . $arrayURL[ $i ];
      }
      return $cleanURL;
      }
      
      Regex Method:
      <?php
      // get host name from URL
      preg_match("/^(http:\/\/)?([^\/]+)/i", "http://www.php.net/index.html", $matches);
      $host = $matches[2];
      // get last two segments of host name
      preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
      echo "domain name is: {$matches[0]}\n";
      /* Output is php.net */
      ?>
      
      

      Read More...
    • Go Back button with Javascript

      JavaScript: Use inline JavaScript to send user back to previous page.

      <input type="button" value="Go Back" onclick="history.back(-1)" />
      Can also send user two steps back as well.
      <input type="button" value="Go Back" onclick="history.back(-2)" />
      PHP: PHP code to send user back.
      <?php
        $url = htmlspecialchars($_SERVER['HTTP_REFERER']);
        echo "<a href='$url'>back</a>";
      ?>
      

      Read More...
    • GPL issues for Joomla extensions

      GPL guidelines for submitting extensions to Joomla Extensions Directory(JED). 1- PHP files: 1A- Notice at the top of each php file stating that it is distributed under the terms of the GPL (see http://www.fsf.org/licensing/licenses/gpl-howto.html for details) 1B- Copyright notice at the top of each php file, as in:

      /**
      * @Copyright Copyright (C) 2010- ... author-name
      * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
      **/
      
      2- XML File 2A- a tag in your extension's XML file stating that it is GPL, as in: [xml]<license>GNU/GPL http://www.gnu.org/copyleft/gpl.html</license>[/xml] 2B- a copy of the GPL license with your package (note: this does not need to be installed with the extension, just included with the package as a text file)

      Read More...
    • Hide .svn folders from Appache

      Use following directive in our httpd.conf to prevent Apache from descending into .svn folders.

      # Disallow browsing of Subversion working copy administrative dirs.
      <directorymatch "^/.*/\.svn/">
          Order deny,allow
          Deny from all
      </directorymatch>
      

      Read More...
    • How to calculate distance between two locations

      A very useful function that can be used to calculate distance between two points using latitude and longitude values. $unit parameter can be passed to get return in miles, kilometers, or nautical miles.

      function distance($lat1, $lon1, $lat2, $lon2, $unit) { 
        $theta = $lon1 - $lon2;
        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);
      
        if ($unit == "K") {
          return ($miles * 1.609344);
        } else if ($unit == "N") {
            return ($miles * 0.8684);
          } else {
              return $miles;
            }
      }
      
      How to use:
      //Kilometers
      echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k") . " kilometers";
      
      Another function:
      // ------------------------------------------
      // converts a string with a stret address
      // into a couple of lat, long coordinates.
      // ------------------------------------------
      public function getLatLong($address){
      	if (!is_string($address))die("All Addresses must be passed as a string");
      	$_url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($address));
      	$_result = false;
      	if($_result = file_get_contents($_url)) {
      		if(strpos($_result,'errortips') > 1 || strpos($_result,'Did you mean:') !== false) return false;
      		preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
      		$_coords['lat'] = $_match[1];
      		$_coords['long'] = $_match[2];
      	}
      	return $_coords;
      }
      

      Read More...
    You are here Blog