How to encode base64 in jQuery ?

Encode base64 in jQuery –
btoa() function is used for it.
For Example –
var str = ‘Hello’;
var encrypted_str = btoa (str);
alert( encrypted_str );

Output – SGVsbG8=

For more related queries, please VISIT.

In case, if you did not find your solution or have any query/question, please contact us.

Copy files to other server(ftp)

How to copy all files of a directory to a directory on other server ?
Suppose, we have to copy all files in a directory(dir/subdir) to other server directory(dir/sub) and we also have to create directory there(in case, if directory does not exist), then –

First of all make connection with Remote(other) FTP (from where we are copying the files) like –
$ftp_host = ‘host’;
$ftp_username = ‘ftp_username’;
$ftp_password = ‘ftp_password’;
$ftp_connection = ftp_connect($ftp_host);

Then, login to Remote or other ftp using –
$ftp_login = ftp_login($ftp_connection,$ftp_username,$ftp_password);

function isdir_ftp($ftp_connection,$dir){
$pushed = ftp_pwd($ftp_connection);
if($pushed!=false && @ftp_chdir($ftp_connection,$dir)){
ftp_chdir($ftp, $pushed);
return true;
}
return false;
}

Suppose, we have to copy the directory and files in public_html directory –
$server_path = “./public_html/”;
$file_path_server = “dir/subdir” ;
$server_file_path = $server_path. $file_path_server ;
$is_dir = isdir_ftp($ftp_connection, $file_path_server);
if(!$is_dir){
$dir = $file_path_server;
$dd = ”;
$d=explode(“,”,$dir);
for($i=0;$i<count($d);$i++){
$dd.=$d[$i].”/”;
//try to create dir
$dir = $dd;
$is_dir = isdir_ftp($ftp_connection, $dir);
if(!$is_dir){
if(ftp_mkdir($frp_connection, $dir)){
echo “Dir created successfully”;
}else{
echo “Error”;
}
}
}
}

Now read the files from local ftp from where we have to copy the files and the copy it –
$local_ftp_dir = ” dir/subdir “;
if ($handle = @opendir($ local_ftp_dir )) {
while (false !== ($file = readdir($handle))) {
if ($file != “.” && $file != “..”) {
$source= $ local_ftp_dir .’/’.$file;
$dest = “public_html/”.$ local_ftp_dir .’/’.$file;
$upload = ftp_put($ftp_connection, $dest, $source, FTP_BINARY);
if (!$upload) {
echo ‘FTP upload failed!’;
} else {
echo “uploaded successfully”;
}
}
}
}

ftp_close($ftp_connection);

 

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.
 

Copy files from other ftp or server to current ftp or server

Steps to copy all files of a particular folder from other ftp to current ftp –

First of all make connection with Remote(other) FTP (from where we are copying the files) like –
$ftp_host = ‘host’;
$ftp_username = ‘ftp_username’;
$ftp_password = ‘ftp_password’;
$ftp_connection = ftp_connect($ftp_host);

Then, login to Remote or other ftp using –
$ftp_login = ftp_login($ftp_connection,$ftp_username,$ftp_password);

After that get all files of that directory of remote ftp –
$remote_dir = ‘/dir/’;
$remote_files = ftp_nlist($ftp_connection,$remote_dir); //Array of all files from dir directory on remote server

Then, check that file exists in that directory on not –
if(count($remote_files)>0){ //There are files in remote server dir
foreach($remote_files as $remote_file){ //run loop through each file
$file_name = end(“/”,explode($remote_file)); //get file name from remote
$local_file = ‘local_dir/’.$file_name;
$server_file = $remote_file; //file from remote server
if(ftp_get($ftp_connection,$local_file,$server_file, FTP_ASCII)){
echo “File successfully copied”;
}else{
echo “error”;
}
}
}

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.
 

JQuery / Javascript Interview Questions

Ques: What is difference between setInterval () and setTimeout () ?

Ans: setInterval(expression, time) – It will run the code or function in the time interval.
Example –
setInterval(function(){ alert(“Hello”); }, 1000);
This will alert “Hello” after every 1 second(1000 milliseconds).

