Accessing PHP Cookies from different directories or domain path

February 25, 2010 by rooturaj  
Filed under Programming





It is pretty easy to work with cookies. They are really tasty. I am talking about PHP cookies and yeah we programmers can taste them. I will be highlighting some ‘not so common’ points about cookies today. Ready?? Lets Go.

What are Cookies?

These are little bits of information stored on your computer by a website. The specialty of these bits is that they can only be opened by the site that stores it in first place. So Google’s Cookies are invisible to Yahoo’s and same the other way round. Cookies can be set for a particular time span and deleted by the site that created it. The user can also clear cookies whenever he wants to from his browser or manually from the personal folders of his system.

Now we know that Cookies are store houses for secure information that we webmasters use to dish out customized content to our visitors. They are widely used for storing user login information and shopping cart contents so that even if the user closes the browser and comes back the site allows access and restores his shopping cart. We could even use it to store your theme choice for sites or to tell you when you visited last time.

How to set a cookie Using PHP?

Its pretty easy. Use this  code.

<?php 

// set a cookie named 'pingu' with a value of 'Penguin'
setcookie('pingu', 'Penguin');

?>

Recalling and using the set Cookie

We use the super global variable $_COOKIE  to  call the stored value of cookie the same way we do with $_GET and $_POST.

<?php 

// We  will  use ‘pingu’ cookie  in a sentence.
echo "Pingu is a ".$_COOKIE['pingu']."."; 

?>

Output: Pingu is a Penguin

Setting  a  time span for your cookie.

For security purposes we need to set some cookie expiry time. Some sites even ask the user how long to store his cookie. Others have a default expiry period. After this time your cookies is dead and you need to log in again to use the site. (or any other similar functionality)

<?php
$time = 7*24*3600 + time() ; //no of secs to store the cookie

// set a cookie named 'pingu' with a value of 'Penguin' for  2  days
setcookie('pingu', 'Penguin', $time);

?>

Accessing a Cookies from a different directory of domain.

Now when using the previous methods to set cookie will restrict the access to the directory where it was originally set. Eg. If you set the cookie on file domain.com/user/setcookie.php you cannot retrieve the cookie  on domain.com/member/getcookie.php. To get around this we need to set an accecibility parameter as well. See below.

<?php

// set a cookie named 'pingu' with a value of 'Penguin' for 2 days  through out the domain.
setcookie('pingu', 'Penguin', $time, “/”);

?>

Now you cookie can be called from any part of the domain.  But it’s a not much recommended. Similarly you can specify particular directories/folders to access the cookie. Like “/user/” or “/member/” instead of “/”.

Overall Syntax format – setcookie (‘[string]’,’[string]’,[integer],’string’);

Setting Excel background and Printing a Spread-sheet with Background

February 2, 2010 by rooturaj  
Filed under Software





This post is to address an every day issue that you face when working with spread sheets (MS Excel – OpenOffice Spreadsheets etc). We normally cannot print spreadsheets with a background. I mean when you print the document it does not show the background graphic.

When confronted with this problem I googled it up. (Sorry can’t help. it’s a habit) Now Microsoft, as we all know, are charming people who love it when you have trouble using their product. They said “This issue occurs because background graphics cannot be printed in Excel.” How smart and what a useful answer. Guess what they even ask “Did this information solve your problem?” I felt like kicking that bloke who wrote this in the ‘you know which’ place.

Ok enough.. Now here is the solution.

Setting a background for your Microsoft Excel Spreadsheet

backgorund-excel

I hope the screen-shot would suffice. All you need to do is go to the main menu. Then Choose Format >> Sheet >> Background.

Browse the image file and select it.

The back ground will get tiled all over the work area. There is no overriding this I guess. So choose a proper sized graphic to fit your printable area.
Tip: Use white space around the image (photoshop or other graphic tool) to fit it wherever you want on the printable area. See this example.

Seriously I do

Seriously I do

Now if you want to print the same you would never get the background. Try and check the print preview.

So How to Print the Spreadsheet along with the Background?

Save the file as webpage. (.html or .htm)

Then open the file in your browser and print as you like. Remember to do the print set up properly. On my Firefox I do this.

print-setup

Hope that helped.

PHP Image Resize script – Resize Images on the fly

January 30, 2010 by rooturaj  
Filed under Programming





What does this Script do?

It changes the dimensions and hence the file size of  image files on the fly. All you need to do is specify a source file, set the new dimensions and this PHP class will generate the new re-sized image for you.

Who should use this?

