Oct 31, 2013

Random Numbers or Password or Pin in MySQL

To obtain a random integer R in the range i <= R < j, use the expression FLOOR(i + RAND() * (j – i)). For example, to obtain a random integer in the range the range 7 <= R < 12, you could use the following statement:
SELECT FLOOR(7 + (RAND() * 5));

To generate between 1000 to 9999, i.e., 4 digits then you can do the following using update query
 
 UPDATE users SET password = FLOOR(1000 + RAND() * 8999);

Oct 21, 2013

Force HTTPS & WWW using htaccess

RewriteEngine on 

RewriteCond %{HTTPS} off

# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Now, rewrite any request to the wrong domain to use www.

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Jun 25, 2013

Get Latitude & Longitude from address

function getLatLong($address){
    $prep_addr = str_replace(' ','+',$address);

    $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prep_addr.'&sensor=false');

    $output= json_decode($geocode);

    $lat = $output->results[0]->geometry->location->lat;
    $long = $output->results[0]->geometry->location->lng;

    return array("latitude" => $lat, "longitude" => $long);
}

Read .docx file as string

I found it after googling for a day, finally a function that reads the .docx file and return you a string. Hats off to the original author of this function.

function readDocx($file_name){
    $striped_content = '';
    $content = '';
    if(!$file_name || !file_exists($file_name))
        return false;

    $zip = zip_open($file_name);
    if (!$zip || is_numeric($zip))
        return false;

    while ($zip_entry = zip_read($zip)) {
        if (zip_entry_open($zip, $zip_entry) == FALSE)
            continue;
        if (zip_entry_name($zip_entry) != "word/document.xml")
            continue;
        $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
        zip_entry_close($zip_entry);
    }// end while
    zip_close($zip);

    $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
    $content = str_replace('</w:r></w:p>', "\r\n", $content);
    $striped_content = strip_tags($content);
    return $striped_content;
}

Jun 18, 2013

Convert object to multi dimensional array

   /**
    *
    * Convert an object to an array
    *
    * @param    object  $object The object to convert
    * @reeturn      array
    *
    */
    
function objectToArray$object )
    {
        if( !
is_object$object ) && !is_array$object ) )
        {
            return 
$object;
        }
        if( 
is_object$object ) )
        {
            
$object get_object_vars$object );
        }
        return 
array_map'objectToArray'$object );
    }

    
/*** convert the array to object ***/
    
$array objectToArray$obj );

    
/*** show the array ***/
    
print_r$array );


 Taken from phpro.org

Feb 28, 2013

JSON array of objects

It can be a situation where you got a array of data that should be sent in the JSON format to server via ajax, then you can do the following

<script type="text/javascript" >
groups = ['A', 'B', 'C'];
users  = ['user1', 'user2', 'user3'];

//required format is  [{"group_name" : "A", "leader" : "user1"}, {"group_name" : "B", "leader" : "user2"}, {"group_name" : "C", "leader" : "user3"}]

group_leaders = new Array();

len = groups.length;

for(var i = 0; i < len; i++ ){
    group_leaders.push({"group_name" : groups[i], "leader" : users[i]});
}

alert(JSON.stringify(group_leaders));
</script>

Here you can test here http://jsfiddle.net/sailesh/6wXdY/

Feb 26, 2013

Windows Azure SQL Database PDO

I faced a problem while trying to connect Windows Azure SQL Database from local system using PDO. Here I'm using PHP 5.4+ and Apache 2.4 on Windows 8. I didn't find better tutorial for trouble shooting.

Following are the steps that explains you what to do..

  1. Download php_pdo_sqlsrv_54_ts.dll and placed it in php/ext directory. Here you can find it
    http://www.microsoft.com/en-us/download/details.aspx?id=20098
    Download SQLSRV30.EXE and extracted to php/ext directory
  2. Open the php/php.ini file and added the following line
    extension=php_pdo_sqlsrv_54_ts.dll
  3. It needs Microsoft SQL Server 2012 Native Client, to go further. So download it from
    http://www.microsoft.com/en-us/download/confirmation.aspx?id=29065
    for 32bits(x86)
    http://go.microsoft.com/fwlink/?LinkID=239647&clcid=0x409
    for 64bits(x64)
    http://go.microsoft.com/fwlink/?LinkID=239648&clcid=0x409
  4. Restart the Apache server.
  5. Write the following code in php file to connect.
    <?php
      $server_url = "xxxxxxx.database.windows.net,1433";
      $db_name = "database_name";
      $db_user = "db_username";
      $db_pwd = "db_pword";
      $conn = new PDO("sqlsrv:Server=tcp:$server_url;Database=$db_name", $db_username, $db_pwd);
      $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    ?>
  6. Fetching data from table
    <?php
      $query = "SELECT * FROM categories";
      $stmt = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
      $stmt->excute();

      while($cat = $stmt->fetch(PDO::FETCH_ASSOC)){
        echo $cat['cat_id']."---".$cat['cat_name']."<br />";
      }
    ?>
That's it...

Feb 1, 2013

Download file using PHP

Downloading a file can be done in two ways:

  1. Direct download
  2. Indirect download
Direct Download:
Assumptions:
File location: c:/xampp/htdocs/project/docs/test.doc
URL: http://localhost/project/docs/test.doc

Code:  <a href='http://localhost/project/docs/test.doc'>click here</a>

Indirect Download:
(recommended)
Assumptions:
File location: c:/xampp/htdocs/project/docs/test.doc
PHP file for the download code:
location: c:/xampp/htdocs/project/download.php

<?php
  $file_name = $_GET['file'];
  $file_path = "docs/".$file_name;

 //setting the content type
  header('content-type: application/octet-stream');

  //downloads file as attachment
  header("content-disposition: attachment; filename='$file_name'");

  //actual file path
  readfile($file_path);

?>

Note: content-type application/octet-stream can be used for any type of file.

To use the above file for download. Create link like as below
<a href='http://localhost/project/download.php?file=test.doc'>click here</a>

For any queries or clarifications post a comment.