setTimeout() – It will run after the time.
Example –
setTimeout(function(){ alert(“Hello”); }, 1000);
This will alert “Hello” once only after 1 second(1000 milliseconds).

Ques: When will be the fourth argument to open() function ?

Ans: When the second argument named as existing window.

 

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.
 

MySQL Interview Questions

Ques: What is difference between VARCHAR and TEXT ?

Ans: Indexing can not be done on TEXT column. So if you have to index, you have to use VARCHAR as type.

Ques: What is size of INT and TINYINT ?

Ans: INT Size – 4 bytes
TINYINT Size – 1 byte

Ques: What is stored procedure ?

Ans: It is a segment of SQL statements stored in MySQL Server. After creating stored procedure, you can directly call it via CALL() function.

Syntax –
CREATE PROCEDURE procedure_name (parameter)
BEGIN
statements
END //

Calling –
CALL procedure_name(arguments);

For example –
Query – Select * from users. – This query will get data of all users.
Create Stored Procedure of it –
DELIMITER //
CREATE PROCEDURE Getallusers()
BEGIN
SELECT * FROM users;
END //
DELIMITER;

To call it –
CALL Getallusers ();

Ques: Write a query to get 3rd highest salary without using limit and offset.

Ans: SELECT name. salary from employee e1 where n-1 = (SELECT COUNT(DISTINCT salary) from employee e2 WHERE e2.salary > e1.salary);

Replace n with highest salaray. In above question to find the 3rd highest salary query wiil be –
SELECT name. salary from employee e1 where 3-1 = (SELECT COUNT(DISTINCT salary) from employee e2 WHERE e2.salary > e1.salary);

Ques: Write a single query to delete duplicate rows ?

Ans: DELETE t1 from table t1 INNER JOIN table t2 WHERE t1.primary_key_column > t2. primary_key_column and t1.duplicate_column_name = t2.duplicate_column_name ;

For Example – We have users table in which some users info. is stored(i.e, ID (Primary Key), Name and Address).

ID (Primary Key) Name Email ID Address
1 Ram test@gmail.com India
2 Shyam test@gmail.com India
3 Bunty bunty@gmail.com India
4 Joni bunty@gmail.com India

Query to deleted duplicate email ids(except one) will be –

DELETE u1 from users u1 INNER JOIN users u2 WHERE u1.ID>u2. ID and u1.email_id = t2.email_id ;

Ques: What is default size of MySQL Database ?

Ans: 256 TB

Ques: Tell about GROUP_CONCAT function.

Ans: GROUP_CONCAT function combines(concatenates) the data of multiple rows in a single row. Let us take an example for explanation –

There is a table say customers table.

ID (Primary Key) Name Email ID Address
1 Ram test@gmail.com Australia
2 Ram test@gmail.com India
3 Bunty bunty@gmail.com India
4 Joni joni@gmail.com India
ID (Primary Key) Name Email ID Address
1 Ram test@gmail.com Australia, India
3 Bunty bunty@gmail.com India
4 Joni joni@gmail.com India

By default GORUP_CONCAT will add comma(,) as separator between the values. To use the different syntax like(;), you have to use SEPARATOR with separator syntax.

SELECT Name, Email, GROUP_CONCAT(DISTINCT Address SEPARATOR ‘;’) from customers.

Output –

ID (Primary Key) Name Email ID Address
1 Ram test@gmail.com Australia; India
3 Bunty bunty@gmail.com India
4 Joni joni@gmail.com India
Ques: Tell about DUPLICATE ON in MySQL.

Ans: Duplicate On is mostly used with the unique key.  For example, if we have unique key in the table and after that if we will insert the same reocrd, MySQL will give error.

For example – There is a table users with email as unqiue id.

ID (Primary Key) Name Email ID Address
1 Ram test@gmail.com India
2 Bunty bunty@gmail.com India

If we try to insert the record again with email id test@gmail.com, it will give error. 

To prevent error –

INSERT into users(Name, email, address) VALUES(‘test@gmail.com’) ON DUPLICATE KEY UPDATE email = ‘test_old@gmail.com’ ;

Ques: What is difference between MyISAM and InnoDB ?