Any one who needs to re-size their images automatically.

For example: If you need to generate thumbnails for the images uploaded to your image sharing site then this is the solution for you. Sometimes we need to display smaller images to save band width and improve page load time.

What does this need?

PHP 5 + GD Library

(and of course the image files to manipulate and apache server)
To check if you have got GD library on your PHP bundle Create a php file with the following code and run it.

<?php
phpinfo();
?>

Let’s get working then.

Here is the Class File. It contains two functions resize() and resize_const(). The first one only takes in a width value with the source file and generates a new image with height in constrained proportions. While resize_const() takes in width, height and source file to generate an image of exact dimensions.


<?php
class ImgResizer {
private $originalFile = '';
public function __construct($originalFile = '') {
$this -> originalFile = $originalFile;
}
public function resize($newWidth, $targetFile) {
if (empty($newWidth) || empty($targetFile)) {
return false;
}
$src = imagecreatefromjpeg($this -> originalFile);
list($width, $height) = getimagesize($this -> originalFile);
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
imagejpeg($tmp, $targetFile, 85); // 85 is my choice, make it between 0 – 100 for
//output image quality with 100 being the most luxurious
}

//the function below will get you an image with the width and height values set by you.
// In case you need exact size images.
public function resize_const($newWidth,$newHeight, $targetFile) {
if (empty($newWidth)|| empty($newHeight) || empty($targetFile)) {
return false;
}
$src = imagecreatefromjpeg($this -> originalFile);
list($width, $height) = getimagesize($this -> originalFile);
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
imagejpeg($tmp, $targetFile, 85); // 85 is my choice, make it between 0 – 100 for output image quality with 100 being the most luxurious
}
}
?>

Using the Class and the Functions.

Use the code below in as where ever you want it to work. (I am sorry but that does not include pasting the code on your photo frame)


<?php
$work = new ImgResizer('path/to/original/image.jpg');
$work -> resize(75, 'path/to/resized/image.jpg');
$work = new ImgResizer('path/to/original/image.jpg');
$work -> resize_const(200,150, 'path/to/resized/image.jpg');
?>

This is not my original code. I am building upon this base.

Kaspersky Detects Trojans in Google Adsense

January 25, 2010 by rooturaj  
Filed under Online Security





I don’t know if it affects you or if my Anti-Virus is just acting up but every time I force refresh a page with Google Adsense with it Kaspersky (ver: 8.0.0.454) Internet Security detects a Trojan on the google javascript file. This even comes up on leading sites like lonelyplanet.com.

Here are the details.
To force refresh I mean using CTRL + F5. Then my antivirus gives this message.

Kaspersky detects Trojan on Site with Adsense

Kaspersky detects Trojan on Site with Adsense

On further checking of this report Kaspersky gives me the following actions and errors.
This is the actual error report on Kaspersky. 1/25/2010 8:01:18 PM- http://pagead2.googlesyndication.com/pagead/show_ads.js Firefox Processing error: Trojan.JS.Redirector.ar

Report points to Adsense file

Report points to Adsense file

I get the same issue on IE6 with Kaspersky. On Internet Explorer I with Kaspersky installed I get an Additional Error. See Below.

Issue duplicates on separate machine with IE6 and Kaspersky

Issue duplicates on separate machine with IE6 and Kaspersky

I have no idea whats going on. After a basic search on Google I found this related post. But this is an old case and the ads are not being hijacked. From the report it seems it is the original Google Adsense Javascript file that is being detected as malicious.

If some of you have kaspersky could you please test this issue at your end and let me know. I will mean while report this to Google.

Google Says Bing is the Best Search Engine – OMG Bing Is King

January 23, 2010 by rooturaj  
Filed under Search Engine Optimization





Just out of curiosity I searched the term “Search Engine” on Google. I was actually testing if Google returned google.com for the term “search engine”. This is what I got. (see snapshot below)

Wow, according to Google, Bing is the No One Search Engine on the planet. Interesting, eh?

google-says-bing-is-king

Bing Is King - Google

This was the result on google India. There were different results on Google.com.

So to what extent are these listings valid? Shall we take that as the real results? I do a wee bit of SEO so I ask from the SEO angle. Is it possible that Bing could have mustered more backlinks than yahoo and Google for the keyword “search engine”. I wonder.

What does Google want here? May be they feel shy suggesting their own name when someone asks them ‘which is the best search engine around’.

