Monthly Archives: August 2012

Hide page content while printing a page

Sometimes, we need to disable editing option of browser like select content, copy and paste or right click disable for preventing our data. Sometimes we ignore one option and it is print option. We also need to take care about print option disabled or hide content while printing page. There is a simple solution about hide content while printing. Yes, I am talking about print @media css type.

Add below content in <head> section.

<style media=”print” type=”text/css”>
body {display:none;visibility:hidden;}
</style>

Disabled selection

<script>
document.onselectstart = new Function(‘return false’);
function dataSelect(evt){return false;}
document.onmousedown = dataSelect;
</script>

How to prevent the web pages from being index by the Search Engine

If you don’t want that search robot does not crawl your web page, your web directory or your entire site. There are several ways to hide web page from search robot.

Since all search engines follow a web robots standard while crawling websites called Robots Exclusion Protocol, Make robots.txt file and put in root and write instruction about what to index and what not to index.

Example about block your entire website:

User-agent: *
Disallow: /

Example about block directories or individual pages on your site:

Disallow: /cgi-bin/
Disallow: /tmp/

Or, You can also block access to your website using META tags.

<meta name=”robots” content=”noindex”>

Put abount META tag in <head> section of your web page.

Get more details about robots.txt and <meta> tag.

How to Use Custom Fonts in Your Web Designs with CSS?

In today’s era web designs become more n more powerful. Web designer uses different font in order to give best look n feel as per requirement and it is far easy from CSS. The history behind write this article is our one of client demands that I want same font on entire site which is used in my logo so here external font comes in picture. It is very easy to load external font in your web interface via CSS @font-face.