Ans: 1.) InnoDB supports transactions while MyISAM does not.
2.) InnoDB has row-level locking while MyISAM has table-locking.
3.) MyISAM supports FULLTEXT Index while InnoDB does not.
4.) Performance speed of InnoDB is less as compared to MyISAM.
5.) InnoDB supports FOREIGN KEY constraints while MyISAM does not.

MyISAM is best for small projects but InnoDB is better option when you have to deal with large database as it supports transactions.

Ques: Write a query to update gender which are male to female and female to male.

Ans: Query –
UPDATE users SET gender = CASE WHEN gender = ‘male’ THEN ‘female’ WHEN gender = ‘female’ THEN ‘male’ ELSE ” END;

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.
 

SELECT Name, Email, GROUP_CONCAT(DISTINCT Address) from customers.

Output –

ID (Primary Key) Name Email ID Address
1 Ram test@gmail.com Australia, India
3 Bunty bunty@gmail.com India
4 Joni joni@gmail.com India

By default GORUP_CONCAT will add comma(,) as separator between the values. To use the different syntax like(;), you have to use SEPARATOR with separator syntax.

SELECT Name, Email, GROUP_CONCAT(DISTINCT Address SEPARATOR ‘;’) from customers.

Output –

ID (Primary Key) Name Email ID Address
1 Ram test@gmail.com Australia; India
3 Bunty bunty@gmail.com India
4 Joni joni@gmail.com India
Ques: Tell about DUPLICATE ON in MySQL.

Ans: Duplicate On is mostly used with the unique key.  For example, if we have unique key in the table and after that if we will insert the same reocrd, MySQL will give error.

For example – There is a table users with email as unqiue id.

ID (Primary Key) Name Email ID Address
1 Ram test@gmail.com India
2 Bunty bunty@gmail.com India

If we try to insert the record again with email id test@gmail.com, it will give error. 

To prevent error –

INSERT into users(Name, email, address) VALUES(‘test@gmail.com’) ON DUPLICATE KEY UPDATE email = ‘test_old@gmail.com’ ;

Ques: What is difference between MyISAM and InnoDB ?

Ans: 1.) InnoDB supports transactions while MyISAM does not.
2.) InnoDB has row-level locking while MyISAM has table-locking.
3.) MyISAM supports FULLTEXT Index while InnoDB does not.
4.) Performance speed of InnoDB is less as compared to MyISAM.
5.) InnoDB supports FOREIGN KEY constraints while MyISAM does not.

MyISAM is best for small projects but InnoDB is better option when you have to deal with large database as it supports transactions.

Ques: Write a query to update gender which are male to female and female to male.

Ans: Query –
UPDATE users SET gender = CASE WHEN gender = ‘male’ THEN ‘female’ WHEN gender = ‘female’ THEN ‘male’ ELSE ” END;

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.
 

PHP(Basic and OOPS) Interview Questions

Are you preparing for PHP Interview ? Whether you are a fresher or experienced, confidence is checked. Here are some questions for you ..

Ques: How to create object without class ?

Ans: You can create it by using empty class. You can use PHP stdClass (which is empty class in PHP) to create its object. It is useful if you are creating dynamic object or if you want to set some dynamic property.

For example –
$object = new stdClass();
$object->name = ‘test’;

Ques: What is armstrong number ? Write a program to check whether the number is armstrong or not.

Ans: Armstrong Number –
It is a number such that the sum of cube of each digit is equal to the number. For example – 153 is an armstrong number because sum of cube of each digit(1*1*1+5*5*5+3*3*3) is 153 which is same as number.

Program –
$n = 153; $sum = 0; $tmp = $n;
while($tmp!=0){
$rem = $tmp%10;
$sum = $sum+($rem*$rem*$rem);
$tmp=$tmp/10;
}
if($n==$sum) {
echo “It is armstrong number”;
}
else {
echo “Not an armstrong number”;
}

Ques: What is difference between object and array ?

Ans: Array is a collection of heterogeneous data(they may be with key value pair or without key value pair) and object is collection of key value pair.

Ques: What will be the output of following :
$a = 1;
foreach($a as $b){
echo $b;
}

Ans: It will give error because foreach works on Array not on string.

