Friday, February 27

Check if PHP Session has already started

Recommended way for versions of PHP >= 5.4.0

<?PHP
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
?>

Source: http://www.php.net/manual/en/function.session-status.php

For versions of PHP < 5.4.0

<?PHP
    if(session_id() == '') {
        session_start();
    }
?>

Tips on Web Application Session practices

    1. Use a database for sessions.
 
    2. Regenerate the session on when the permissions change (e.g., when a user logs in).
 
    3. Regenerate the session on every page load (optional).
 
    4. Don't expose the session ID in the URL.
 
    5. Don't expose any sensitive data to the session.
 
    6. Only use the session through secure transport, otherwise someone could sniff the cookie and hijack the session.
 
    7. Expire your session after a reasonable amount of time.

In addition to VirtuosiMedia's list:

    1. Use TLS (SSL) across the entire site. Use the HSTS header.
 
    2. Use a session cookie, rather than adding a session token to every link-href and form-action.
 
    3. Use the secure and httpOnly flags on the cookie.
 
    4. Use the X-Frame-Options header.
 
    5. Keep the content of the session minimal. E.g., store only the user-id. If caching is needed, cache in a general caching layer, not the session.
 
    6 Cryptographically sign the session cookie with a secret key known only to the server. Include an expiration datetime in the signed data. Check the signature and the expiration at the server on every request.

Prepared Statements using PHP or Fix SQL Injection.

PHP coders should use the PDO module if possible as it supports prepared statements across various databases. MySQL users should in particular avoid the old "mysql" module which does not support prepared statements. As of PHP 5, mysqli is available and it supports prepared statements.

Secure Usage:

<?PHP
    $oDB=new PDO('... your connection details... ');
    $hStmt=$oDB->prepare("select name, age from users where userid=:userid");
    $hStmt->execute(array(':userid',$nUserID));
?>

Vulnerable Usage

<?PHP
    // Example #1 (using old mysql library)
    $q=$_GET["q"];
    $con = mysql_connect('localhost', 'peter', 'abc123');
    mysql_select_db("ajax_demo", $con);
    $sql="SELECT * FROM user WHERE id = '".$q."'";
    $result = mysql_query($sql);
