Skip to main content

Posts

Joomla validate chrono forms using jquery

It is a common practice to use Chrono forms in our joomla site to setup various forms in the site, be it a contact us form, submit a ticket form, or whatever. I have set the option "validate form" to "No" under chronoform settings in admin panel, and also preferred to not include any js or css files. For validating the chrono forms, i prefer jquery. So first lets add jquery support in our joomla. It is quite simple: 1. Download jquery.js and jquery_min.js (1.4.2 version is enough) and place them in media/system/js folder of your joomla. 2. Edit libraries->joomla->html->html->behavior.php, and add the following function below the mootools() function: function jQuery($debug = null)     {         static $loaded;         global $mainframe;         // Only load once         if ($loaded) {    ...

css link remove dotted outline

Its quite awkward to look at the link, when it is clicked and the dotted outline appears on it. To overcome it, just add the following line to your css file: a { outline: 0; } For example, to remove the dotted outline for the menu links on your page, add this to your css: #navigation li a {    outline: 0; } ( Assuming you have this menu structure: <ul id="navigation"><li><a href="news.html">News</a></li></ul> )

Javascript get array key from value

This is an example function that can search for a key in a javascript array and return it... function check(v) {     var x = new Array();     x = { a: '1', b: '2', c: '3' };         for(var key in x)     {         if(x[key] == v)         console.log(key);     } } Test: check(2);   // b

joomla remove category name in url

-) If anyone is using the lyftenbloggie component, and want to remove the component name and category title from the sef url, follow this hack: (Note: You also need to install the lyftenbloggie extension for ARTIO SEF) Under components/com_sef/joomsef.php, After this code: $location = array();         foreach ($title as $titlePart) {             if (strlen($titlePart) == 0) continue;             $location[] = JoomSEF::_titleToLocation($titlePart);         } Just add this code: if($location[0] == 'lyftenbloggie')         {         $temp_sef = end($location);         $location = array();            $location[] = $temp_sef;         ...

php read file line by line, write file line by line

The following code is an example to write to a file line-by-line: if(file_exists("files/john") && is_dir("files/john")) $myFile = "files/john/msg.txt"; else { mkdir("files/john"); $myFile = "files/john/msg.txt"; } $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = date("d-M-Y H:i:s").' : '.trim($_POST['msg']); fwrite($fh, $stringData." "); fclose($fh); Read a file line-by-line: $filename = "test.txt"; $fp = fopen( $filename, "r" ) or die("Couldn't open $filename"); while ( ! feof( $fp ) ) {    $line = fgets( $fp, 1024 );    print "$line<br>"; }

htaccess disable directory browsing, disable file listing, disable file access

There may be some personal or secure data in a file, that you want to hide from the end user, when it is viewed through a web browser. Ex: http://www.example.com/user_files/24/chat.txt In the above scenario, if the file "chat.txt" contains a secure data, and you dont want to allow end users to directly access the file, or to disable the file listing in the folder "user_files" or "24", use the below code in your .htaccess file inside "user_files" folder: Options -Indexes order allow,deny deny from all

PHP get, set and convert Timezone

Set the timezone for the script: define('TIMEZONE', 'Asia/Calcutta'); // INDIA date_default_timezone_set(TIMEZONE); Get the default (script) timezone: date_default_timezone_get(); Get ini set timezone: ini_get('date.timezone'); Get timezone name: date("T"); Set timezone example: date_default_timezone_set('Europe/London'); // GMT GMT to IST conversion example: $event_length = 330; // IST is 5:30 ahead of GMT, so add 330 minutes $timestamp = strtotime(date("H:i:s")); $etime = strtotime("+$event_length minutes", $timestamp); $ist_time = date('H:i:s', $etime); echo '<br>'.'GMT - IST: '.$ist_time;

Parsing json data

HTML code: <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> function get_json() {     $.post('json.php', function(data) {       var resp = eval('(' + data + ')');       var msg = resp.fruits;       console.log(msg);          alert(msg.letter+': '+msg.name);     }); } </script> </head> <body> <div style="margin:10px;" align="left"> <a href="javascript:void(0);" onclick="get_json();">Get Json response</a> </div> </body> PHP code: <?php echo json_encode(array('fruits'=>array('letter'=>'a', 'name'=>'apple'))); ?>

Mysql join examples

1. Inner join: Sample Fields in "person" table:  id, email, password, firstname, lastname Sample Fields in "personprofile" table: person_id, age, dob, city, country, phone, mobile Query: select * from person inner join `personprofile` on person.id=personprofile.person_id and person.id=9; 2.  Left join: Sample fields in "employee" table: emp_id (primary), name, active Sample fields in "online" table: id (primary), user_id (references emp_id), online Query: SELECT *  FROM employee e left join online o on e.emp_id = o.user_id where e.active=1; Note the use of "where" in the above query, instead of normal "and". It will give the accurate results.

Different ways of parsing xml data

Here i show the example for parsing xml data, using jquery, javascript and php. Here is a sample xml file, we are using, msg.xml: <messages>     <message>     <name>Sam</name>        <msg>Hi Anna</msg>     </message>     <message>     <name>Kelly</name>     <msg>Hi Anna</msg>     </message>     <message>     <name>Sam</name>     <msg>Hi Anna</msg>     </message>     <message>     <name>Sam</name>     <msg>Hello Anna</msg>     </message>     <message>     <name>Kelly</name>     <msg>Anna</msg> ...

Joomla ARTIO SEF set default Itemid for new posts

A small hack to set the default Itemid for new posts added into the admin panel can be done at 2 places in the file:  components/com_sef/joomsef.php Line: 1462                     if (isset($Itemid) && ($Itemid != '')) {                         $col = ', `Itemid`';                         $val = ", '171'";                      // Itemid of the menu item, which is included for almost all modules in our site                     } Line: 1567  ...

Joomla jquery conflicts

Sometimes, we face certain jquery conflicts in Joomla. These can be avoided by using jQuery instead of $ in your code. For example, instead of: $(function() {         $( "#tabs" ).tabs();     }); Use this: jQuery(function() {         jQuery( "#tabs" ).tabs();     }); And in your template index (or head includes script file), add a js file (noconflict.js) with just this content: jQuery.noConflict(); For example: $this->addScript($this->baseurl."/templates/".$this->template."/js/jquery-1.7.1.js"); $this->addScript($this->baseurl."/templates/".$this->template."/js/noconflict.js");

Joomla redirection

Example of URL Redirection in joomla: Suppose the user visits our component view page without logging in. Then we want to force the user to login page (if he is not already logged in) and then redirect back to our page after logging in, and show a custom logout button. This is a sample code in our component view: <?php $user =& JFactory::getUser(); global $mainframe; if($user->id == 0) { $return_url = 'index.php?option=com_comments'; $return_url = urlencode(base64_encode($return_url)); $redirect_url = '&return='.$return_url; $login_url = 'index.php?option=com_user&view=login'; $finalUrl = $login_url . $redirect_url; $mainframe->redirect( $finalUrl, 'Please login or register before you post comment' ); } else {  ?> <table width="800"> <tr><td><?php echo 'Welcome <b>'.$user->name; ?></b></td> <td align="right"> <form id="l...

Detecting the flash player version

If a user is using a browser with a flash player that is not upgraded, we can show him a message to upgrade his flash player.... using the swfobject javascript. The below code can show the upgrade message over the video, which is run using the jwplayer. <html> <head> <script type='text/javascript' src='jwplayer.js'></script> <script type="text/javascript" src="swfobject.js"></script> </head> <body> <div id="video_player"></div> <script type="text/javascript">     var so = new SWFObject('player.swf','flashContent','280','240','11');     so.useExpressInstall('expressInstall.swf');     so.addParam('allowfullscreen','true');     so.addParam('allowscriptaccess','always');     so.addParam('bgcolor','#FFFFFF');     so.addParam('allowfullscreen','true...

php debugging

The simplest way to debug our php code is to write the data to a log file. For example, this code prints an array to a text file.... <?php $myFile = "logFile.txt"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = '';                foreach($elem as $k=>$v) $stringData .= $k.'=>'.$v."\n";                fwrite($fh, $stringData); fclose($fh); ?> Dont forget to view the file in its stored location...

php array to xml example

This is an example of generating an xml output format from the database. This code is creating a sample rss feed from the joomla articles (which can be added to a rss.xml file). <?php     $dbhost = "localhost";     $dbuser = "root";     $dbpass = "";     $dbname = "joomla";     mysql_connect($dbhost,$dbuser,$dbpass);     mysql_select_db($dbname);     mysql_query("SET NAMES 'utf8'"); // to get proper format         $sql = "SELECT id, title, alias, title_alias, metadesc FROM `jos_content`     where catid=12 limit 3";     $q   = mysql_query($sql) or die(mysql_error());     $xml = "";     while($r = mysql_fetch_array($q)){       $xml .= "<item>";       $xml .= "<title>".trim($r['title'])."</title>";  ...

php validate image type

You can validate image in php, this way: <?php     $img = "banner.gif"; // an image     $info = getimagesize($img);     print image_type_to_mime_type($info[2]); ?> The outout will generally be: image/jpeg or image/gif or image/png But if it is: application/octet-stream, then the file is not an image.

Interview questions

These are some of the php and mysql interview questions i faced: > difference between HAVING and WHERE clause in mysql > how can you interchange the genders of male and female in a mysql table having the column gender with values 'male' and 'female' (refer: http://stackoverflow.com/questions/8400617/mysql-replace-values-in-a-table ) > What is the use of singleton class in php

How to edit php.ini in the cpanel

It is often required to change some settings in the php configuration of our site. If you have access to the cpanel of your hosting provider, then the below steps can help you in modifying the settings in php.ini file..... (Note: these steps are specific to hostmonster) Step 1- Login into your cPanel. Step 2- Under the Software/Services category, click on the PHP Config icon. Step 3- In this screen, there is a section called Install Default php.ini. Under that section, please check mark the "IonCube" and the "SourceGuardian" check boxes (Many commercial php scripts need these turned on - if you think your script may not require the IonCube or SourceGuardian packages, it is okay to not check mark the boxes - but it will not hurt anything to check mark both boxes.). Step 4- Under the same section, click the "INSTALL PHP.INI MASTER FILE" button. Step 5- You have just successfully installed the "php.ini.default" file . But the next step is to r...

Mysql queries (complex)

Scenario-1 : Using the count or sum with inner join query Table structures: videos: id, title, description, date_uploaded categories: id, category_name votes: id, videoid, vote, date (vote will range between 1 and 5) Query: SELECT v.id as vid, v.title, v.description, v.date_uploaded, c.category_name, v2.total, v2.count FROM videos v inner join categories c inner join (select videoid, sum(vote) as total, count(*) as count from votes group by videoid) v2 on v.category_id=c.id and v2.videoid=v.id and v.featured=1 and v.published=1 order by v.date_uploaded desc; Resultset: vid  title  description    date_uploaded            id    category_name   total  count 12   Ford   inauguration 2011-10-07 01:08:22    3    Inauguration        97     31 9     Nano   n...