Ques: Write a program to find the missing number from an array of number from 1 to 99(There is not empty value if number is missing).
array(1,2,3,4,5,………..,99);

Ans: $array = array(1,2,3,4,5,……….,99);
for($i=0;$i<count($array)-1;$i++){
if($array[$i+1]!=$array[$i]+1){
$missing_number = $array[$i]+1;
echo “Missing Number is “.$missing_number;
}
}

Ques: Can we use session without cookies in PHP ?

Ans: Yes, in PHP, Session can be used without Cookies.
Way to use Session without Cookie –
There are two ways to do it –
1.) For a HTML form, PHP will add a hidden input whose name will be PHPSESSID. The value of PHPSESSID will be based on what PHP assigns to your session ID.
For Example –
<form>
<input type=”hidden” name=” PHPSESSID” value=”12345678″>
</form>
So, when form will be submitted, PHP will get Session id value from form and will get information about session.
2.) PHP will look for all links in HTML, and will modify them and will append PHPSESSID with them.
For Example –
<a href=”http:www.example.com”>Test</a>
PHP will change it to –
<a href=”http:www.example.com? PHPSESSID =12345678″>Test</a>

Ques: Write a program to show duplicate values in array and find the sum between duplicate values.
array(1,2,3,2,5,4,7,5,8).
Output – Duplicate Values are 2,5.
2+3+2 = 7
5+4+7+5 = 21

Ans:Program
$array = array(1,2,3,2,5,4,7,5,8);
$arr1 = array(); $arr2 = array();
for($i=0;$i<count($array);$i++){
if(in_array($array[$i],$arr1)){
$arr2[$i] = $array[$i];
}else{
$arr1[] = $array[$i];
}
}
echo “Duplicate Values are “.implode(“,”,$arr2);
echo “<br>”;

foreach($arr2 as $k=>$v){
$flag = 0;
for($i=0;$i<count($array);$i++){
if($array[$i]==$v && $flag==0){
$sum=0;
for($j=$i;$j<=$k;$j++){
$sum = $sum+$array[$j];
}
echo $sum;
echo “<br>”;
$flag = 1;
}
}
}

Ques: Write a program to check whether a number is palindrome or not.

Ans: Palindrome Number – Palindrome number is that number whose reverse is same as the number.
For Example – Number 131 is palindrome but number 57 is not palindrome.
Program –
$number = 131; $tmp = $number;
$rev = 0;
while(floor($tmp)){
$rem = $tmp%10;
$rev = $rev*10+$rem;
$tmp = $tmp/10;
}
if($number==$rev){
echo “Number is palindrome”;
} else{
echo “Number is not palindrome”;
}

Ques: Write a program to reverse an array at a position.
Array – array(1,2,3,4,5,6,7);
Position – 2
Output – array(4,5,6,7,1,2,3)

Ans: Program –
$array = array(1,2,3,4,5,6,7); $pos = 2;
for($i=0;$i<count($array);$i++){
if($i<=$pos){
$arr1[] = $array[$i];
}else{
$arr2[] = $array[$i];
}
}
$final_array = array_merge($arr2,$arr1);
echo implode(“,”,$final_array);

Ques: Write a program to print table of a number(say 8) without using loop.

Ans: Program –
$n = 8;
function print_table($n,$i){
if($i<=10){
echo $n*$i;
echo “<br>”;
return print_table($n,$i+1);
} else {
return;
}
}
print_table($n,1);

Ques: What is abstract function ?

Ans: It is the function that is defined but not implemented in the code.

Ques: How can i create the object if that class whose constructor is defined as private ?

Ans: You can not create object of that class. But if you have to use the function inside it then you should make function as static.
Example – 
Class Test(){
private function __construct(){
echo “constructor called”;
}
public static function display($message){
echo $message;
}
}

Test::display(‘Hello I am in the function’);

Ques: Write a program to find the sum of a matrix.
Matrix –     1  2  3  4
                  5  6  7  8
                  1  2  3  4
                  5  6  7  8

Ans:
function diagonalSums($matrix, $n)
{
$left_diagonal_sum = 0;
$right_diagonal_sum = 0;
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
{
// principal diagonal
if ($i == $j){
$left_diagonal_sum += $matrix[$i][$j];
}

// secondary diagonal
if (($i + $j) == ($n – 1)){
$right_diagonal_sum += $matrix[$i][$j];
}
}
}

