Jan 18 2015

My Programming Blog: http://lokalhost.in

Category: Uncategorizedksg91 @ 11:57 am

Hi,

It’s been a pretty long time since I last posted here. I have decided to resume blogging but my all programming related blog posts will be on my new blog which is dedicated to programming stuff only. Please bookmark my new blog: http://lokalhost.in

I may continue to post general posts (rants!) on this blog posts.

Hope to see you there. 🙂

 

Tags: , ,


Jul 09 2014

Introduction To Microdata and Google Rich Snippets

Category: SEO,Tips & Tricksksg91 @ 11:29 am

[slideshare id=36777442&doc=microdataplus91technicalpresentationkishangor-140709004543-phpapp01]

HTML5 is taking web documents to a next level, by adding semantics. HTML5 contains several semantics elements but they are not enough to annotate your content. You can tag your content with Microdata to build a better web document which can be understood by machines. 

I created this presentation as an activity in my company to provide introduction to Microdata, one of the most popular format to add semantics to your content. It will also give a brief about Google Rich Snippets.

Feel free to share it and ask any questions. You can connect with me @ksg91.

 

Tags: , , , , , ,


Dec 29 2013

Testing @Tweet_My_Post with Media Upload

Category: Uncategorizedksg91 @ 1:40 pm

banner-772x250


Jun 20 2013

Sort observableArray of Objects in Knockout.js

Category: PHP,Programmingksg91 @ 6:32 pm

Lately, I have worked good amount of time with knockout.js and to be honest, I have been quite impressed with the dependency tracking of ko.js , no doubt, performance sucks sometime if you don’t take enough care.

Knockout.js offers a sort method for observableArray which sorts the array alphabetically (for strings) or numerically (for numbers). But consider a case when observableArray is of some objects or say you need to sort the array on some special condition. Just sort() method won’t work.

ObservableArray.sort() methods allows you to pass a function. Your function will be passed two objects and now it is up to your function how to sort them. Your function should return a negative value if first object is smaller (in your term), a positive value if first object is great, zero if both are equivalent.

For example, let’s say you have a observableArray of product object and you want to sort the array based on the price,  you may do something like this

[javascript]
function myCompareFunction(a,b){
if(a.price()<b.price()){ // if price is observable
return -1;
}else if(a.price() > b.price())
return 1;
}else {
return 0;
}
}
myObservableArray.sort(myCompareFunction);
[/javascript]

Similarly, you can sort your observableArrays. It is up to you on how you want to.

Tags: , , , , , , , ,


Mar 01 2013

HOW TO STORE A FILE AND MAKE IT DOWNLOADABLE?

Category: PHP,Programmingksg91 @ 8:00 pm

HOW TO STORE A FILE AND MAKE IT DOWNLOADABLE?


I often come across this question and new comers often find it difficult to understand. Let me put this thing in simple way.

What do we need to do this?

To make this possible, we need to do following simple things:
  1. Store file at some permanent location
  2. Store data about file
  3. Serve the file whenever user request for it.
 
If we simply move uploaded file to a particular location, we may end up overwriting a file which was previously uploaded and had same name. To cope with this issue, we may rename the file and try to generate a unique name to avoid collision. 
 
I usually follow following approach:
 
[php]
//! Generate a unique file name
 $uniqueFileName == md5(uniqid('',true));
//! Generate a upload path
$uploadfileTo =  UPLOAD_PATH. $uniqueFileName ;
//! Move to permanent location
move_uploaded_file($file['tmp_name'], $uploadfileTo);&amp;lt;br /&amp;gt;[/php]

uniqid() generates a random string. First argument is prefix for the random string. If we pass second argument as true, a string with more entropy will be generated , i.e. more random numbers. We are hashing the generated string using md5 algorithm. You can also use the hash of combination of timestamp and output of uniqid().

Now if we have store the file, we will need information of file in our database.  I would recommend storing at least this details about file:

  • File’s original name
  • File’s extension
  • File’s Content-Type / MIME type
  • File Size
  • Storage location
  • File’s generated name
Now when you’ve store this information in database, you can create a download page. This can be achieved in two ways.
  1. Redirect user to the URL of actual stored file.
  2. Create a proxy page which will serve the content of file.
Problem with first approach is that, actual storage URL is known and you have no control over who is accessing it.
 