Well there is always the obvious fact that we must consider here. Since the search is being made on Google the user is aware of Google. So the result google.com looses relevance. But that does not answer the question? Is this factor included in the algorithm? If no, then these are filtered results with the previously mentioned factors included.

But if you want to filter yourself then go off completely. What does it mean when google.co.in and google.com feature on the next page of results after www.123khoj.com and www.mamma.com . I say these results are strange. What do you say?

Hacking into your life through your emails

January 20, 2010 by rooturaj  
Filed under Online Security





I am going to share with you a funny but serious event that unfolded in my Inbox yesterday. There is a silly job listing site in the name of jobszone.info. They blast bulk mails to thousands of people about latest job openings. Yesterday I received a mail from them that reads.

mail from idiot

Now what does a user like me do in this case. Carelessness like this leads to the hacking of email accounts and corporate websites.

Here is how a hacker would proceed once he is fed with information like this. I am not a hacker but I have read about them and I am somewhat familiar with their train of thought. Thanks to recent events like Iranian attack on Twitter.and previous Twitter Admin hack news.

So first of all we try out popular mail portals like Gmail, Yahoo, Hotmail, AOL etc. If our trial yields no result then we try to access the webmail accounts using urls like domain.com/webmail or mail.domain.com. How to find out the site? Use google for the most relevant term from the mail. It is not always that easy though.

In my case I struck gold with Gmail. Though I tried the domain.com/webmail approach first as the mails seemed to originate from the said website.

Normally what first timers would do is reset the password. But that is the stupid thing to do. Don’t let the original user suspect that the account has been compromised.

Next search for password or username using mail accounts search feature. Gmail in this case is just wow. I got around 40 results. This idiot left an excel file with a list of user ids and passwords for some 25 accounts. Wow. I can further use the same to get into more classified information. May be I could find some credit card details too but my ethics stop me going beyond this. LOL

Additionally one could use Gmail labels or folders in other email clients to reach out to specific information on your email accounts.

I hope this malicious email account access process would give you enough ideas about how to protect your accounts from being hacked. Many large organizations like twitter have been hacked using this very method.

This has been a long post already. Watch out for my next post that is a list of steps to keep your accounts safe from hacking.

Mom I am not Ready yet | Womb Raiders forcing prenatal competition

January 11, 2010 by rooturaj  
Filed under Gadgets, Society and Nature





3-idiotsYesterday I saw the movie 3 Idiots. This is a true tale of India’s educational system. It is competition form day one after your birth. If you are in a metro city like New Delhi and Mumbai you know how difficult it is to get into a decent school. What right do we have to kill the colorful world of  a four year old kid. They have to sit interviews and are bred to see their friends as competitors. (img Src : Santabanta.com)

While scanning through some of the products online at the CES 2010 I came across some weird ones. This particular device called “BabyPlus Prenatal Education system” has been intriguing me for the last few hours. Was it not enough that you are taking the fun out of kids at the age of 3.  Isn’t Home work and ranking system a curse big enough?  You want to ruin their lives even before they see the light of the world?

Womb Raiders

Womb Raiders (src:usposttoday.com)

This device produces a range of sounds that mimic mother’s heart beat. Their bull shit research shows this will make your baby more “interactive, responsive, relaxed and alert”.  I might put it in another simpler way if you would like to hear. Your child will be “stressed, restless, pissed off and sleep less”. The mother has to wear the device two times, one hour each time. If you can hear the poor chap inside, it is saying – “Mom – I am not ready yet.”

If the mother’s heartbeat was that good for the fetus then the wombs would be the chest and not in the pelvis. Nature has had a longer time experimenting with us than these people. I am not against technology but something like this that is totally profit motivated and has the potential of deeply influencing out social setup should be controlled; better banned.

To end my rambling I say the power still lies with the consumer. Tell them what you want for your kid. They have a life of their own. Don’t force it upon them. Let them choose.

Adding a Facebook share button and Digg this button with tweetmeme retweet button in wordpress thesis theme

November 5, 2009 by rooturaj  
Filed under Programming, Social Media, Technology





I guess the thesis theme is among the most popular wordpress themes among professional bloggers. The best part about the theme is its ability to support custom functions and styles. So virtually everything is possible.

After I tried my hands at Thesis theme for Wordpress I added some plugins. I need not explain to you the merits of social media sharing buttons. The hottest in this section are Twitter, Facebook and Digg. Especially the share buttons with the counter are must haves for any blog. You get the code to add these buttons from the official portals. There are plugins to achieve the same. But it’s hard to get all three of them or two of them next to each other using different plugins. The example is right on this post.