echo “Principal Diagonal: “.$left_diagonal_sum. “<br>”;
echo “Secondary Diagonal: “.$right_diagonal_sum.”<br>”;
}

$array = array (array ( 1, 2, 3, 4 ),
array ( 5, 6, 7, 8 ),
array ( 1, 2, 3, 4 ),
array ( 5, 6, 7, 8 ));
diagonalSums($array, 4);

Ques: Suppose there is an array with collection of objects, say
array(
    {
       ‘key’ : ‘1’,
       ‘name’ : ‘test’,
       ‘value’ : 1
   },
  {
     ‘key’ : ‘2’,
     ‘name’ : ‘test2’,
    ‘value’ : 2
  },
  {
     ‘key’ : ‘2’,
     ‘name’ : ‘test2’,
    ‘value’ : 3
  }
);

Print the object that is unique and if the objects key and name matches, then, their value is summed up and shown only once.

Output – 
array(
    {
       ‘key’ : ‘1’,
       ‘name’ : ‘test’,
       ‘value’ : 1
   },
  {
     ‘key’ : ‘2’,
     ‘name’ : ‘test2’,
    ‘value’ : 5(2+3)
  }
);

Ans:

$arr1 = array(“key”=>’1′, ‘name’ => ‘test’, ‘value’ => 1);
$obj1 = (object)$arr1;

$arr2 = array(“key”=>’2′, ‘name’ => ‘test2’, ‘value’ => 2);
$obj2 = (object)$arr2;

$arr3 = array(“key”=>’2′, ‘name’ => ‘test2’, ‘value’ => 3);
$obj3 = (object)$arr3;

$main_array = array($obj1, $obj2, $obj3);   //main array containing the objects

$final_array = array();

function search($key, $name, $array){
$response = array();
foreach($array as $k=>$v){
if($v->key==$key && $v->name==$name){
$response[0] = ‘1’;
$response[1] = $k;
break;
}else{
$response[0] = ‘0’;
$response[1] = ”;
}
}
return $response;
}

foreach($main_array as $main_key=>$main_value){
$res = search($main_value->key, $main_value->name, $final_array);
if(!empty($final_array) && $res[0]==1){
$final_array[$res[1]]->value = $final_array[$res[1]]->value+$main_value->value;
}else{
$final_array[] = $main_value;
}
}

echo “<pre>”;
print_r($final_array);

Ques: What is default session time in PHP ?

Ans: 24 minutes.

Ques: What is difference between unset() and unlink() ?

Ans: The unset() function will unset the variable i.e. it will make the variable undefined while the unlink() function is used to delete the files.

Ques: What is type casting ?

Ans: Changing the value from one format to another.
For example – There is an array and we have to convert it an object then –
Suppose – $array = array(“1″,”2”);
To convert it into object –
(object)$array;

Ques: What is difference between Abstraction and Interface ?

Ans: 1.) In abstraction, it is not necessary that all methods should be abstracted but in Interface every method should be abstracted.
2.) Interface methods should be public but abstraction methods can be public or protected.
3.) Inheritance supports both multiple and multilevel interface but abstraction supports single and multilevel inheritance.
4.) In interface, methods can only be defined. But in abstraction, methods can be defined as well as declared.

Ques: What is difference between PHP 5 and PHP 7 ?

Ans: 1.) Return Type – In PHP 7, type(float, int, other) of returning value can be defined.
For example – 
public function subtract(float $a, float $b) : float
{
return $a-$b;
}
2.) Null Coalesce Operator (??) – The coalesce operator(??) return result of its first operand if it exists or null.
For example – 
if(isset($_GET[‘id’])){
$id = $_GET[‘id’];
}else{
$id = null;
}
In PHP 7 –
$id = $_GET[‘id’]?? null;

Ques: What is PDO ?

Ans: PDO stands for PHP Data Objects. It is consitent interface to access database.

Ques: What is persistent cookie ?

Ans: Persistent cookies help to remember info., settings, preferences or login details. 
Persistent cookie have some expiration date.
Example – Google Analytics cookie is the best example of persistent cookie which tracks the visitors when they move through the website.

