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>
<security-constraint>
<web-resource-collection>
<web-resource-name>Solr authenticated application</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>

<login-config>
<auth-method>BASIC</auth-method>
<realm-name>Test Realm</realm-name>
</login-config>

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">
<Arg>
<New class="org.eclipse.jetty.security.HashLoginService">
<Set name="name">Test Realm</Set>
<Set name="config"><SystemProperty name="jetty.home" default="."/>/etc/realm.properties</Set>
<Set name="refreshInterval">0</Set>
</New>
</Arg>
</Call>
Now, create / update the realm.properties 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 http://wiki.apache.org/solr/SolrSecurity
If needed to configure realm for TOMCAT, please use UserDatabaseRealm as explained in http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html

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 core.properties file, need to mention the current collection name in core.properties 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.)
QUERY :

DELETE FROM records USING records, records AS virtualtable WHERE (records.sno>virtualtable.sno) AND (records.name=virtualtable.name)
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.)
QUERY :

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

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,limitrecordsone.name FROM records limitrecordsone WHERE (SELECT COUNT(*) FROM records limitrecordstwo WHERE limitrecordstwo.sno <= limitrecordsone.sno) <=5
OUTPUT:

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,player.name,(SELECT coach.name FROM playercoach coach WHERE coach.sno=player.coach) AS coachname FROM playercoach player
Procedure 2:
SELECT player.sno,player.name,coach.name AS coachname FROM playercoach player JOIN playercoach coach ON coach.sno=player.coach
Output:
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.
<?php
$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
Example

<?php
echo "Champion";
echo "Dusk"
echo "Light";
?>
Output:
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.
Example
<?php
fun2();
echo "Fatal Error !!";
?>
Output:
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.
Example

<?php 
include ("Welcome.php");
echo "You got Warning Error!!";
?>
Output:
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.
Example

<?php 
echo $test;
echo "You got Notice error!";
?>

Output:

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.
Ex:
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/>";
date_default_timezone_set('UTC');

File upload code


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

<p>

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

<?php
if (isset($_POST['loc'])){
if ( $_FILES["file"]["error"] > 0)
{
 echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
 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 http://in1.php.net/manual/en/mssql.requirements.php . 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.
Examples:
$server = "xxx.xx.xx.xxx";
$database = "testDb";
$UID = "user";
$PWD = "password";
$sql_query = "EXEC test.Get_Details";
/* For sqlsrv: */
if(function_exists('sqlsrv_connect')){
$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) ) {
            print_r($row);
       }
}
/* 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) ) {
            print_r($row);
       }
}else{
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, "gdata.youtube.com/feeds/api/playlists/PL802BE7047AA4DE0E?max-results=50&amp;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
curl_close($ch);
$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');