Thursday, July 8, 2010

What does !important mean in CSS?

This means that the styles are applied in order as they are read by the browser. The first style is applied and then the second and so on. What this means is that if a style appears at the top of a style sheet and then is changed lower down in the document, the second instance of that style will be the one applied, not the first.

For example, in the following style sheet, the div text will be black, even though the first style property applied is red:

div { color: red; }
div { color: black; }

The !important rule is a way to make your CSS cascade but also have the rules you feel are most crucial always be applied. A rule that has the !important property will always be applied no matter where that rule appears in the CSS document. So if you wanted to make sure that a property always applied, you would add the !important property to the tag. So, to make the div text always red, in the above example, you would write:

div { color: red !important; }
div { color: black; }

However, the !important rule was also put in place to help Web page users cope with style sheets that might make pages difficult for them to use or read. Typically, if a user defines a style sheet to view Web pages with, that style sheet will be over-ruled by the Web page author's style sheet. But if the user marks a style as !important, that style will overrule the Web page author's style sheet, even if the author marks their rule as !important.

This is a change from CSS1 to CSS2. In CSS1, author !important rules took precedence over user !important rules. CSS2 changed this to make the user's style sheet have precedence.

require() vs include() in PHP

require() and include() are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error. In other words, don’t hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well.

$_GET vs $_POST in PHP Forms

All information sent from a form with a GET method is visible to others and has a limit on the amount of information to send (100 max char). Whereas the $_POST variable, the information sent from the form with POST method is invisble to others and has no limits on the amount of information to send.

Differences between constants and variables

1. Constants do not have a dollar sign ($) before them;
2. Constants may only be defined using the define() function, not by simple assignment;
3. Constants may be defined and accessed anywhere without regard to variable scoping rules;
4. Constants may not be redefined or undefined once they have been set; and
5. Constants may only evaluate to scalar values.

Advantages of Using Functions

Functions are basically named scripts that can be called upon from any other script to perform a specifc task. Values (known as arguments) can be passed into a function so that they can be used in the function script, and functions can, in turn, return results to the location from which they were called.

What are the advantages of using functions?
Debugging is easier
It is easier to understand the logic involved in the program
Testing is easier
Recursive call is possible
Irrelevant details in the user point of view are hidden in functions
Functions are helpful in generalizing the program

PHP Arrays

PHP Arrays provide a way to group together many variables such that they can be referenced and manipulated using a single variable. An array is, in many ways, a self-contained list of variables.

Once an array has been created items can be added, removed and modified, sorted and much more. The items in an array can be of any variable type, and an array can contain any mixture of data types - it is not necessary to have each element in the array of the same type.

Elements of an array are accessed using a key. There are two types of array, and the type of key that is used to access an array element dictates the array type. In a numerical key array, elements are accessed by specifying the numerical position of the item in the array. The first item in an array is element 0, the second is element 1 and so on. The second type of array is the associative array where a name is given to each element, and that name is used to access the corresponding array element.