Ques: How to get the ip address of the client ?

Ans: $_SERVER[‘REMOTE_ADDR’] can be used to get that.

Ques: Write a program to check that a given string is palindrome or not without using second variable.

Ans: Program –
function palindrome($str){
   if(strlen($str)==0 || strlen($str)==1){
       return “It is palindrome”;
   }else{
      if(substr($str,0,1) == substr($str,(strlen($str)-1),1)){
         return palindrome(substr($str,1,(strlen($str)-2)));
     }else{
        return “It is not palindrome”;
     }
   }
}
$string = “NITIN”;
echo palindrome($string);

Ques: How will you reverse the words in a given string ?
Input – “garry’s giraffe gobbled goosberries greedily”
Output – “greedily goosberries goobled giraffe garry’s”

Ans: Program – 

$input = “garry’s giraffe gobbled goosberries greedily”;
$inputarray = explode(” “,$input);

$output = ”;

for($i=count($inputarray)-1;$i>=0;$i–){
$output.= ‘ ‘.$inputarray[$i];
}

echo $output;

Ques: Convert string into new string :
Input : abcD             
Output: cdeF

Ans: Program – 

$input = “abcD”;
$output = “”;

for($i=0; $i<strlen($input);$i++){
$ascii=ord($input[$i]);   //find ascii value of character
$output.= chr($ascii+2);   //add 2 to ascii value and then print character at that value
}

echo $output;

Ques: What is difference between array_merge() and array_combine() ?

Ans: array_merge() function merges the elements of the array in a single array.
For Example –
$array1 = array(1,”name”=>”Ram”);
$array2 = array(1,”position”=>”God”);
$final_array = array_merge($array,$array2);
When you print $final_array – print_r($final_array),
Output –
Array([0]=>1 [name]=>”Ram” [1]=>2 [position]=>”God”);

array_combine() function takes two array and creates the final array from them by using one array values as key and other array values as values of that keys.
$array1 = array(“name”,”position”);
$array2 = array(“Ram”,”God”);
$final_array = array_combine($array,$array2);
When you print $final_array – print_r($final_array),
Output –
Array([name]=>”Ram” [position]=>”God”);

Ques: What will the output of $x = true and false; var_dump($x) ?

Ans: true. In this, = takes precedence over and operator i.e. it becomes –
$x = true;  //set value of x to be true
true and false.  

Ques: What will be he output of –
$x = ‘php’; echo $x++;

Ans: php

Ques: Can we add third party site in our site in iframe or any code ?

Ans: No. There are server setting which the site owner can change that if site origin is their site then it will work. 

Ques: Difference between http and https.

Ans: 1.) Http uses port number 80 while https uses 443.
2.) Http works at Application layer while Https works at transport layer.
3.) In Http, Encryption is absent while in Https, encryption is present.

Ques: How to define constant in PHP ?

Ans: define is used to define constant.
define(“constant name”,”constant value”);

Ques: Write a program to print – 

***********
   *********
      *******
         *****
            ***
               *

Ans: $space = 0; $star = 11;
for($i=1; $i<=6; $i++){
for($j=1; $j<=$space+$star; $j++){
if($j<=$space){
echo ” “;
}else{
echo “*”;
}
}
echo “<br>”;
$space++; $star = $star-2;
}

 

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.
 

Append or insert an element(div) after another element(div)

JQuery .after() and .insertAfter() functions can be used to append or insert an after other element.
Let us take an example we have to insert an element after a paragraph tag –

Insert an element (div) after another element(div) –
JQuery .after() and .insertAfter() functions can be used to append or insert an after other element.
Both performs the same task. The only difference between them is syntax.

In .after(), the first selector is that element after which other element will be inserted while in .insertAfter(), the second selector is that after which the element will be appended(inserted).

Let us take an example we have to insert an element after a paragraph tag –
So, it can be done in 2 ways –
<p>This is dummy text.</p>

With .after() –
$(“p”).after(“<p>The above is dummy text.</p>”);

With .insertAfter() –
$(” <p>The above is dummy text.</p>”). insertAfter (“p”);

