Friday, October 28, 2016

How to find how many parameter / Arguments has been passed and there value

code-
<?php
    function parentFunction($name='name') {
        echo "There are total: ".func_num_args()." Arguments passed.<BR>";
        $args = func_get_args();

echo '<pre>';
print_r($args);
echo '</pre>';

//fetch the value
        for($i = 0; $i < count($args); $i++) {
echo "Passed Value: {$args[$i]}<br />";
        }
      }
    parentFunction($name= 'name','email','phone','location');
?>

login authentcation via browser prompt using PHP




<?php
if (($_SERVER['PHP_AUTH_USER'] != 'a') || ($_SERVER['PHP_AUTH_PW'] != 'a')) {
      header('WWW-Authenticate: Basic Realm="Secret Stash"');
      header('HTTP/1.0 401 Unauthorized');
      print('You must provide the proper credentials!');
      exit;
   }
else{
echo 'login done';
//do stuff here
}
?>

Extract Only numbrs from long string using Regex with PHP (Regular Expressions)

Here is a string -: RT4646R@TWBNSN3234FHFHFH893892389FHDJJD$

Now How will find all red marked numbers in an Array.Here is solution.




<?php
$string = 'RT4646R@TWBNSN3234FHFHFH893892389FHDJJD$';
$special_char = '\[#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]';
preg_match_all('/\d+/', $string,$output);

echo '<pre>';
print_r($output[0]);
?>






Here is the output

PHP Regular Expressions





Author - 
sudhir k gupta | sudhir gupta | sudhir kumar gupta | eghara
Sudhir K gupta | Lonawala

Tuesday, September 27, 2016

Convert All Table TD data into Titlecase with 1 line of code

Lets say.. you receive input from server and that input is unstructured. No proper title case. 


Just like this. 


And You want like this (in just one click or unload )



Here is the code (Copy link is below the screenshot)



Download Full Code From Here

Tuesday, September 20, 2016

How to check a value exists in javascript array

Lets say user send a input "abcd" or "123". Now i want to check that incoming input should be  valid as assign in javascript array.

Like this -:



And you want output like this



var validFormatsArray = ['varchar','email','int','phone','sudhir'];
var isValidFormat = $.inArray('int'.toLowerCase(), validFormatsArray);

if(isValidFormat == -1){
  alert('Invalid format detected');
}else{
  alert('valid format');
}

Checkout this video tutorial







Also Read-:

Top most 15 haunted places in india which will dread your body



Sunday, September 18, 2016

How to translate one word to all possible language in single click

This trick will work in google spreadsheets only.


1) open a blank (new) google docs spreadsheet
2) add this to cell B2:
=GoogleTranslate($A$1, "en", "af")
3) Copy the formula entered into B2 to as many rows you want, one for each language.
4) replace the "af" (afrikaans) with whatever language codes you want in the formulas below B2 ... google has 149 languages to pick from. See here: Google Language Codes - tomihasa
5) Enter the stuff you want translated into cell A1




Saturday, September 17, 2016

How to use google voice in chrome (awesome tricks)

1. How do you turn on voice search on Google Chrome?
2. What is the Voice Search?
3. How do I use voice commands?



must watch and learn how to use effectively google voice in your computer using chrome

Friday, September 16, 2016

World-easiest-profile-management-crud-application-in-symfony



Hey Guys, I developed this application in one of my interview in Mumbai. Later on i feel that, this application can help to lot of developer (not only in core php but all PHP Frameworks i.g Symfony)...
What cover PMCA (Profile Managment CRUD System)

1. Insert Profile Details with Profile Pic (Preview also) using Ajax with required validation

2. Update Existing Record (required validation too)

3. View All Records with pagination by id

4. List all Profile in single page

5. Delete Single Record

6. Api End Point where, if you request ids (,2,5,10). you will get profile details in Json format.


HERE IS FULL CODE (FREE DOWNLOAD)



HERE IS FULL CODE (FREE DOWNLOAD)




Thursday, September 15, 2016

Export Html Table into Excel using Javascript in 2 Minute

Hey guys, Want to export your small/Large Table data with row header in excel.
Also, you want to put some color in first row. then you are in right place.

This code (few lines of code ) will export the same.

No rocket science required.
No external setup
Only Vanilla JavaScript

----------------------------------------------------------


HTML-:

  <table id="exTable" border="1">
    <thead class="lockedRecordsBg">
        <tr>
            <th>S#</th>
            <th>name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Country</th>
    </thead>
    <tbody>
        <tr>
            <td rel="client">1</td>
            <td rel="regionName">Sudhir K Gupta</td>
            <td rel="date">sudhirgupta.456@gmail.com</td>
            <td rel="shift">+91 89********</td> 
            <td rel="shift">India</td>             
        </tr>
        <tr>
            <td rel="client">2</td>
            <td rel="regionName">Sudhir K Gupta</td>
            <td rel="date">test@gmail.com</td>
            <td rel="shift">+91 89********</td> 
            <td rel="shift">USA</td>             
        </tr>
    </tbody>