I will recommend using second approach. To do so, we have to tell browser that the php page is actually an original file with particular content type. Browser identify the document based on the HTTP headers. So, we can achieve this by simply passing proper HTTP headers. PHP allows us to send HTTP headers using function header() .
 
On a download page, you can simply retrieve details of original files. Suppose we have those details in self explaining variables below, we can serve the file using following code snippet:
[php]
//! pass content type header for the file
header("Content-type: {$sContentType}");

//! force browser to download the content
header("Content-Disposition:attachment;filename='{$sFileName}'");

//! load the content of the file
readfile($filePath);
[/php]

And that’s it. Your file will be served to user with original name and content type. And user will actually never know the real location. 

Common issue people face with this is, file is downloaded properly but when they open it, they realized that the file is corrupted. This happens because you are sending some other output to the browser also as payload along with content of file. You may have some code which is echoingsomething.  You can also use output buffering to stop sending anything to browser except the actual content. Use output buffering, before you readfile flush the output buffer and then read the file.


Nov 06 2012

Generating List of affected file from patch files of Git with PHP

Category: PHP,Programmingksg91 @ 8:44 pm

No doubt, Git is a best thing you can use for managing your code. But sometimes you really put yourself in such a worse situation that you start cursing yourself for using Git. I am working on a fairly large project and been working in teams, I had to switch to another branch because the code base I had was greatly differing from the one on git but I had to work with that source because of some reasons. Being base code not being same as Git’s master, I made a commit and started working on that. I cannot simply merge because there were total 20k+ files with code and almost impractical to go through most of them to resolve the conflicts.  I thought of then applying patch for all the later commits. It started giving me lot’s of conflicts too. The files I worked on were not touched by others so simple thing was to take all the files that I edited and to use them. I am no git expert and quite lazy to find the way to do so.  There can be several nice way to deal with this situation using git only but as I said, I am no git expert. And that is not this post is about.

So I created a simple php script that can read and identify the files that were affected in that commits. I thought to share the code, so this is the post.

As I explained already, I had created serial patch I can read from it the affected files. Being quite short on time, wrote a quick code, which may be improved in efficiency and accuracy.

Here is the script I wrote:

[php]

<!–?<span class="hiddenSpellError" pre=""–>php
$result=”;
for($i=1;$i<89;$i++) {
$fname=glob(‘patch/’.substr("0000".$i,-4)."*");
$entry=$fname[0];

$content = explode(‘diff –‘,file_get_contents($entry));
$content = $content[0];
$re="/([a-zA-Z0-9_]+)(\.php|\.js|\.css)/";
preg_match_all($re,$content,$out, PREG_PATTERN_ORDER);
$out[0]=array_unique($out[0]);
foreach($out[0] as $val){
$result[$val]=true;
}
}
foreach($result as $key=>$val){
echo $key."<br />";
}

?>

[/php]

Explanation

Simple thing to do was to read each patch and look for a filename. I used three extensions to look: .php , .js, .css . I put the folder in a directory and put patches in the subdir patch/

Format for patch file name was a serial number starting from 0001 up to the number of files. I simply generated name myself using glob(). I am sure you will argue why didn’t I simply read the directory. Actually, my initial code cause script to exceed the timeout and I was not sure if it was the number of file or something else. So I thought of controlling the number of files. So was the code like this.

Reason for so long execution time was preg_match_all on a long patch files (couple of them were 20 MB! ). We don’t need to search for the files in changes, only portion containing  the list of files was important so I simply search for file names in that portion by exploding contents to diff — and searching in first array value.

To maintain the unique list, I used file name as index so unnecessary memory space does not get wasted. I believe rest of the part makes sense without any explanation.

Above code was enough and efficient in my case. Let me know what you thing about this.

Tags: , , , , , , ,


Oct 16 2012

Tweet My Post is Back, Working

Category: Programming,Tweet My Post,WordPressksg91 @ 12:48 pm

Sorry for the inconvenience, guys. Tweet My Post was not working for last 4-5 days and I only got to know about that 2 days back.

Being quite busy in office projects, I didn’t have enough time to look after my plugin. But I have already released the hotfix which has solved the issue. Tweet My Post is working again.  Go and update the plugin from your admin panel or download it from http://wordpress.org/extend/plugins/tweet-my-post/ asap.