single-quote( ' ) vs double-quote ( " ) in PHP

Difference between single-quote( ' ) and double-quote ( " ) strings in php

Briefly:
In double-quoted strings, variables are replaced by their values:
PHP Code:
$word = "Hello".
echo "$word there!"

The above code will output:
Hello there!

Doing the same with single quotes:
PHP Code:
$word = "Hello".
echo '$word there!'

...will print:
$word there!

Using single quotes where possible, will be slightly more efficient to process, because PHP doesn't have to search single quoted strings for variables.

DETECTING MOBILE BROWSERS IN PHP

I used the following block of code to redirect site to a page when it is been accessed via mobile phone browser and to another page when it is accessed via desktop browsers. This is tested in ie, firefox, netscape, opera, chrome and some mobile phone browser simulator. This works well for me.


$BrowserSplit = explode("/",$HTTP_SERVER_VARS["HTTP_USER_AGENT"]);
$Machine = $BrowserSplit[0];


if($Machine == "Opera" || $Machine == "Mozilla") {
header("location: $site1");
}
else {
header("location: $site2");
}
?>


$HTTP_SERVER_VARS

Basic surfer information variables (from HTTP_SERVER_VARS)

[ip] = $HTTP_SERVER_VARS["REMOTE_ADDR"];

// $surfer_info[real_ip] will only contain something if the surfer used a transparent proxy

$surfer_info[real_ip] = $HTTP_SERVER_VARS["X_FORWARDED_FOR"];

$surfer_info[port] = $HTTP_SERVER_VARS["REMOTE_PORT"];

$surfer_info[browser_lang] = $HTTP_SERVER_VARS["HTTP_ACCEPT_LANGUAGE"];

$surfer_info[user_agent] = $HTTP_SERVER_VARS["HTTP_USER_AGENT"];

$surfer_info[request_path] = $HTTP_SERVER_VARS["PATH_INFO"];

$surfer_info[request_query] = $HTTP_SERVER_VARS["QUERY_STRING"];

$surfer_info[request_method] = $HTTP_SERVER_VARS["REQUEST_METHOD"];

$surfer_info[http_referrer] = $HTTP_SERVER_VARS["HTTP_REFERER"];

?>


It is just a row of variables, - it is up to you to decide how they are useful to your script and how to integrate them.
But if you want to see something happening any way, add

print_r($surfer_info);
to the bottom of the script (but before the closing ?>). Doing so will cause the script to show you what information the variables picked up

40 Tips for optimizing your php code

  1. If a method can be static, declare it static. Speed improvement is by a factor of 4.
  2. echo is faster than print.
  3. Use echo's multiple parameters instead of string concatenation.
  4. Set the maxvalue for your for-loops before and not in the loop.
  5. Unset your variables to free memory, especially large arrays.
  6. Avoid magic like __get, __set, __autoload
  7. require_once() is expensive
  8. Use full paths in includes and requires, less time spent on resolving the OS paths.
  9. If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
  10. See if you can use strncasecmp, strpbrk and stripos instead of regex
  11. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
  12. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
  13. It's better to use switch statements than multi if, else if, statements.
  14. Error suppression with @ is very slow.
  15. Turn on apache's mod_deflate
  16. Close your database connections when you're done with them
  17. $row[’id’] is 7 times faster than $row[id]
  18. Error messages are expensive
  19. Do not use functions inside of for loop, such as for ($x=0; $x <>
  20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
  21. Incrementing a global variable is 2 times slow than a local var.
  22. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
  23. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  24. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
  25. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
  26. Methods in derived classes run faster than ones defined in the base class.
  27. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
  28. Surrounding your string by ' instead of " will make things interpret a little faster since php looks for variables inside "..." but not inside '...'. Of course you can only do this when you don't need to have variables in the string.
  29. When echoing strings it's faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
  30. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
  31. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
  32. Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request
  33. When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.
    Ex.
    if (strlen($foo) < 5) { echo "Foo is too short"; }
    vs.
    if (!isset($foo{5})) { echo "Foo is too short"; }
    Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.
    more about isset() vs strlen() here
  34. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
  35. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
  36. Do not implement every data structure as a class, arrays are useful, too
  37. Don't split methods too much, think, which code you will really re-use
  38. You can always split the code of a method later, when needed
  39. Make use of the countless predefined functions
  40. If you have very time consuming functions in your code, consider writing them as C extensions
  41. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
  42. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%
  43. Excellent Article about optimizing php by John Lim

STRLEN vs ISSET in PHP

When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.

if (strlen($foo) < 5) { echo "Foo is too short"; }
if (!isset(
$foo{5})) { echo "Foo is too short"; }
?>

Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length.

JAVASCRIPT EQUIVALENT FOR PHP FUNCTIONS

Found this from Kevin van Zonneveld site and I just feel to post it here. List of PHP Functions are below:

abs

acosh

acos

addslashes

array

array_change_key_case

array_chunk

array_combine

array_count_values

array_diff

array_diff_assoc

array_diff_key

array_fill

array_fill_keys

array_filter

array_flip

array_keys

array_key_exists

array_map

array_merge

array_merge_recursive

array_pad

array_pop

array_product

array_push

array_rand

array_reduce

array_reverse

array_search

array_shift

array_slice

array_sum

array_unique

array_unshift

array_values

array_walk

array_walk_recursive

asinh

asin

atanh

atan

base64_decode

base64_encode

basename

base_convert

bin2hex

bindec

call_user_func_array

ceil

checkdate

chop

chr

chunk_split

compact

constant

cosh

cos

count

count_chars

crc32

create_function

date

decbin

dechex

decoct

defined

define

deg2rad

dirname

echo

empty

end

explode

exp

filesize

file

file_exists

file_get_contents

floatval

floor

fmod

function_exists

getdate

getrandmax

get_class

get_headers

get_html_translation_table

get_included_files

hexdec

htmlentities

htmlspecialchars

htmlspecialchars_decode

html_entity_decode

http_build_query

hypot

implode

include

include_once

intval

in_array

ip2long

isset

is_array

is_bool

is_finite

is_infinite

is_int

is_nan

is_null

is_numeric

is_object

is_string

join

krsort

ksort

lcg_value

levenshtein

log10

log

long2ip

ltrim

max

md5

md5_file

microtime

min

mktime

mt_getrandmax

mt_rand

nl2br

number_format

octdec

ord

parse_str

pi

pow

preg_quote

printf

print_r

quotemeta

rad2deg

rand

range

require

require_once

reset

round

rsort

rtrim

serialize

setcookie

sha1

sha1_file

shuffle

sinh

sin

sizeof

sleep

sort

soundex

split

sprintf

sqrt

strcasecmp

strchr

strcmp

stripos

stripslashes

strip_tags

stristr

strlen

strnatcmp

strncasecmp

strpbrk

strpos

strrev

strripos

strrpos

strstr

strtolower

strtoupper

str_ireplace

str_pad

str_repeat

str_replace

str_rot13

str_split

substr

substr_count

tanh

tan

time

trim

ucfirst

ucwords

unserialize

urldecode

urlencode

utf8_decode

utf8_encode

var_export

wordwrap