</table> 


Javascript-:

<script>
function exportToExcel(tableID){
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6' style='height: 75px; text-align: center; width: 250px'>";
    var textRange; var j=0;
    tab = document.getElementById(tableID); // id of table

    for(j = 0 ; j < tab.rows.length ; j++)
    {

        tab_text=tab_text;

        tab_text=tab_text+tab.rows[j].innerHTML.toUpperCase()+"</tr>";
        //tab_text=tab_text+"</tr>";
    }

    tab_text= tab_text+"</table>";
    tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, ""); //remove if u want links in your table
    tab_text= tab_text.replace(/<img[^>]*>/gi,""); //remove if u want images in your table
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); //remove input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer

    {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write( 'sep=,\r\n' + tab_text);
        txtArea1.document.close();
        txtArea1.focus();
        sa=txtArea1.document.execCommand("SaveAs",true,"sudhir123.txt");
    }

    else {
       sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
    }
    
    return (sa);
}
</script>

Now Put button below the script (must) or put jquery window.load function for this click event.
otherwise it will not work.

<input type="button" value="export" onclick="exportToExcel('exTable')" />




Download Code From Here


Ads.


Know top 10 most interesting and awesome YouTube fact

Do you know why are headphones printed L and R

job doesn’t define how good human being you are

5 funny and interesting fact about your jeans






Author-

sudhir k gupta | sudhir gupta | sudhir kumar gupta | eghara
sudhir k gupta | sudhir gupta | sudhir kumar gupta | eghara






Sunday, September 11, 2016

How to see Wi - Fi password of connected network in window 10

Guys, It's very easy to find out the password of connected wi-fi connection. those who are facing Problem. Follow below steps or watch video directly.


1. Head out mouse cursor over Wi-Fi icon
2. Right click and select "Open network and sharing center"
3. Click on connected Wi-Fi connection
4. Click on wireless properties
5. Click on security
6. Check on "show characters"

Now See Network security key.  This is your Wi-Fi password.

Checkout video 


Tuesday, September 6, 2016

bind javascript event for future element without attaching any event - DOMNodeInserted (alternative of .on )

1st approach what we did always 

$('body').on('click','.abcd',function () {
        $(this).prev('.teaseRestText').toggle();
        if ($(this).attr('toggle') == '0') {
            $(this).html('Show Less...').attr('toggle', 1);
        }
        else {
            $(this).html('Show More...').attr('toggle', 0);
        }
});


But sometimes, situation came that we don't have any event like "click " but still need a function to execute for dynamic elements. 

I came to this solution  



$(document).bind('DOMNodeInserted', function(event) {
    $('#table tr').each(function (e) {
        console.log(e);
    });
});


Friday, August 19, 2016

Create Simple Chat Sever Using PHP and MySql

Do you want to create a simple chat server using php if yes then you are at right place.
Check out this snapshot click on below link to download package.



Create Simple Chat Sever Using PHP and MySql


Create Simple Chat Sever Using PHP and MySql


Click Here to Download this script


Saturday, August 6, 2016

How to store data in Hindi (unicode) language

some time we need to save data into another language such as Hindi.
if we want save Hindi font in MySQL then we have to take care of  collation 





Steps

 when you are creating a table, see collation column. select urf_general_ci. if you will choose another collation and will insert Hindi text then it will appear like "?????? ?? [][][][][][]"





Solution



Wednesday, July 27, 2016

Inject multiple javascript src tag using javascript (dynamically)

Code-:
function scriptLoader(scripts, callback) {

    var count = scripts.length;

    function urlCallback(url) {
        return function () {
            console.log(url + ' was loaded (' + --count + ' more scripts remaining).');
            if (count < 1) {
                callback();
            }
        };
    }

    function loadScript(url) {
        var s = document.createElement('script');
        s.setAttribute('src', url);
        s.onload = urlCallback(url);
        document.head.appendChild(s);
    }

    for (var script of scripts) {
        loadScript(script);
    }
};


Uses-:
scriptLoader(['a.js','b.js'], function() {
    // use code from a.js or b.js
});

Inject multiple javascript src tag using javascript (dynamically)
Inject multiple javascript src tag using javascript (dynamically)

Monday, July 25, 2016

get all html code (clone) and encode the data