Just follow below steps to get external font in your site.

  • Collect external font.
  • Recommended .eot font for IE browsers, .woff (web open font format) for some firefox(3,6) and chrome(6) browsers versions, .ttf for css3 support browser, .svg for iPhone and iPad.
  • Add below code top of the css. Recommended use separate css for font configuration.

    @font-face {
    font-family: ‘font-nick-name’;
    src: url(‘font.eot’);
    src: url(‘font.eot?#iefix’) format(’embedded-opentype’),
    url(‘font.woff’) format(‘woff’),
    url(‘font.ttf’) format(‘truetype’),
    url(‘font.svg#OpenSansLight’) format(‘svg’);
    font-weight: normal;
    font-style: normal;
    }

  • font-family: ‘font-nick-name’ – you can take any name you want. You need to use given name in css for example: font-family:’font-nick-name’;
  • .eot : IE Browsers.
  • .woff (web open font family): For Firefox3.5+, Chrome6, Opera.
  • .ttf: css3 supports browser.
  • .svg: iPhone, iPad.
  • External font configuration over here.
  • Now you can use configured font in your main css. Like font-family: ‘font-nick-name’;

Hope you enjoy this article. Happy Coding.

How to add a day in JavaScript date?

Whenever date operation comes in picture then it always create issue. Today I need to add one day in given date so hopefully start googling to find date add function to increment a day in loop. But there are no JavaScript function exits for that. After some googling get one line code to add a day in given date. I just copy n paste it. See below line of code to add a day in give date.

dateObj.getTime() + (1 * 24 * 60 * 60 * 1000);

Here 1 stands for day, 24 hours, 60 minutes, 60 seconds and 1000 milliseconds.

Here my search is over and I have completed my works but after taking lunch I just think date adds function should be in our js library for future reference.

Now, start building JavaScript Date prototype functions for easy to use. See below function.

Date.prototype.dateAdd = function(days){
    return dateObj = new Date(this.getTime() + (days * 24 * 60 * 60 * 1000));
}

How to use JavaScript Date prototype function?

The prototype function should be load before your login is going to run. You can use prototype function as like other default JavaScript date function like getDate(), getTime(), getDay()…..

For example,

var nextDate = new Date(’08/21/2012′).dateAdd(2);

Here nextDate has ‘Thu Aug 23 2012 00:00:00 GMT+0530 (India Standard Time)’.

Hope you enjoy a lot. Happy coding.

PHP Interview Question – 2

There are some more PHP Interview Questions.

What does a special set of tags <?= and ?> do in PHP?

The output is displayed directly to the browser.

What’s the difference between include and require?

It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.
I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem? – PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.

Would I use print “$a dollars” or “{$a} dollars” to print out the amount of dollars in this example?

In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like “{$a},000,000 mln dollars”, then you definitely need to use the braces.

How do you define a constant?

Via define() directive, like define (“MYCONSTANT”, 100);

How do you pass a variable by value?

Just like in C++, put an ampersand in front of it, like $a = &$b

Will comparison of string “10” and integer 11 work in PHP?

Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.

When are you supposed to use endif to end the conditional statement?

When the original if was followed by : and then the code block without braces.

Explain the ternary conditional operator in PHP?

Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.

How do I find out the number of parameters passed into function? – func_num_args() function returns the number of parameters passed in.

If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b? – 100, it’s a reference to existing variable.

What’s the difference between accessing a class method via -> and via ::?

:: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization.

Are objects passed by value or by reference?

Everything is passed by value.

How do you call a constructor for a parent class?

parent::constructor($value)

What’s the special meaning of __sleep and __wakeup?

__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.

Why doesn’t the following code print the newline properly?
<?php
$str = ‘Hello, there.nHow are you?nThanks for visiting TechInterviews’;
print $str;
?>

Because inside the single quotes the n character is not interpreted as newline, just as a sequence of two characters – and n.
Would you initialize your strings with single quotes or double quotes?
Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution.

How come the code <?php print “Contents: $arr[1]”; ?> works, but <?php print “Contents: $arr[1][2]”; ?> doesn’t for two-dimensional array of mine?

Any time you have an array with more than one dimension, complex parsing syntax is required. print “Contents: {$arr[1][2]}” would’ve worked.

What is the difference between characters 23 and x23?

The first one is octal 23, the second is hex 23.

With a heredoc syntax, do I get variable substitution inside the heredoc contents?

Yes.

I want to combine two variables together:
$var1 = ‘Welcome to ‘;
$var2 = ‘TechInterviews.com’;

What will work faster?

Code sample 1: $var 3 = $var1.$var2;
Or code sample 2: $var3 = “$var1$var2”;

Both examples would provide the same result – $var3 equal to “Welcome to TechInterviews.com”. However, Code Sample 1 will work significantly faster. Try it out with large sets of data (or via concatenating small sets a million times or so), and you will see that concatenation works significantly faster than variable substitution.

For printing out strings, there are echo, print and printf. Explain the differences. – echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like:
<?php echo ‘Welcome ‘, ‘to’, ‘ ‘, ‘TechInterviews!’; ?>
and it will output the string “Welcome to TechInterviews!” print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf.

I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP?

On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split().

What’s the output of the ucwords function in this example?
$formatted = ucwords(“TECHINTERVIEWS IS COLLECTION OF INTERVIEW QUESTIONS”);
print $formatted;
What will be printed is TECHINTERVIEWS IS COLLECTION OF INTERVIEW QUESTIONS.

ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it’s worth using strtolower() first.

What’s the difference between htmlentities() and htmlspecialchars()?

htmlspecialchars only takes care of <, >, single quote ‘, double quote ” and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.

What’s the difference between md5(), crc32() and sha1() crypto on PHP?

The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.
So if md5() generates the most secure hash, why would you ever use the less secure crc32() and sha1()? – Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, depending on the data that you’re encrypting, you might have reasons to store a 32-bit value in the database instead of the 160-bit value to save on space. Second, the more secure the crypto is, the longer is the computation time to deliver the hash value. A high volume site might be significantly slowed down, if frequent md5() generation is required.

jQuery datepicker disabled weekday

jQuery Disabled Weekday

jQuery Disabled Weekday

There is another custom setting for jQuery datapicker. Here we have discuss about how to disabled any weekday in jQuery datepicker. As you know in today’s era jQuery become more and more populare and why not? It should be because jQuery does our work very easy. Recently, in our one of the project need to give date field value in one of the form. In this form date calculate dynemic with exclude weekend days (saturday and sunday) as per client timeline setting but client also wants their employee also change date value manually. Now what, we need to give datepicker to the text field and as we love jQuery so of course we use jQuery datepicker and see there is no default function to handle disabled weekday. We know there is a function to handle custom setting before show datapicker and before show day. i.e. there are two different function beforeShow, beforeShowDay. beforeShow function uses when you want to set before showing datepicker and beforeShowDay function uses when you want to apply setting before load each day. So we use beforeShowDay function to disabled day. It’s very simple and short code for disabling weekday. Let’s understand by example.

[code language=”javascript”]
jQuery(‘#fromdate’).datepicker({

beforeShowDay : function(date){

if(date.getDay()== 0 || date.getDay()== 6)

return [0];

else

return [1];

}

});
[/code]

beforeShowDay function returns date value so we just get DAY from date and give condition for that if sunday or saturday then return 0 or 1 but keep in  mind it allows return format in array.

PHP Interview Question

Here is the series of PHP interview question which helps to student, fresher as well as experience person.

1. What is the full form of PHP?

PHP stands for Hypertext Preprocessor.

2. Can I say PHP is fully object oriented language?

No. PHP is server side scripting language.

3. Who is the founder of PHP and when?

PHP was created by Rasmus Lerdorf in 1995.

4. Discribe comments in PHP.

// for single line.

/* …. */ for multiline block.

5. Can I start PHP variable name with Number?

No. You can’t. It must start with alphabet or underscore(_) only.

6. Is $name and $Name have same value?

No. Both variables having different value as PHP is case sensitive language.

7. How many variables scope in PHP?

There are four types of variable scope in PHP.
1. local
2. global
3. static
4. parameter

8. Which special character is used for concatenating different string?

The dot(.) character is used for concatenating different string.

9. How to print variables value?

There are 3 ways to print variables value.
1. echo
2. print
3. printf

10. What is different between echo and print?

Click on below link to get in details.
http://www.sourcecodemart.com/difference-between-echo-and-print/

11. Is $name and $$name having same value?

No. Both having different value. For example
<?php
$name = ‘Sourcecode’;
$$name = ‘Mart’;
?>

Here $name has ‘Sourcecode’ and $$name has ‘Mart’. i.e. $Sourcecode has ‘Mart’;

mysql_num_rows() VS mysql_affected_rows()

Today I need to display record set like how many rows fetched or affected by query. There are two different function in PHP to get fetched or affected rows information and it is mysql_num_rows() and mysql_affected_rows().

What is the different between mysql_num_rows() and mysql_affected_rows()?

The mysql_num_rows() function is used with select statements whereas mysql_affected_rows() function is used with insert, update and delete statements.

An example of mysql_num_rows()

[code language=”php”]<?php
$result = mysql_query(‘SELECT field FROM tablename’);
$rows = mysql_num_rows($result);
// returns int :: getting number of rows from select statements
?>[/code]

An example of mysql_affected_rows()

[code language=”php”]<?php
$result = mysql_query("INSERT INTO tablename VALUES (‘$value’)");
$rows = mysql_affected_rows();
// returns 1
?>[/code]
Happy Coding…

WordPress Media Settings

In today’s era WordPress become more and more popular script for expressing your thought and small content management system. There are so many custom setting functionality available in WordPress admin.

Actually, I want to post some YouTube video on blog so for that I just copy n paste YouTube url in my blog post. WordPress is automatically converted into iFrame. From here there is no any issue with me but when I run my blog post in browser it was spoiled my blog look due to its default height and width.

I have decided to find code for converting link to iFrame or something else and change it to custom height and width then after I look into admin setting with hope that there will be setting for setting embedded video settings and yes I got it.

In order to set height and width of embedded video setting follow below steps.

  • Go To Settings > Media.
  • Media Settings

    Media Settings

  • Check “Auto-embeds” to Yes.
  • Set Maximum Embed Size.
  • Media Settings for embeds and image size

    Media Settings for embeds and image size

  • That’s it….

There is no need to install plug-in for setting YouTube video height or width.

My search is over here.

PHP MD5() Function

MD5() is a most useful function in PHP.

MD5() means Message-Digest Algorithm. MD5() is used to encrypt string value. MD5() function returns hash value on success and False on failure.

We can say MD5() is one way encryption function. I.e. you cannot decrypt string value. You have to always compare with MD5() hash value and new generated MD5() string of value.

Syntax:

md5(string, raw);

String :

Required parameter. Calculated based on raw parameter.

Raw :

Optional. Specifies binary and hex output format: True – 16 Characters binary format and False(Default). 32 character hex number.
Note: Raw parameter was introduce in PHP 5.0

Example 1:

[code language=”php”]<?php
$str = ‘sourcecodemart’;
echo md5($str);
?>[/code]

Output of above code is:

ce01a33c357ce7a3feae55ab25c13add

Example 2:

In this example we will print MD5() value and test it.

[code language=”php”]<?php
$str = ‘sourcecodemart’;
echo md5($str);
if(md5($str) == ‘ce01a33c357ce7a3feae55ab25c13add’){
echo ‘<br />’ . ‘Welcome to tech world’;
}else{
echo ‘Not Match’;
}
?>[/code]

Output of above code is:

ce01a33c357ce7a3feae55ab25c13add
Welcome to tech world

People are generally using MD5() for encrypt password value.

What happens if you forget your passord as MD5() is not support decrypt value. At that time you have to give new password with the encryption of MD5().