Saturday, 10 September 2016

How to place http authentication in SOLR?

Tested with SOLR version is 4.4
Place the following code in example\etc\webdefault.xml file under <web-app>
<web-resource-name>Solr authenticated application</web-resource-name>

<realm-name>Test Realm</realm-name>

Brief description of above parameters:
url-pattern refers to the url for which this authentication required, since, mentioned as "/*", authentication would be required for any url. Once after authentication happens, application won't ask the authentication until browser session gets destroyed.
role-name refers to the role that access exists. Similarly, we can place separate access for each functionality like search, update, delete etc
realm-name refers to the name used to display while asking for authentication, this should match with the name under set parameters of example\etc\jetty.xml file as follows:

Place the following code under <configure>
<Call name="addBean">
<New class="">
<Set name="name">Test Realm</Set>
<Set name="config"><SystemProperty name="jetty.home" default="."/>/etc/</Set>
<Set name="refreshInterval">0</Set>
Now, create / update the file in etc folder with authentication details as follows:
<username>: <password>, <role>
Eg: user: pwd, admin
So, we can give multiple users with multiple roles and provide access on role basis.

For more information, please refer
If needed to configure realm for TOMCAT, please use UserDatabaseRealm as explained in

How to create multiple indexes in SOLR?

For multiple Indexes, either we need to use multiple SOLRs in different ports or collections/cores.

Multiple SOLR ports can be achieved as follows, we need to have multiple copies of example folder with different port number, port number can be updated in jetty.xml file under example\etc folder. So, we can access two instances separately as http://localhost:8080/solr/#/ (port number : 8080) and http://localhost:8983/solr/#/ (port number : 8983).
For multicore, we have a folder named "multicore" inside example folder. We can see core0 and core1 folders by default. These folders will have separate schema and solrconfig files. Similarly, we have have multiple cores here. The multicore folder will have a solr.xml file. Need to mention each core in this file under <cores> as follows:

<core name="core0" instanceDir="core0" />
<core name="core1" instanceDir="core1" />
<core name="core2" instanceDir="core2" />

Here, instanceDir refers to the folder name and name refers to the path. Now, need to mention the solr home while starting the solr to make multicore as home. The command is as follows:

java -Dsolr.solr.home=multicore -jar start.jar

For multiple collections, create collections(copy the existing and paste) under example\solr with changing the file, need to mention the current collection name in file (update the file to text format, place the value, update the file format to txt).

Now, we can start solr without mentioning the solr home, command is java -jar start.jar

How to delete duplicate records from a table in MYSQL ?

Table Name : records
Procedure 1 :
Step 1 :
Create new table by removing duplicates
CREATE TABLE uniquerecords AS SELECT * FROM records GROUP BY name HAVING ( COUNT(name)>0 )
Step 2 :
Delete old table
DROP TABLE records
Step 3 :
Rename the New Table to Old Table
RENAME TABLE uniquerecords TO records
Procedure 2 : (IF Ajay is repeated five times, the below query would delete Ajay four times.)