?>
(code copied from http://www.w3schools.com/PHP/php_ajax_database.asp )

This code is vulnerable to SQL injection. It uses the old mysql library, which does not support prepared statements. However, the vulnerability could still be avoided by either properly escaping or validating the user input.

<?PHP
    // Example #2 (incorrectly preparing a statement with PDO)
    $oDB=new PDO('... your connection details...');
    $hStmt=$oDB->prepare("select name, age from users where userid=".$_GET['userid']);
    $hStmt->execute();
?>

The second vulnerable example looks just like the secure one above. But instead of properly binding the user data, it assembles dynamic SQL and prepared it after adding user data.

Thursday, February 26

Send Email to Multiple Recipients using PHP

You can send email to multiple recipient at one shot using php. When you submit, this file will be sent an email immediately to the target emails from your database.

First create a DB

Database "mail" and table "email_list" with 3 fields: id(auto_increment), name(varchar, 50), email (varchar, 50) and put some records into this table.

<?php
    // Check, if submitted.
    if($Submit){
     
        // Get variables from POST method form.
        $subject=$_POST['subject'];
        $note=$_POST['note'];
         
        $sender="admin@yourdomain.ext"; // Your Email here.
         
        echo "Email has been sent to:";
         
        // Connect database
        mysql_connect("localhost","","");
        mysql_select_db("mail");
         
        $rs=mysql_query("select * from email_list order by id asc");
         
        // Do while loop to send email.
        while($row=mysql_fetch_assoc($rs)){
            $to=$row['email'];
            $mail_from="From:$email n";
            $mail_from .="Content-Type: text/html; charset=utf-8 n";
             
            mail($to,$subject,$note,$mail_from);
             
            // Show sent emails.
            echo "$row[email]<br>";
        }
    }else{
     
        // Do following codes if not found "Submit" value.(Not submitted)
        ?>
        <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            </head>
            <title>Email Form</title>
            <body>
                <form action="<? echo $PHP_SELF; ?>" method="post" name="form" id="form">
                    <table>
                        <tr>
                            <td align="right">Subject : </td>
                            <td><input name="email" type="text" id="email" /></td>
                        </tr>
                        <tr>
                            <td align="right" valign="top">Note : </td>
                            <td><textarea name="comment" cols="60" rows="5" id="comment"></textarea></td>
                        </tr>
                    </table>
                    <input type="submit" name="Submit" value="Send Email" />
                </form>
            </body>
        </html>
    <?php
    }
?>

Tuesday, February 24

How do PHP sessions work in PHP, and how are they used?

In the general situation :

    1. the session id is sent to the user when his session is created.
    2. it is stored in a cookie (called, by default, PHPSESSID)
    3. that cookie is sent by the browser to the server with each request
    4. the server (PHP) uses that cookie, containing the session_id, to know which file corresponds to that user.
    5. The data in the sessions files is the content of $_SESSION, serialized (ie, represented as a string -- with a function such as serialize) ; and is un-serialized when the file is loaded by PHP, to populate the $_SESSION array.


Sometimes, the session id is not stored in a cookie, but sent in URLs, too -- but that's quite rare, nowadays.


For more informations, you can take a look at the Session Handling section of the manual, that gives some useful informations.

For instance, there is a page about Passing the Session ID, which explains how the session id is passed from page to page, using a cookie, or in URLs -- and which configuration options affect this.


Start a PHP Session:

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.


<?php

    // Start the session
    session_start();
    
    // Set session variables
    $_SESSION["favcolor"] = "green";

?>

Get PHP Session Variable Values:

<?php
    // Echo session variables that were set on previous page
    echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
    
    //Another way to show all the session variable values for a user session is to run the following code:
    print_r($_SESSION);
?>

Modify a PHP Session Variable:

To change a session variable, just overwrite it:

<?php
    // to change a session variable, just overwrite it 
    $_SESSION["favcolor"] = "yellow";
    print_r($_SESSION);
?>

Destroy a PHP Session:

To remove all global session variables and destroy the session, use session_unset() and session_destroy():

<?php
    // remove all session variables
    session_unset(); 
    
    // destroy the session 
    session_destroy(); 
?>

Monday, February 23

Sort Multi-dimensional Array by Value using PHP

Take a look at en.wikipedia.org/wiki/Sorting_algorithm for sorting algoritms to be able to sort your data as efficient as possible

<?php
    function aasort (&$array, $key) {
        $sorter=array();
        $ret=array();
        reset($array);
        foreach ($array as $ii => $va) {
            $sorter[$ii]=$va[$key];
        }
        asort($sorter);
        foreach ($sorter as $ii => $va) {
            $ret[$ii]=$array[$ii];
        }
        $array=$ret;
    }
    
    aasort($your_array,"order");
?>

Better alternative

<?php
    function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
        $sort_col = array();
        foreach ($arr as $key=> $row) {
            $sort_col[$key] = $row[$col];
        }
    
        array_multisort($sort_col, $dir, $arr);
    }    
    
    array_sort_by_column($array, 'order');
?>

Find out if two files are identical using PHP.

If you just need to find out if two files are identical, comparing file hashes can be inefficient, especially on large files.  There's no reason to read two whole files and do all the math if the second byte of each file is different.  If you don't need to store the hash value for later use, there may not be a need to calculate the hash value just to compare files.  This can be much faster:

    <?php
    define('READ_LEN', 4096);
    
    if(files_identical('file1.txt', 'file2.txt'))
        echo 'files identical';
    else
        echo 'files not identical';

    //   pass two file names
    //   returns TRUE if files are the same, FALSE otherwise
    function files_identical($fn1, $fn2) {
        if(filetype($fn1) !== filetype($fn2))
            return FALSE;
    
        if(filesize($fn1) !== filesize($fn2))
            return FALSE;
    
        if(!$fp1 = fopen($fn1, 'rb'))
            return FALSE;
    
        if(!$fp2 = fopen($fn2, 'rb')) {
            fclose($fp1);
            return FALSE;
        }
    
        $same = TRUE;
        while (!feof($fp1) and !feof($fp2))
            if(fread($fp1, READ_LEN) !== fread($fp2, READ_LEN)) {
                $same = FALSE;
                break;
            }
    
        if(feof($fp1) !== feof($fp2))
            $same = FALSE;
    
        fclose($fp1);
        fclose($fp2);
    
        return $same;
    }
    ?>