Both of the above will insert new paragraph( The above is dummy text. ) after above paragraph( This is dummy text. ).

 

 

For more related queries, please VISIT.

In case, if you did not find your solution or have any query/question, please contact us.

Read contents from input type file

Read input type file contents –
File content can be read using FileReader function of javascript. Here is an example for explanation –

Create HTML (input field and a div where we have to show the content of file) –

<input type=”file” name=”inputfile” onchange=”readinputfile()”>
<div class=”showfilecontent”></div>

Now call JS function –

const reader = new FileReader()
function readinputfile (input) {
const input = input.files[0]
reader.readAsText(input)
}
reader.onload = function (e) {
document.querySelector(‘. showfilecontent ‘).innerText = e.target.result;
}

 

 

For more related queries, please VISIT.

In case, if you did not find your solution or have any query/question, please contact us.

Get Last Level Category – WordPress

Function to get all last level category ( whether it is category or subcategory )which have posts iis as follows –

Do you want to get last level category in wordpress(whether it is category or subcategory) which have posts then create the custom function defined below and call it in all categories loop –

function return_lastpostcat($categories){
$categories_temp = $categories;
foreach ( $categories_temp as $child_cat ) {
foreach ( $categories_temp as $k => $parent_cat ) {
if ( isset( $categories[ $k ] ) ) {
if ( cat_is_ancestor_of( $parent_cat, $child_cat ) ) {
unset( $categories[ $k ] );
}
}
}
}
return $categories;
}

For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.
 

Custom form validation Codeigniter

Some validation function are already defined in codeigniter form validation library. But sometimes, we might need to have a custom validation. You can do it by –

There are 2 ways to implement custom form validation in codeigniter

1.) Create function in controller (in the same controller in which we are implementing the validation).
2.) Create own or custom library and create function in that file.

1.) Create function in same controller –

Create function and call it by using callback_.

Example – Here is an example how to validate Indian mobile number using custom form validation function –

public function _check_phone($phone)

{

  if(preg_match(‘/^(?:(?:\+|0{0,2})91(\s*[\ -]\s*)?|[0]?)?[789]\d{9}|(\d[ -]?){10}\d$/’,$phone))

{

return true;

} else {

$this->form_validation->set_message(‘_check_phone’, ‘%s ‘.$phone.’ is invalid format’);

return false;

}

}

Function Call –

$this->form_validation->set_rules(‘contact_no_1’, ‘Mobile Number’, ‘trim|required|xss_clean|min_length[10]|max_length[18]|callback__check_phone’);

Disadvantage – You can use that function only that controller. What will you do if you have to put the validation at multiple places (controllers) ? So, its better to create custom library and create function in that library.

2.) Create Custom Library –

Create custom library file(say my_form_validation) in application/libraries directory.

Example – Same Indian mobile number validation –

<?php 

/**

 * CIMembership

 * 

 * @package Libraries

 * @author 1stcoder Team

 * @copyright   Copyright (c) 2015 1stcoder. (http://www.1stcoder.com)

 * @license http://opensource.org/licenses/MIT MIT License

 */

defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);

class MY_Form_validation extends CI_Form_validation 

{

protected $ci;

function __construct() {

parent::__construct();

$this->ci =& get_instance();

}

public function _check_phone($phone)

{

$this->ci->form_validation->set_message(‘_check_phone’, “This %s “.$phone.” is in invalid format!”);

  if(preg_match(‘/^(?:(?:\+|0{0,2})91(\s*[\ -]\s*)?|[0]?)?[789]\d{9}|(\d[ -]?){10}\d$/’,$phone))

{

return true;

} else {

return false;

}

}

}

Function Call –

 $this->load->library(‘my_form_validation’); //load the library

$this->form_validation->set_rules(‘contact_no_1’, ‘Mobile Number’, ‘trim|required|xss_clean|min_length[10]|max_length[18]|_check_phone’); // Call the functions like others

Note: You can create the function in both – controller and custom library But always prefer to write the function by creating custom library, so that in case, if need to use that function in multiple controllers, can be used easily.

 
 
 
____________________________________________
For more related queries, please visit.
In case, if you did not find your solution or have any query/question, please contact us.