some time you need to save some of html data on localStorage. that time we need to encode that data before saving. this code might be help you.

 var entityMap = {
            "&": "&",
            "<": "<",
            ">": ">",
            '"': '"',
            "'": ''',
            "/": '/'
        };

        function escapeHtml(string) {
            return String(string).replace(/[&<>"'\/]/g, function (s) {
                return entityMap[s];
            });
        }

           $clone = $('html').html();
           console.log("Encoded HTML is = "+escapeHtml($clone));

save a custom text file in your computer using javascript

Write the text and click.. that's it... your text will be exported into text file in your computer.

Uses-: copy it into an .html file and open that file in a web browser that runs JavaScrip.


So, Here the code-


<html>
<body>

<table>
<tr><td>Text to Save:</td></tr>
<tr>
        <td colspan="3">
            <textarea cols="80" id="inputTextToSave" rows="25"></textarea>
        </td>
    </tr>
<tr>
        <td>Filename to Save As:</td>
        <td><input id="inputFileNameToSaveAs" /></td>
        <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
    </tr>
<tr>
        <td>Select a File to Load:</td>
        <td><input id="fileToLoad" type="file" /></td>
        <td><button onclick="loadFileAsText()">Load Selected File</button><td>
    </td></td></tr>
</table>
<script type="text/javascript">

function saveTextAsFile()
{
    var textToSave = document.getElementById("inputTextToSave").value;
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);

    downloadLink.click();
}

function destroyClickedElement(event)
{
    document.body.removeChild(event.target);
}

function loadFileAsText()
{
    var fileToLoad = document.getElementById("fileToLoad").files[0];

    var fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent) 
    {
        var textFromFileLoaded = fileLoadedEvent.target.result;
        document.getElementById("inputTextToSave").value = textFromFileLoaded;
    };
    fileReader.readAsText(fileToLoad, "UTF-8");
}

</script>

</body>
</html>

Sunday, May 29, 2016

Thursday, April 7, 2016

Add Decimal in your amount at desire position

Code

$amount = 560;
$decimalPosition = 2;
$divideBy   =   pow(10, $decimalPosition );
$newNumber  =   number_format( $totalTax / $divideBy , 2, '.','');
echo $newNumber;

OutPut

5.60


Second Way

        $decimal_point = 2;
        $totalTax=1260; //1.260

        $a=substr($totalTax,0,-$decimal_point); //560 ka 5
        $b=substr($totalTax,-$decimal_point,$decimal_point); //560 ka 60
        
        $c = $a.'.'.$b;
        echo $c;
        


Third Way

        /********* in one line ****************************************\
        
        $d = (substr($totalTax,0,-$decimal_point)).'.'.(substr($totalTax,-$decimal_point,$decimal_point));
        echo $d;

Tuesday, March 8, 2016

What is the difference between Synchronous and Asynchronous ajax request

Every developer want to know about Synchronous vs Asynchronous

Most of the developer often faces this question in interview.
I was also questioned several times so i plan to write a small post so that others can get help.
I found a nice explanation on stackoverflow.

See below explanation-:



Here i found another nice one explanation.



Finally i come to this conclusion


Friday, March 4, 2016

Get directory path in symfony 2.8 and 3.0



Get base path -:


  echo 'path is '.realpath($this->container->getParameter('kernel.root_dir').'/..');

Tuesday, March 1, 2016

How to shift php array key pair value to top or bottom

MOVE KEY VALUE PAIR TO THE TOP/BOTTOM OF AN ARRAY

<?php
class demo{
   public function arratData(){
      $myArray= array (
                 'bk101' => array (
                                'author' => 'Gambardella, Matthew',
                                'title' => 'XML Developer\'s Guide',
                                'genre' => 'Computer',
                                'price' => '44.95',
                                'publish_date' => '2000-10-01',
                                'id' => 'bk101'
                                  ),
                 'bk102' => array (
                                'id' => 'bk102',
                                'author' => 'Ralls, Kim',
                                'title' => 'Midnight Rain',
                                'genre' => 'Fantasy',
                                'price' => '5.95',
                                'publish_date' => '2000-12-16',
                                'description' => 'A former architect battles corporate zombies...',
                                  ),
                        );
 
    echo '<pre>Actual Array set <br />';
    print_r($myArray);
 
    // call the function move_to_top
    // i want ID of "bk101" should be at top
 
    $top = $this->move_to_top($myArray['bk101'],'id');
 
    echo '<h4>ID of "bk101 will be at top which is at bottom in actual array"</h4>';
    print_r($top);
 
 
    // Now call the function move_to_bottom
    // i want ID of "bk102" should be at bottom which is at top right now
 
    $bottom = $this->move_to_bottom($myArray['bk102'],'id');
 
   echo '<h4>ID of "bk102 will be at bottom which is at top in actual array"</h4>';
    print_r($bottom);
 
 
 
 
   }
 
    public  function move_to_top(&$array, $key) {
        $temp = array($key => $array[$key]);
        unset($array[$key]);
        return $array = $temp + $array;
    }

    public  function move_to_bottom(&$array, $key) {
         
            $temp = array($key => $array[$key]);
            unset($array[$key]);
            return $array = $array + $temp;
    }
}

$a=new demo;
$show_data=$a->arratData();
echo $show_data;
?>

Output





Download File

Tuesday, February 9, 2016

How to Deploy Symfony 2.8 or 3.0 Project on Linux Hosting Server.

After spending several day finally i success to launch my symfony project on share hosting.
Guys ! Its very diffrent to work in xampp / Wamp than Production server in symfony case.


I will tell you story step by step.
I developed a small project in symfony 2.8 which need some ajax call, some CRUD operation.
that project was running like a charm at my localhost. Then finally I upload all files into my shared server under  "public_html" (which turn wrong for me). using this method, some time my page was blank or some time i was geeing un-understandable  error :-).

Finally i got one solution to that work for me on Linux shared hosting .

Follow Below steps
  • Before uploading any thing delete everything under "App/Chache"
  • upload "WEB" folder which is inside of  your symfony Project  into "/public_html"
  • Now Go up one label from /public_html. you  will see  "/"  in remote site path 
  • upload all Remain Folders of your symfony project here. 
  • Never forgot to update your DB Details in " app/config/parameters.yml

Thats it. Go to the url, you will must see the running page.

Note-: i will brief you my Shared Hosting Details which i performed.
  •            Server -: Linux
  •            Type -:    Share hosting at Hioxindia pvt ltd
  •            Framework version-: Symfony 2.8
  •            Localy developed with  Wamp + PHPMyadmin



Here is snap shot of my Test Project 



Tuesday, February 2, 2016

Make Mysql Database Connection using PDO || Very Easy to learn

1.Config.php
<?php
     
        error_reporting(E_ALL);
        try
        {
 $pdo = new PDO('mysql:host='. DB_HOST .';dbname='.$selected_db, DB_USER, DB_PASSWORD);  // with db connect
             $db = new PDO( "mysql:host=localhost", 'root', '' ); without DB.. just an open  connection
        }
        catch (PDOException $e)
        {
            $db='Error: '.$e->getMessage();
            die($db);
        }
        return $db;
?>



2. logic.php
 
   <?php
       $db = include_once('config.php');
        try{
         
         $q_object = $db->query("select password('my_hash_password') as m_password");
     
         $get_data = $q_object->fetch(PDO::FETCH_ASSOC);
         echo '<pre>';
         print_r($get_data);
      }
      catch(PDOException $e){
          echo 'Some Error Found<br />'.$e->getMessage();
          die();
      }

Thursday, January 28, 2016

How to create table backup using native Php Script ( Using PHP/PDO )

Take database backup using PHP Script

------------------------

<?php
session_start();
$con = include("connection.php");


function backup_db($con){
/* Store All Table name in an Array */
$allTables = array();

$query = $con->query('SHOW TABLES');

$result=$query->fetchAll(PDO::FETCH_COLUMN);
$allTables=$result;    

$return ='';
foreach($allTables as $table){
$result_tab = $con->query('SELECT * FROM '.$table);
$num_fields = $result_tab->columnCount();

$return.= 'DROP TABLE IF EXISTS '.$table.';';

$create_query = $con->query('SHOW CREATE TABLE '.$table);
$row2 = $create_query->fetch(PDO::FETCH_NUM);
$return.= "\n\n".$row2[1].";\n\n";

for ($i = 0; $i < $num_fields; $i++)
    {
        $eachRow =$result_tab->fetchAll(PDO::FETCH_NUM);
        foreach($eachRow as $keys=>$row)
        {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j<$num_fields; $j++){
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = str_replace("\n","\\n",$row[$j]);
                        if (isset($row[$j]))
                            {
                                $return.= '"'.$row[$j].'"' ;
                            }
                            else
                            {
                               $return.= '""';
                            }
                if($j<($num_fields-1))
                {
                    $return.= ',';
                }
                }
            $return.= ");\n";
         }
    }
    $return.="\n\n";
}

// Create Backup Folder
$folder = 'sql/';
if (!is_dir($folder))
mkdir($folder, 0777, true);
chmod($folder, 0777);

$date = date('m-d-Y-H-i-s', time());
$filename = $folder."db-backup-".$date.'.sql';
$_SESSION['backupFile'] = $filename; // you can found out this file path while importing
$handle = fopen($filename,'w+');
fwrite($handle,$return);
fclose($handle);
}

// Call the function
backup_db($con);
?>



 How to import sql backup using php script ( Using PHP/PDO )