Source: php.net

What is Hotlinking, bandwidth theft OR almost perfect htaccess file for wordpress blogs.

Hotlinking is also known as bandwidth theft.

It is when other sites direct link to the images on your site from their articles making your server load increasingly high.

If one site does it, it might not make a significant difference, but there are too many spammers that will do this and that is something your server cannot hold specially if they copy your article with a lot of images.

No matter how good your web host is, it will be slowed down if hotlinking is not prevented.

There are a few ways you can disable hotlinking. First way we will share is through your root .htaccess file where you will place this code below:

    #disable hotlinking of images with forbidden or custom image option
    RewriteEngine on
    RewriteCond %{HTTP_REFERER} !^$
    RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?wpbeginner.com [NC]
    RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC]
    RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?feeds2.feedburner.com/wpbeginner [NC]
    RewriteRule \.(jpg|jpeg|png|gif)$ – [NC,F,L] 
 
You can make an image that will replace all hot linked image that will say Stealing is bad or something so it makes the spammer look stupid.
Remember you must allow your feed otherwise your feed readers would not see any images.

Source: Josiahcole

Write a program to accept values of two numbers and print their division in C language

    #include<stdio.h>
    #include<conio.h>
    main()
    {
        float a,b,c;
        clrscr();
        printf("Enter number 1: ");
        scanf("%f",&a);
        printf("Enter number 2: ");
        scanf("%f",&b);
        c=a/b;
        printf("Division is : %f",c);
        getch();
    }

Sunday, February 22

Questions every good PHP Developer should be able to answer

Admittedly, I stole this question from somewhere else (can't remember where I read it any more) but thought it was funny:

Q: What is T_PAAMAYIM_NEKUDOTAYIM?
A: Its the scope resolution operator (double colon)

An experienced PHP'er immediately knows what it means. Less experienced (and not Hebrew) developers may want to read this.

But more serious questions now:

Q: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it?
A: *Cause:* body data was sent, causing headers to be sent too.
Prevention: Be sure to execute header specific code first before you output any body data. Be sure you haven't accidentally sent out whitespace or any other characters.

Q: What is wrong with this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]"?
A: 1. It is vulnarable to SQL injection. Never use user input directly in queries. Sanitize it first. Preferebly use prepared statements (PDO)

    2. Don't select all columns (*), but specify every single column. This is predominantly ment to prevent queries hogging up memory when for instance a BLOB column is added at some point in the future.