If you need to have some thing like this on your blog, then follow this simple guide. I have put in screenshots to help you in process. We will be tinkering around with the coding. So some hands on experience with PHP and HTML is welcome. Else you can follow the coding exactly as it is and hope for the best.

Most popular and accurate Re-Tweet button with count comes from tweetmeme. They have a wordpress plugin for that. I am going to add official Facebook and digg share buttons with share count display to the tweetmeme plugin. In this example I am messing with Thesis wordpress theme. You can do the same to any theme you want. It only changes the code of the plugin so – a theme independent solution.

Browsing to the Tweetmeme.php file in wordpress

Browsing to the Tweetmeme.php file in wordpress

I believe you have a self hosted wordpress blog.

>>So navigate to the wp-content folder.

>> >>Find the plugins folder. Enter

>> >> >>Find the TweetMeme folder. Enter

>> >> >> >> locate this file tweetmeme.php

Now we tinker with the code. To do so, download the file to local system and open is with some standard text editor. I am using dreamweaver. Now look for this function in the code ‘tm_generate_button()’. Use the find feature in your text editor (ctrl +f ) to find this function. The code is rather long so might be hard to do it manually.

Editing the code

Editing the code

The red bordered area is where we do the actual change. You will have something different in the original file. Now add this code to the $button variable so that the final code looks like above.

<br><br><script>var fbShare = {size: \’large\’,google_analytics: \’true\’}</script><script src=”http://widgets.fbshare.me/files/fbshare.js”></script>
<br><br>
<script type=”text/javascript”>
digg_url = \”.$url.’\';digg_title = “TITLE”;

</script>
<script src=”http://digg.com/tools/diggthis.js” type=”text/javascript”></script> </div>

Replace the file and enjoy. Download this php file right here if it is too much for you.

You can do your own modifications to suit your purpose. Replace the <br> with spaces to get a horizontal effect. Feel free to comment.

RESTful time for PHP developers working with ADO.NET

September 7, 2009 by rooturaj  
Filed under Programming, Technology





Microsoft’s open source community manager, Peter Galli reported on this post about the new technology to bridge Microsoft .NET developer’s platform and widely popular PHP server side scripting language. The open source community is glad that this finally came up. PHP programmers can now connect to ADO.net data services with ease. It was not possible for Apache based clients to draw data form MS SQL servers with .net platform.

They use RESTful service interface to connect the previously stranger (to each other) internet data sharing methods. Sources say that full support will be available in Visual Studio 2008 SP1 and the forthcoming 2008 build.

Full report at http://news.idg.no/cw/art.cfm?id=3E8FFC06-1A64-6A71-CEB8414EFC373373

The PHP toolkit is available at Microsoft CodePlex site for open source projects.

Disable Javascript on IE8 /IE7 (Internet Explorer) : Common Mistakes

September 4, 2009 by rooturaj  
Filed under Programming, Technology





I was surprised when one of our engineers asked me – “ How can we disable Javascript on Internet Explorer?” He was testing Javascript validation and precautions against bypassing this layer of validation. As usual he googled it up and tried something. But it would not work. When I arrived at his system he showed me what he was doing to disable javascript but it was still working.

There was just one thing he was over looking. This I guess is one of the common errors people face while disabling javascript on Internet explorer.

In case you do not know how to do it here is a picture guide for you.
1.Open your Internet Explorer browser window.
2.Go to the menu and click on TOOLS
3.Choose Internet Options. (See below; it might help)

Step One - Tools>Internet Options (Disable Javascript IE)

Step One - Tools>Internet Options (Disable Javascript IE)

Once you open the Internet Options then
4.Click the Security Tab. (Use the picture below as guide)

Step 2 >> Choose Security Tab (Disable Javascript IE)

Step 2 >> Choose Security Tab (Disable Javascript IE)

Now here is the trick. The Zones. By default the Internet Zone is selected. So if you proceed further you would be able to disable Javascript on websites that are live on internet. If you are developing / testing on local files then it would still be working. So choose what you want. In our case, since we were working locally we have chosen the Local Intranet option.

Finally
5. Scroll down till you find the Scripting Option.
6.On Active Scripting Radio Button choose Disable.(Use the screen shot for reference)

Step 3 >> Disable Active Scripting (Disabling javascript IE)

Step 3 >> Disable Active Scripting (Disabling javascript IE)

If your job is not done yet make sure your Javascript function is al right. Else curse me for wasting your time. If your job is done you can leave a comment below.

Cheers

Next Page »