My plugin uses https://github.com/jmathai/twitter-async library for Twitter API. It uses version 1, which is deprecated. However version 1 should work till March 2013 but it was returning “Page Not Found” error for last 5 days. I don’t have clue what has gone wrong with Twitter API or this plugin and I don’t have enough time to look into that either.

I fixed the issue by changing the version to 1.1 by updating line number 25 in EpiTwitter.php to

[php] protected $apiVersion = ‘1.1’;[/php]

You can also use library’s function to update version to 1.1 by using

[php]$EpiTwitter->useApiVersion(‘1.1’);[/php]

before sending any request.

I’ve sent the pull request already to Github. Author of library will unit test the changes and merge it asap. You can use updated version by downloading it from https://github.com/ksg91/twitter-async until it is merged.

Tags: , , , , , , , ,


Oct 15 2012

Test Post

Category: Tweet My Postksg91 @ 5:03 pm

Test Post


Jul 19 2012

Transferring Data Securely on HTTP using PHP

Category: PHP,Tips & Tricksksg91 @ 4:23 pm

Image courtesy of MIT OCW.

Well, I have been working on a WordPress plugin and I required to transfer some data from client’s host to my host. Data is Access Token and Secrets for their Twitter account (Of course, not to store it on my host but to perform their operations on Twitter). Being sensitive data, it was required to transfer them securely over the network, keeping it secure from at MITM attacks. As a option, I can use buy a IP and SSL certificate and transfer it using HTTPS. But, being a free plugin, I really didn’t want to spend money in such things. And only option I was left with was to use HTTP and transferring data encrypted.

For this, client will register to me and avail its access token and secret (not of twitter, but for my site). There were multiple data and instead of encrypting them independently, I decided to make a class named Request which holds all the data to be transferred.  Now this request class is serialized and then that string can be encrypted.

I use following code snippet to encrypt :

[php]
$req=serialize($this->request);
$req=$this->key.$req;
$this->enc_req = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($this->acc_sec), $req, MCRYPT_MODE_CBC, md5(md5($this->acc_sec))));
[/php]

Here,

[php]$this->key[/php]

is Access key given to user and

[php]$this->acc_sec[/php]

is Access Secret given to the user.
Let’s check example of this encryption:

Object Request:

object(Request)[1]
  private 'tmp_key' => string  '___' (length=16)
  private 'tw_acc_tok' => string'blah' (length=4)
  private 'tw_acc_sec' => string 'blah 1' (length=6)
  public 'tweet' => string 'Tweet' (length=5)

Serialized Object

string

 'O:7:"Request":4:{s:16:"?Request?tmp_key";s:16:"___";s:19:"?Request?tw_acc_tok";s:4:"blah";s:19:"?Request?tw_acc_sec";s:6:"blah 1";s:5:"tweet";s:5:"Tweet";}' (length=168)

Encrypted Object

string

 'NxFivVICmrRzh/fSlvT3jeWrT8pdvWRKPPc9lpEe1g1MoYgvom2/Sg6kqm0sqQ/PeYIeJXCahQSubW78CbHzBfMcIXsBCmAistVq/XvkZUSe5Hb5OWIr1D3AiGb5943BO9E2reUKr0GJYyIS+Lxrh1mTvSdpbcu9twt7qqhay6dU77icqu8jdvDBs7XrBTTxDFNS57Cl8KYSICInrJ30nwT8CqLHZdsA4poAhZm7TeIV7xp+bUmRAF5WXV6QUlKm' (length=256)

 Now, this encrypted data is sent to me using cURL and Access Key and encrypted text is send along with it.

On my end, I have access token and secret stored in my database, so I will decrypt the request using the access secret that I have stored in my database with the requesting access token. Following code will help me to recover original Request object:

[php]
&nbsp;
<pre>
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
$so=substr($decrypted,strlen($this->key)+1);
$this->request=unserialize($so);

[/php]

I have used Access Key as a salt. Of course, it’s not the only thing I am going to use to achieve higher security. But I believe, this will be enough to give you an idea of how we can achieve a certain level of security. I am not quite sure how secure this method is, but surely enough for my application.

Please feel free to post your views and comments on this. Hoping, this helped. 🙂

Tags: , , , ,