Q: What is wrong with this if statement: if( !strpos( $haystack, $needle ) ...?
A: strpos returns the index position of where it first found the $needle, which could be 0. Since 0 also resolves to false the solution is to use strict comparison: if( false !== strpos( $haystack, $needle )...

Q: What is the preferred way to write this if statement, and why?
      if( 5 == $someVar ) or if( $someVar == 5 )
A: The former, as it prevents accidental assignment of 5 to $someVar when you forget to use 2 equalsigns ($someVar = 5), and will cause an error, the latter won't.

Q: Given this code:

function doSomething( &$arg )
{
    $return = $arg;
    $arg += 1;
    return $return;
}

$a = 3;
$b = doSomething( $a );
...what is the value of $a and $b after the function call and why?
A: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter because the return value of the function is a copy of (not a reference to) the initial value of the argument.

OOP specific

Q: What is the difference between public, protected and private in a class definition?
A: public makes a class member available to "everyone", protected makes the class member available to only itself and derived classes, private makes the class member only available to the class itself.

Q: What is wrong with this code:

class SomeClass
{
    protected $_someMember;

    public function __construct()
    {
        $this->_someMember = 1;
    }

    public static function getSomethingStatic()
    {
        return $this->_someMember * 5; // here's the catch
    }
}
A: Static methods don't have access to $this, because static methods can be executed without instantiating a class.

Q: What is the difference between an interface and an abstract class?
A: An interface defines a contract between an implementing class is and an object that calls the interface. An abstract class pre-defines certain behaviour for classes that will extend it. To a certain degree this can also be considered a contract, since it garantuees certain methods to exist.

Q: What is wrong with classes that predominantly define getters and setters, that map straight to it's internal members, without actually having methods that execute behaviour?
A: This might be a code smell since the object acts as an ennobled array, without much other use.

Q: Why is PHP's implementation of the use of interfaces sub-optimal?
A: PHP doesn't allow you to define the expected return type of the method's, which essentially renders interfaces pretty useless.




Definitively security questions !

(simple answers in this post, of course securing php web applications is far more complex)

how to deal with SQL injection ?
mysql_real_escape_string() for a start with MySQL. Then try to learn PDO to take advantage of prepared statements and portability across database vendors.

how to deal with CSRF (Cross-Site Request Forgery) ?
Add a token on every important request to secure important operations (user must have seen the form before sending the crucial request).?

how to deal XSS (Cross-Site Scripting) reflected and stored ?
htmlentities() is good for a start.

variant of XXX injections: LDAP injection, XPath injection, etc... ?
You need to know what is the "vocabulary" used by the XXX and then deduct what you need to sanitize and/or "check-and-reject".

what is the list of sensible functions ?
Functions which interpret PHP code (possibly included in a remote file) or which execute command on your system. A short and incomplete list could be: exec(), passthru(), system(), popen(), eval(), preg_replace()...

how to deal with file inclusion dangers ?
what is a path transversal ?
what are the risks associated with file upload ?
Need careful check of the parameters used when opening file or remote resources.

how to enforce the configuration of your PHP configuration (i.e. do you know what is the use of php.ini) ?
It is going to be long so I skip the answer, please read the PHP manual.

about filtering user data: what is the difference between sanitizing and check-and-refuse ?
The first one transforms the entry in something less hostile. The second one check if the entry is correct and, if not refuse it.


Source: stackoverflow.com

Determining a web user's time zone

Using Unkwntech's approach, I wrote a function using jQuery and PHP. This is tested, and does work!

On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:

<?php    
    session_start();
    $timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.

On the same page, in the , you need to first of all include jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the , below the jQuery, paste this:

<script type="text/javascript">
    jQuery(document).ready(function() {
        if("<?php echo $timezone; ?>".length==0){
            var visitortime = new Date();
            var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
            jQuery.ajax({
                type: "GET",
                url: "http://domain.com/timezone.php",
                data: 'time='+ visitortimezone,
                success: function(){
                    location.reload();
                }
            });
        }
    });
</script>
You may or may not have noticed, but you need to change the url to your actual domain.

One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)

<?php
    session_start();
    $_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.


What should every PHP programmer know?

First off, there is no must know about learning PHP and MySQL... You go into it not knowing anything, and you'll come out of it knowing a bunch. If there was a must know, then nobody would be able to get into PHP and MySQL development. I personally think you are at a slight advantage going into this without knowing everything about it. It'll give you a fresh perspective and a think outside of the box attitude :)

As far as the object oriented stuff in this thread, it's true. But, as others have said, it's completely up to the programmer (you) to decide how to write your code. You can use object oriented practices, make a spaghetti code junction, or just right a bunch of functions, or whatever. Either way, as everyone else has been saying, it's up to you :)

IRC channel:

Don't really need this, but I find it helpful... See you in here :)


Manual:

The manual is your friend and probably the only thing you should know before diving in.

1. http://www.php.net/manual/en/

2. http://dev.mysql.com/doc/refman/5.0/en/apis-php.html

Frameworks:

Make sure it's an MVC framework :)

1. http://www.cakephp.org/

2. http://www.phpmvc.net/

3. http://www.codeigniter.com/

4. http://www.symfony.com/

IDE:

Whatever suits you best :)

1. http://www.eclipse.org/

2. http://www.vim.org/

3. http://www.zend.com/en/products/studio/

4. http://php.netbeans.org/

Template engines:

PHP is a good template engine

Model view controller frameworks help with this

Ajax:

1. http://jquery.com/

2. http://www.mootools.net/

3. http://developer.yahoo.com/yui/

4. http://www.prototypejs.org/

5. http://www.extjs.com/

6. http://code.google.com/webtoolkit/

CSS:

1. http://www.yaml.de/en/home.html

2. http://code.google.com/p/blueprintcss/

3. http://developer.yahoo.com/yui/reset/

Definitely not an exhaustive list, and things change constantly... But, it's a start :)

Have fun!


Source: stackoverflow.com

Tools for faster, better web development

Over the years most web developers will have built an arsenal of tools or "tools of the trade". Recently I discovered rsync and I am surprised how I managed to live without it all these years. What tools do you consider to be the most compelling? Please stick to the ones you use on a regular basis and swear by. They can also be frameworks, platforms, editors and whatever else you think web developers ought to be using (jquery, joomla, xdebug, vi, notepad++, etc).

I'll start off with a couple:

1. rsync - 'One click' sync to live servers or vice-versa

2. mysqldump - used alongside rsync to sync the databases

3. test styles bookmarklet - live css editor bookmarklet which beats the heck out of the 'edit > save > reload' cycle by allowing live editing.

4. javascript shell - javascript shell window attached to a window

5. firebug - advanced javascript/css/dom debugger

6. php-shell - I use this regularly for quickly testing statements, functions, classes or scripts

7. CSS-Discuss Wiki - I'd be surprised if you couldn't find a solution to your CSS problem on this wiki (in which case you should add it)

8. Font Matrix - Helps me choose font stacks

9. PHPMyAdmin - I'm certain everyone uses this for managing their MySQL databases but thought I'd add it to the list for good measure


Even though I have highlighted tools in the LAMP environment, you may mention tools you use in your environment.


SOURCE: stackoverflow.com

Thursday, February 19

Write a program to accept values of two numbers and print their multiplication in C language

    #include<stdio.h>
    #include<conio.h>
    main()
    {
        int a,b,c;
        clrscr();
        printf("Enter number 1: ");
        scanf("%d",&a);
        printf("Enter number 2: ");
        scanf("%d",&b);
        c=a*b;
        printf("Multiplication: %d",c);
        getch();
    }

Wednesday, February 18

Send a email using PHP

    <?php
    $to = "somebody@example.com, somebodyelse@example.com";
    $subject = "HTML email";
    
    $message = "
    <html>
    <head>
    <title>HTML email</title>
    </head>
    <body>
    <p>This email contains HTML Tags!</p>
    <table>
    <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    </tr>
    <tr>
    <td>John</td>
    <td>Doe</td>
    </tr>
    </table>
    </body>
    </html>
    ";
    
    // Always set content-type when sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    
    // More headers
    $headers .= 'From: <webmaster@example.com>' . "\r\n";
    $headers .= 'Cc: myboss@example.com' . "\r\n";
    
    mail($to,$subject,$message,$headers);
    ?> 

Repeat a string multiple times with a separator in PHP

Here is a simple one liner to repeat a string multiple times with a separator:

    <?php
    implode($separator, array_fill(0, $multiplier, $input));
    ?>

Example script:

    <?php
    
    // How I like to repeat a string using standard PHP functions
    $input = 'bar';
    $multiplier = 5;
    $separator = ',';
    print implode($separator, array_fill(0, $multiplier, $input));
    print "\n";
    
    // Say, this comes in handy with count() on an array that we want to use in an
    // SQL query such as 'WHERE foo IN (...)'
    $args = array('1', '2', '3');
    print implode(',', array_fill(0, count($args), '?'));
    print "\n";
    ?>

