Archive for the ‘PHP Programming’ Category

php Syntax and data types

Saturday, November 15th, 2008

PHP only parses code within its delimiters. Anything outside its delimiters is sent directly to the output and is not parsed by PHP. The most common delimiters are <?php and ?>, which are open and close delimiters respectively. <script language=”php”> and </script> delimiters are also available. Short tags can be used to start PHP code, <? or <?= (which is used to echo back a string or variable) and the tag to end PHP code, ?>. These tags are commonly used, but like ASP-style tags (<% or <%= and %>), they are less portable as they can be disabled in the PHP configuration. For this reason, the use of short tags and ASP-style tags is discouraged.The purpose of these delimiters is to separate PHP code from non-PHP code, including HTML. Everything outside the delimiters is ignored by the parser and is passed through as output.

Variables are prefixed with a dollar symbol and a type does not need to be specified in advance. Unlike function and class names, variable names are case sensitive. Both double-quoted (”") and heredoc strings allow the ability to embed a variable’s value into the string.PHP treats newlines as whitespace in the manner of a free-form language (except when inside string quotes), and statements are terminated by a semicolon.PHP has three types of comment syntax: /* */ serves as block comments, and // as well as # are used for inline comments.The echo statement is one of several facilities PHP provides to output text (e.g. to a web browser).

In terms of keywords and language syntax, PHP is similar to most high level languages that follow the C style syntax. If conditions, for and while loops, and function returns are similar in syntax to languages such as C, C++, Java and Perl.

Data types

PHP stores whole numbers in a platform-dependent range. This range is typically that of 32-bit signed integers. Unsigned integers are converted to signed values in certain situations; this behavior is different from other programming languages. Integer variables can be assigned using decimal (positive and negative), octal, and hexadecimal notations. Real numbers are also stored in a platform-specific range. They can be specified using floating point notation, or two forms of scientific notation.PHP has a native Boolean type that is similar to the native Boolean types in Java and C++. Using the Boolean type conversion rules, non-zero values are interpreted as true and zero as false, as in Perl and C++. The null data type represents a variable that has no value. The only value in the null data type is NULL.Variables of the “resource” type represent references to resources from external sources. These are typically created by functions from a particular extension, and can only be processed by functions from the same extension; examples include file, image, and database resources.Arrays can contain elements of any type that PHP can handle, including resources, objects, and even other arrays. Order is preserved in lists of values and in hashes with both keys and values, and the two can be intermingled.PHP also supports strings, which can be used with single quotes, double quotes, or heredoc syntax.

Posted by

Objects oriented concepts in php

Saturday, November 15th, 2008

Basic object-oriented programming functionality was added in PHP 3.Object handling was completely rewritten for PHP 5, expanding the feature set and enhancing performance. In previous versions of PHP, objects were handled like primitive types.The drawback of this method was that the whole object was copied when a variable was assigned or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value. PHP 5 introduced private and protected member variables and methods, along with abstract classes and final classes as well as abstract methods and final methods. It also introduced a standard way of declaring constructors and destructors, similar to that of other object-oriented languages such as C++, and a standard exception handling model. Furthermore, PHP 5 added interfaces and allowed for multiple interfaces to be implemented. There are special interfaces that allow objects to interact with the runtime system. Objects implementing ArrayAccess can be used with array syntax and objects implementing Iterator or IteratorAggregate can be used with the foreach language construct. There is no virtual table feature in the engine, so static variables are bound with a name instead of a reference at compile time.

If the developer creates a copy of an object using the reserved word clone, the Zend engine will check if a __clone() method has been defined or not. If not, it will call a default __clone() which will copy the object’s properties. If a __clone() method is defined, then it will be responsible for setting the necessary properties in the created object. For convenience, the engine will supply a function that imports the properties of the source object, so that the programmer can start with a by-value replica of the source object and only override properties that need to be changed.

Posted by

Why PHP?

Saturday, November 15th, 2008

You may be wondering why you should choose PHP over other languages such as Perl or even why you should learn a scripting language at all. I will deal with learning scripting languages first. Learning a scripting language, or even understanding one, can open up huge new possibilities for your website. Although you can download pre-made scripts from sites like Hotscripts, these will often contain advertising for the author or will not do exactly what you want. With an understanding of a scripting language you can easily edit these scripts to do what you want, or even create your own scripts.

Using scripts on your website allows you to add many new ‘interactive’ features like feedback forms, guestbooks, message boards, counters and even more advanced features like portal systems, content management, advertising managers etc. With these sort of things on your website you will find that it gives a more professional image. As well as this, anyone wanting to work in the site development industry will find that it is much easier to get a job if they know a scripting language.

Posted by

What Is PHP?

Saturday, November 15th, 2008

Up until recently, scripting on the internet was something which very few people even attempted, let alone mastered. Recently though, more and more people have been building their own websites and scripting languages have become more important. Because of this, scripting languages are becomming easier to learn and PHP is one of the easiest and most powerful yet.

PHP stands for Hypertext Preprocessor and is a server-side language. This means that the script is run on your web server, not on the user’s browser, so you do not need to worry about compatibility issues. PHP is relatively new (compared to languages such as Perl (CGI) and Java) but is quickly becomming one of the most popular scripting languages on the internet.

Posted by

What’s the difference between JavaScript and Java?

Friday, September 26th, 2008

Actually, the 2 languages have almost nothing in common except for the name. Although Java is technically an interpreted programming language, it is coded in a similar fashion to C++, with separate header and class files, compiled together prior to execution. It is powerful enough to write major applications and insert them in a web page as a special object called an “applet.” Java has been generating a lot of excitment because of its unique ability to run the same program on IBM, Mac, and Unix computers. Java is not considered an easy-to-use language for non-programmers.

Javascript is much simpler to use than Java. With Javascript, if I want check a form for errors, I just type an if-then statement at the top of my page. No compiling, no applets, just a simple sequence.

Posted by Mohamed Asif

What is SEO?

Thursday, July 24th, 2008

SEO stands for Search Engine Optimization and is defined as (in my own words):

“The process of finding out the best keywords for a web site and by the use of optimizing the web site along with other off-page work making that web site attain a higher position in the search engine result pages (SERPs) for those selected words.”

Although the exact calculations used by the search engines are kept secret, there is lot of knowledge and observations in this field from thousands of webmasters worldwide.

It could be said to be a branch of online marketing. In general terms you can say that it means to make a web site more visible and make it look important in the eyes of search engines.

Not being familiar with SEO and not applying it compared to actually doing the right things can make a huge difference in terms of visitors to your web site.

Posted by

What is relative vs absolute links?

Thursday, July 24th, 2008

When designing a site, you will always face the question of whether you should use relative or absolute links. Later in this answer I will explain the benefits of each but first here is a definition:

Relative: Relative links usually look something like index.html or /folder/page.html. The way the page knows where to go is all relative to the page the link is placed on. A link to index.html for example, will only work if the file is found in the current folder.

Absolute: Absolute links usually look something like http://www.example.com/page.html. This is a full url and the linked to page will be found regardless of where that link is located on the site.

Which you use depends on the following:

Speed: When your browser goes to find a page with a relative url it looks within the existing site. When it uses an absolute url it leaves the site for an instant and “refinds” the page. This means when it comes to speed, relative is the way to go.

Ease of Design: When you are designing a site using notepad, the danger with relative urls is that if you move a folder, it can break your entire site. As each page depends on another, if you are not a find and replace whiz, absolute may be your best bet.

SEO: This is the one area that I would place firmly in “Theory or Assumption”. The truth is that we know broken links can hurt you so the most important is to choose a technique of linking that works best for your site. One of the better case for Absolute Links can be seen here

Posted by

Tips for optimizing your php code

Friday, July 18th, 2008

# If a method can be static, declare it static. Speed improvement is by a factor of 4.

# echo is faster than print.

# Use echo’s multiple parameters instead of string concatenation.

# Set the maxvalue for your for-loops before and not in the loop.

# Unset your variables to free memory, especially large arrays.

# Avoid magic like __get, __set, __autoload

# require_once() is expensive

# Use full paths in includes and requires, less time spent on resolving the OS paths.

# If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()

# See if you can use strncasecmp, strpbrk and stripos instead of regex

# str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4

# 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.

# It’s better to use switch statements than multi if, else if, statements.

# Error suppression with @ is very slow.

# Turn on apache’s mod_deflate

# Close your database connections when you’re done with them

# $row[’id’] is 7 times faster than $row[id]

# Error messages are expensive

# Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.

# Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.

# Incrementing a global variable is 2 times slow than a local var.

# Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.

# Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

# 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.

# 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.

# Methods in derived classes run faster than ones defined in the base class.

# 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.

# 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.

# 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.

# 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.

# 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.

# 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

# 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.

# 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.

# Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.

# Do not implement every data structure as a class, arrays are useful, too

# Don’t split methods too much, think, which code you will really re-use

# You can always split the code of a method later, when needed

# Make use of the countless predefined functions

# If you have very time consuming functions in your code, consider writing them as C extensions

# 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

# 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%

Posted by

What is meant by PEAR in php?

Saturday, May 10th, 2008

Answer1:
PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install “packages”

Answer2:
PEAR is short for “PHP Extension and Application Repository” and is pronounced just like the fruit. The purpose of PEAR is to provide:
A structured library of open-sourced code for PHP users
A system for code distribution and package maintenance
A standard style for code written in PHP
The PHP Foundation Classes (PFC),
The PHP Extension Community Library (PECL),
A web site, mailing lists and download mirrors to support the PHP/PEAR community
PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.

Posted by

subquery - join using in mysql

Wednesday, April 23rd, 2008

SELECT sports_name
FROM sports
WHERE id
IN (

SELECT sports_id
FROM sports_key
WHERE user_id =1
)

In this query we have selected field(sports_id) from the table(sports_key) and also we checed the field(user_id) This process has been done in subquery. Then finally, we have selected field (sports_name) from the table (sports_key) according to receiving field (id) values from subquery.

Posted by