Jun 07 2012

How to use Virtual Box to install Windows 8

Category: Tips & TricksGTX OC @ 10:37 am

How to use Virtual Box to install Windows 8

Microsoft recently released the Windows 8 release preview and I couldn’t resist trying it out . Problem was that I didn’t have an empty partition . So what did I do ? I used Virtual Box(by Oracle) to create a virtual machine and run the release preview inside Windows 7 and today I will show you how to do it .Basically virtual box allows you to create a virtual machine inside an OS to run and install other OSs in a safe environment .

This article is divided into two parts : The Lock(where we prepare a virtual machine) and The Load(where we will actually install windows 8 on the virtual machine) .

Before beginning I would recommend you have 4GB of RAM or more and a graphics card with 256mB frame buffer or more . Make sure you have around 20GB of space free in a partition .Download(and install) Virtual Box from the oracle website and an iso image of Windows 8(32 bit or 64bit).Make sure you note down the product key just below the download links in the Microsoft page.

My system specs:

  • Intel Core i5 -750
  • Intel DH55TC
  • 8GB DDR3-1333Mhz RAM
  • AMD Radeon 5770(1GB)
  • Seagate Barracuda 1TB HDD
  • Corsair VX550W

Right on with the guide .

The Lock:

1)  Fire up Virtual Box and click on New .

Step 1

A wizard will pop up and we will follow the instructions .Click on Next.

2) Enter a name for your virtual machine and below that select Microsoft as Operating system and if you like me downloaded the 64 bit make sure you select the version as Windows 8(64 bit)

3) Select the amount of RAM that you would want the virtual machine to use(you can change it later if you wish) and click next .I would recommend using 2048mB RAM for a good experience.

4) Probably the most difficult step in this guide 😛 is to prepare a virtual hard disk . Select create a new hard disk and click on next . The create a new virtual hard disk wizard will pop up. Select the file type as VDI(virtualBox Disk Image) . Click next.

5) Would recommend “fixed size” . 

6) In this step you have to give a name for your virtual hard disk as well as decide its size and select the location where you want to create it(to select the location,click on the folder icon next to the text field where you entered the name of you virtual disk).

8) Click on create . Virtual box will create your virtual disk, it took around 5 minutes on my system .

After the disk has been created you will again be taken back to the original screen and you will see your virtual hard disk listed on the left side(see first screenshot) . Now we are ready to install Windows 8 😀 .

The Load

1) Select you virtual hard disk and click on start .

2) A window will pop up telling you that the host key – right control key can be used to capture and focus the cursor and keyboard into your virtual machine.Check the “Do not show this message again” if you well don’t want to see the message again and click OK .

3) A wizard will pop up and will guide us through the installation . Click on Next .

4) In this step you will select your iso . Click on the folder icon and browse to where you have downloaded the iso image . Select the iso and click open . You will see under “media source” the name of the iso will appear . Onward .

5) We will now start the installation of Windows 8 Release Preview .

Select Language to Install as English(United States) or whatever language you want along with the Time and currency format and keyboard input .

6) Enter the product key that you have noted from the Microsoft web page .If you missed it , here is the product key :

TK8TP-9JN6P-7X7WW-RFFTV-B7QPF.

7) Select custom:install windows.

8) You will only see a single disk(which is the virtual hard disk) as you have mounted windows 8 onto your virtual hard disk. We are almost done now . Click next and Windows will begin installing onto your virtual hard disk .Hang in there.

9) When the installation is complete, windows will reboot .

10 )After the reboot you will have to select the colour scheme , some basic settings and log into your windows live account(if you have one) or create one/log into an offline account and enter your phone number . Windows will reboot again and load your settings and get all the devices ready.

And you are good to go with Windows 8 release preview.Hope this helped .

Notes:

  • If you see black bands in Windows 8 along the breadth of your monitor , you will have to install guest additions on your virtual machine . In windows 8 , press the right ctrl key + D and follow the on-screen instructions to install Guest additions .
  • If your machine is very slow , stop the virtual machine . Right click on your virtual machine and select settings .Select System and under system select processor . Now move the processor slider to the number of cores that your processor has.
  • Sorry for the cursor in few of the screenshots .
  • It took me around 12 minutes to install Windows 8 .


Tags: , ,


Next Page »