Example Output:

bar,bar,bar,bar,bar
?,?,?

Best way to prevent some sql injection attacks using PHP

Automagically add slashes to $_POST variables. It helps to prevent some sql injection attacks. Also works with $_GET variables.

FILE NAME: input_cl.php

<?php
    //create array to temporarily grab variables
    $input_arr = array();
    //grabs the $_POST variables and adds slashes
    foreach ($_POST as $key => $input_arr) {
        $_POST[$key] = addslashes($input_arr);
    }
?>

Just put this at the top of your script that gets the variables. Here is an example.

Usage Example

<?php
    include("input_cl.php");
    // all $_POST variables have slashes added to them
    $f_name = $_POST["f_name"];
    $l_name = $_POST["l_name"];
    $phone_num = $_POST["phone_num"];
    $address1 = $_POST["address1"];
    $address2 = $_POST["address2"];
    $city = $_POST["city"];
    $State = $_POST["State"];
    $zip = $_POST["zip"];
 
    //sql insert code goes here.
?>

Write a program to Accept values of two numbers and print their subtraction

    #include<stdio.h>
    #include<conio.h>
    main()
    {
        int a,b,c;
        clrscr();
        printf("Enter number 1: ");
        scanf("%d",&a);
        printf("Enter number 2: ");
        scanf("%d",&b);
        c=a-b;
        printf("Subtraction : %d",c);
        getch();
    }

Write a program to Accept values of two numbers and print their addition

    #include<stdio.h>
    #include<conio.h>
    
    main()
    {
        int a,b,c;
        clrscr();
        printf("Enter number 1: ");
        scanf("%d",&a);
        printf("Enter number 2: ");
        scanf("%d",&b);
        c=a+b;
        printf("Addition is : %d",c);
        getch();
    }

Tuesday, February 17

Write a program to Print a string in C language

    #include<stdio.h>
    #include<conio.h>
    main()
    {
        clrscr();
        printf("\nKodeGod.com");
        getch();
    }

Monday, February 2

json_encode 'php array' to a 'json array'

Array in JSON are indexed array only, so the structure you're trying to get is not valid Json/Javascript.

PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.

If you want to get such structure you can do:

<?php
    $indexedOnly = array();
    
    foreach ($associative as $row) {
        $indexedOnly[] = array_values($row);
    }
    
    json_encode($indexedOnly);
?>

Will returns something like:

[
     [0, "name1", "n1"],
     [1, "name2", "n2"],
]

Validate user login through JS(JavaScript), Ajax and PHP

    <script>       
    function validateLogIn()
    {
    
        var username  = $("#IdOfYourUserFiled").val();
        var password  = $("#IdOfYourPasswordFiled").val();
        $.ajax({                                      
            url: 'login.php',    //checking the login in                     
            data: {username:username,password:password}, //You have to pass user inputs to next page to validate in DB            
            type: "POST",     //Method by which data being transmitted
            dataType: 'json',                  
            success: function(data)          
            {
                if(data.flag === 0){
                    alert("Username or Password is incorrect");
                } else if (data.flag == 1){
                    window.open('index.php', '_self');  
                }
            }
        }); 
    }
    </script>
 
    login.php
 
    <?php
        /*Database Details */
        define('DB_HOST', 'localhost');
        define('DB_NAME', 'practice');
        define('DB_USER','root');
        define('DB_PASSWORD','');
        
        /* Database connectivity */
        $con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); 
        $db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
        
        /* Username and Password */
        $username = mysql_real_escape_string($_POST['username']);
        $password = mysql_real_escape_string($_POST['password']);
        
        $query = mysql_query("SELECT * FROM UserName where userName = '$username' AND pass = '$password'") or die(mysql_error()); 
        $row = mysql_fetch_array($query) or die(mysql_error());
        if(!empty($row['userName']) AND !empty($row['pass'])){
            print(json_encode(array('flag'=>1)));
        } else { 
            print(json_encode(array('flag'=>0)));
        }
        exit;
    ?>