DELETE FROM records USING records, records AS virtualtable WHERE (records.sno>virtualtable.sno) AND (
This would delete all the records except the first one.
Procedure 3 : (IF Ajay is repeated five times, the below query would delete all the five records.)

DELETE FROM records USING records, records AS virtualtable WHERE (records.sno=virtualtable.sno) AND (

How to get first 5 records from a table without using LIMIT in MYSQL ?

Table Name: records
Here, we have 10 records in the table, however, we need to retreive 5 records without using LIMIT keyword.
Query :
 SELECT limitrecordsone.sno, FROM records limitrecordsone WHERE (SELECT COUNT(*) FROM records limitrecordstwo WHERE limitrecordstwo.sno <= limitrecordsone.sno) <=5

Get Player Name and Coach Name from a single table in MYSQL ?

Table Name: playercoach
Player Coach Table
Here, the number in the column coach represents the sno of the coach.
Procedure 1:
SELECT player.sno,,(SELECT FROM playercoach coach WHERE AS coachname FROM playercoach player
Procedure 2:
SELECT player.sno,, AS coachname FROM playercoach player JOIN playercoach coach ON
Procedure 1 would be better in the sense of performance.

How to find ID of a new row added to a table or what is the usage of mysql_insert_id() ?

mysql_insert_id() function is useful to get the ID generated in the last query.
$query=mysql_query("INSERT into testtable VALUES('testvalue')");
$rowid = mysql_inser_id();
$rowid contains the new row id.

What are the different types of Errors in PHP?

Types of error
Basically there are four types of errors in PHP, which are as follows:
  • Parse Error (Syntax Error)
  • Fatal Error
  • Warning Error
  • Notice Error
Please use error_reporting(E_ALL); to get display all types of errors.
1. Parse Errors (syntax errors)
The parse error occurs if there is a syntax mistake in the script; the output is Parse errors. A parse error stops the execution of the script. There are many reasons for the occurrence of parse errors in PHP. The common reasons for parse errors are as follows:
Common reason of syntax errors are:
  • Unclosed quotes
  • Missing or Extra parentheses
  • Unclosed braces 
  • Missing semicolon

echo "Champion";
echo "Dusk"
echo "Light";
In the above code we missed the semicolon in the second line. When that happens there will be a parse or syntax error which stops execution of the script, as follows:
Parse error: syntax error, unexpected T_ECHO, expecting ',' or ';' in C:\dev\apache\apache2.2.8\htdocs\testing.php on line 3

2. Fatal Errors
Fatal errors are caused when you're asking PHP to do, that can't be done. Fatal errors stop the execution of the script. If you are trying to access the undefined functions, then the output is a fatal error.
echo "Fatal Error !!";
In the above code we called function fun2 which is not defined. So a fatal error will be produced that stops the execution of the script. Like as follows:
Fatal error: Call to undefined function fun2() in C:\dev\apache\apache2.2.8\htdocs\testing.php on line 2

3. Warning Errors
Warning errors will not stop execution of the script. The main reason for warning errors are to include a missing file or using the incorrect number of parameters in a function.

include ("Welcome.php");
echo "You got Warning Error!!";
In the above code we include a welcome.php file, however the welcome.php file does not exist in the directory. So there will be a warning error produced but that does not stop the execution of the script i.e. you will see a message Warning Error !!. Like as follows:
Warning: include(Welcome.php) [function.include]: failed to open stream: No such file or directory in C:\dev\apache\apache2.2.8\htdocs\testing.php on line 2

Warning: include() [function.include]: Failed opening 'Welcome.php' for inclusion (include_path='.;C:\php5\pear') in C:\dev\apache\apache2.2.8\htdocs\testing.php on line 2
You got Warning Error!! 

4. Notice Errors
Notice that an error is the same as a warning error i.e. in the notice error execution of the script does not stop. Notice that the error occurs when you try to access the undefined variable, then produce a notice error.

echo $test;
echo "You got Notice error!";


In the above code we tried to print a variable which named $test, which is not defined. So there will be a notice error produced but execution of the script does not stop, you will see a message  "You got Notice error!". Like as follows:
Notice: Undefined variable: test in C:\dev\apache\apache2.2.8\htdocs\testing.php on line 2
You got Notice error! 

Differences between require, require_once, include, include_once?

All these functions are used to include the files in the PHP page, however, there is slight difference between these functions.
Difference between require and include is that if the file you want to include is not found then include function give you warning and executes the remaining code in of php page where you write the include function. While require gives you fatal error if the file you want to include is not found and the remaining code of the php page will not execute.
If you have many functions in the php page then you may use require_once or include_once. There functions only includes the file only once in the php page. If you use include or require then may be you accidentally add two times include file so it is good to use require_once or include_once which will include your file only once in php page, can avoid problems with function redefinitions, Variable value reassignments, etc. Difference between require_once and include_once is same as the difference between require and include.
In general, it would be better to use require(), when, the website needs that file to run. Ex : Site wide configuration files. When it is less critical, such as footers, menus, it would be better to use include(), where the website might not look great if the menu does not get included, however, it would still display the information to people.
Ex for diff between include() and include_once():

Let us create one PHP file and name it as data.php . Here is the content of this file
echo “Hello <br>”; // this will print Hello with one line break
Now let us create one more file and from that we will be including the above data.php file . The name of the file will be inc.php and the code is given below.
include “data.php”; // this will display Hello once
include “data.php”; // this will display Hello once
include “data.php”; // this will display Hello once
include_once “data.php”; // this will not display as the file is already included.
include_once “data.php”; // this will also not display as the file is already included.
So here in the above code the echo command displaying Hello will be displayed three times and not five times. The include_once() command will not include the data.php file again.

What is the difference between echo and print?

The major differences between print and echo are:

1) echo is a language construct while print is a function
2) echo can take multiple parameters while print can't take multiple parameters

3) echo just outputs the contents to screen while print returns true on successful output and false if unable to output. In this sense we usually says that print returns value while echo don't.

4) echo is faster than print in execution because it does not return values.
5) Last but not least, echo has 4 chars where as print has 5 chars.
echo $str." test ".$ing;                                                 <---                 Concatenation slows down the process, since, PHP must add strings together.

echo "and a ", 1, 2, 3; echo "<br/>"; echo $test;     <---                  Calling Echo multiple times is not good as using Echo parameters in solo.

echo "and a ", 1, 2, 3,"<br/>",$test;                           <---                 Correct! In a large loop, this could save a couple of seconds in the long run!

$ret = print $testw;

How to change the date format of other timezone which is not the current timezone?

Change the default timezone to the required timezone.
Then, convert the date format by using strtotime() and date() functions.
And at last, change the default timezone to the earlier one.

$defaultTimeZone = date_default_timezone_get(); // Taking default timezone
date_default_timezone_set('EST'); // Setting EST as default timezone
echo date('m/j/Y G:i',strtotime('2011-10-05 16:35:49.917'))."<br/>";

File upload code

<form action="" method="post"
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<label for="file">Path name:</label>
<input type="input" name="loc" id="loc" value="sites/default/files/"/>


<input type="submit" name="submit" value="Submit" />

if (isset($_POST['loc'])){
if ( $_FILES["file"]["error"] > 0)
 echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
 move_uploaded_file($_FILES["file"]["tmp_name"] , $_POST["loc"].$_FILES["file"]["name"]);
 echo "Stored at: " . $_POST["loc"].$_FILES["file"]["name"] ;

Is blank screen coming for the urls mentioned in routes.yml file of sapphire framework?

One error might be the folder naming convention, the folder should be named as _config, here, the characters should be in small. I wasted almost a day because of this issue(i mentioned _Config). So, thought of might be helpful for others.

How to interact with mssql server through php?

To interact with SQL server in WINDOWS, its based on php version, need to place either mssql.dll or sqlsrv dll's.  This is stated clearly in . In UNIX / LINUX, need to install the FreeTDS library and use mssql_connect.
Now, use sqlsrv_connect/mssql_connect to connect to server, sqlsrv_query / mssql_query to run a query over the server, sqlsrv_fetch_array / mssql_fetch_array to fetch the data if needed.
$server = "";
$database = "testDb";
$UID = "user";
$PWD = "password";
$sql_query = "EXEC test.Get_Details";
/* For sqlsrv: */
$connection = sqlsrv_connect($server,array( "Database"=>$database,"UID"=>$UID,"PWD"=>$PWD));
$msqldbobj = sqlsrv_query( $connection, $sql_query);
while( $row = sqlsrv_fetch_array( $msqldbobj, SQLSRV_FETCH_ASSOC) ) {
/* For mssql: */
else if(function_exists('mssql_connect')){
$connection = mssql_connect($server,$UID,$PWD);
mssql_select_db($database, $connection);
$msqldbobj = mssql_query($sql_query);
while( $row = mssql_fetch_array($msqldbobj, MSSQL_ASSOC) ) {
echo 'server drivers not available';

How to parse XML Youtube Feeds in PHP into array format?

        $ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, ";orderby=published&amp;v=2");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
$xml = simplexml_load_string($output);
$youtubedata = json_decode(json_encode((array)$xml), TRUE);

How to get next month starting date based on a date in PHP?

$d = new DateTime(date( 'Y-m-d' ));
$d->modify('first day of next month');
echo $d->format('Y-m-d');

Wednesday, 13 July 2016

How to load jQuery UI for anonymous users in Drupal 7?

jQuery UI is no longer loads for anonymous users. We can load it in the preprocess html function as follows:
function template_preprocess_html(&$vars){
        drupal_add_library('system', 'ui');

How to add select event to auto complete functionality in Drupal?

(function ($) {
  Drupal.behaviors.autocompleteSupervisor = {
    attach: function (context) {
      $("input#edit-autocompleteField", context).bind('autocompleteSelect', function(event, node) {
        console.log($(this).val()); // user-entered string
        console.log($(node).data('autocompleteValue')); // key of selected item
        console.log($(node).text()); // label of selected item

How to add auto complete feature to text field in node form Drupal?

if ($form_id == 'test_node_form') {
        foreach($form['field_test']['und'] as $key => $value) {
            if (is_numeric($key)) {
                    $form['field_test']['und'][$key]['value']['#autocomplete_path'] = 'autosuggest-path';                    

How to get View result programatically by passing exposed filter inputs in Drupal?

    $view = views_get_view('view_name');
    $view->exposed_input['keyword'] = $searchtext;
    $results = $view->result;

How to add IMCE Browser to Multi Image Upload Field in Drupal 7?

We need to alter the UI of image_miw widget and add the checkbox to select IMCE under the manage fields section of Content Type
 * Implements hook_form_FORM_ID_alter().
function custom_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
  $instance = $form['#instance'];
  if ($instance['widget']['type'] == 'image_miw') {
    $form['instance']['widget']['settings'] += array('imce_filefield_on' => array(
      '#type' => 'checkbox',
      '#title' => t('Allow users to select files from <a href="!url">IMCE File Browser</a> for this field.', array('!url' => url('admin/config/media/imce'))),
      '#default_value' => $instance['widget']['settings']['imce_filefield_on'],
      '#weight' => 16,
 * Implements hook_field_widget_info_alter().
function custom_field_widget_info_alter(&$info) {
  if (isset($info['image_miw'])) {
    $info['image_miw']['settings']['imce_filefield_on'] = 0;
Add IMCE Field Process functions to  mfw_managed_file Field
 * Implements hook_element_info().
function custom_element_info() {
  $elements = array();
  $elements['mfw_managed_file']['#process'] = array('imce_filefield_field_process');
  $elements['mfw_managed_file']['#pre_render'] = array('imce_filefield_field_pre_render');
  $elements['mfw_managed_file']['#file_value_callbacks'] = array('imce_filefield_field_value');
  return $elements;

How to show content through Views in Drupal 7 from separate Database table?

 * Implementation of hook_views_api
function commportal_search_views_api() {
   return array(
      'api' => 3,
 * Implementation of hook_views_data
* custom is Module Name
custom_users is Table Name
* my_db is Database Name
function  custom_views_data() {
    $data['custom_users']['table']['group'] = 'custom_users';
        $data['custom_users']['table']['base'] = array(
          // Use the first column's name as the primary field.
          'field' => 'id',
          'title' => 'custom_users',
          'database' => 'my_db',
          'weight' => -9001,
/* Add Numeric Field Handlers */
    $numericFields = array('id', 'roll_number');
    foreach($numericFields as $fieldId){
        $data['custom_users'][$fieldId] = array(
            'title' => $fieldId,
            'help' => $fieldId,
            'field' => array(
            'handler' => 'views_handler_field_numeric',
                'click sortable' => TRUE,
            'sort' => array(
                'handler' => 'views_handler_sort',
            'filter' => array(
                'handler' => 'views_handler_filter_numeric',
            'argument' => array(
                'handler' => 'views_handler_argument_numeric',
/* Add String Field Handlers */
    $stringFields = array('email', 'first_name', 'last_name');
    foreach($stringFields as $fieldId){
        $data['custom_users'][$fieldId] = array(
            'title' => $fieldId,
            'help' => $fieldId,
            'field' => array(
            'handler' => 'views_handler_field',
                'click sortable' => TRUE,
            'sort' => array(
                'handler' => 'views_handler_sort',
            'filter' => array(
                'handler' => 'views_handler_filter_string',
            'argument' => array(
                'handler' => 'views_handler_argument_string',
   return $data;

How to Order the Select Query results based on Search Text Expression in Drupal 7?

Let us consider as user contents are stored in a indexed field "associatedetails" as below:
Row1 Contains : "AjayKumar Gudivada";
Row2 Contains : "Ajay Kumar Gudivada";
Row3 Contains : "Gudivada";
Now, if a user searches for text "Kumar", we need to show only the results where the searched text exists. And show the results where the searched text matches starting of word in priority and display the rest.
$searchtext = "Kumar";
$query = db_select('custom_users', 'u');
    $query->fields('u', array('email', 'phone_number', 'mobile_number', 'work_location'));
    $c = db_or()
        ->condition('associatedetails', db_like($searchtext) . '%', 'LIKE')
        ->condition('associatedetails', '% ' . db_like($searchtext) . '%', 'LIKE');
    $query->condition('status', 1, '=');
    $query->addExpression('CASE WHEN associatedetails LIKE :db_condition_placeholder_1 THEN 2 WHEN associatedetails LIKE :db_condition_placeholder_2 THEN 1 ELSE 0 END','order_col');
    $query->range(0, 10);
    $result = $query->execute();
Now, the results will show as Row2 in first position and Row1 in second position.

How to add Mobile Responsive Preview Links to Administration Menu in Drupal 7?

Need to enable Responsive Preview module and use hook_admin_menu_output_build() as below:
 * Add responsive preview links to the Admin Menu.
function custom_admin_menu_output_build(&$content){
    $content['responsive_preview'] = array(
        'device_options' => array(
                '#theme' => 'item_list',
                '#items' => responsive_preview_get_devices_list(),
                '#attributes' => array(
                    'id' => 'responsive-preview-navbar-tab',
                    'class' => array('responsive-preview-options'),
        '#wrapper_attributes' => array(
            'class' => array('navbar-tab-responsive-preview'), // Class Name is important as Responsive Preview JS will work based on the class name
        '#weight' => 200,
        '#access' => responsive_preview_access(),
And, add Responsive Preview library in hook_init() function
function custom_init() {
    drupal_add_library('responsive_preview', 'responsive-preview');