PHP, HTML, CSS, Javascript,GIT







what is PHP 5.3

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.



explode function in php


explode — Split a string by string
syntax: array explode ( string $delimiter , string $string [, int $limit ] )
example:
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2


in_array() in php

in_array — Checks if a value exists in an array
syntax:

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

example:

$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}


is_array function in php


is_array — Finds whether a variable is an array
syntax:bool is_array ( mixed $var )
example:
$yes = array('this', 'is', 'an array');

echo is_array($yes) ? 'Array' : 'not an Array';



implode function in php


implode — Join array elements with a string
syntax: string implode ( string $glue , array $pieces )
example:
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone



split function in php


split — Split string into array by regular expression
syntax: array split ( string $pattern , string $string [, int $limit = -1 ] )
example:
$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year
\n";


Difference Between PHP 4 and PHP 5


1) Passed by Reference
This is an important change. In PHP4, everything was passed by value, including objects. This has changed in PHP5 -- all objects are now passed by reference.

ex: $joe = new Person();
$joe->sex = 'male';

$betty = $joe;
$betty->sex = 'female';

echo $joe->sex; // Will be 'female'

2) Class Constants and Static Methods/Properties
You can now create class constants that act much the same was as define()'ed constants, but are contained within a class definition and accessed with the :: operator.

Static methods and properties are also available. When you declare a class member as static, then it makes that member accessible (through the :: operator) without an instance. (Note this means within methods, the $this variable is not available)

3) Unified Constructors and Destructors


Difference b/w strstr() and stristr()


strstr() returns part of a given string from the first occurrence of a given substring to the end of the string. For example: strstr(“user@example.com”,”@”) will return “@example.com”.
stristr() is idential to strstr() except that it is case insensitive.


Difference b/w ereg_replace() and eregi_replace()


ereg_replace is case sensitive
ereg_replace is case insensitive
example:
$s = "Coding PHP is fun.";
print "ereg_replace(): " .
ereg_replace("CODING", "Learning", $s) . "
";
print "eregi_replace(): " .
eregi_replace("CODING", "Learning", $s);


Find No.of arguments in a function in PHP


using func_num_args();

function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs\n";
}

foo(1, 2, 3);
answer is:Number of arguments : 3


What is Difference between Session and Cookie

The main difference between cookies and sessions is that cookies are stored in the user's browser, and sessions are not. A cookie can keep information in the user's browser until deleted. Sessions work instead like a token allowing access and passing information while the user has their browser open. The problem with sessions is that when you close your browser you also lose the session.


Cookies

There are two different types of cookies:

Session cookies - these are temporary and are erased when you close your browser at the end of your surfing session. The next time you visit that particular site it will not recognise you and will treat you as a completely new visitor as there is nothing in your browser to let the site know that you have visited before

Persistent cookies - these remain on your hard drive until you erase them or they expire. How long a cookie remains on your browser depends on how long the visited website has programmed the cookie to last


Unset function in php

unset — Unset a given variable

If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

Example: function destroy_foo()
{
global $foo;
unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;

answer: bar


To unset() a global variable inside of a function, then use the $GLOBALS array to do so:

function foo()
{
unset($GLOBALS['bar']);
}

$bar = "something";
foo();


What is difference between $var and $$var


$var is a variable
$$var is Variable to Variable.

Means see the below example

Example:
Suppose $var "Hello";
$hello "World";

echo $var; will print Hello, echo $$var; will print World.



What is difference between require_once(), require(), include(),include_once()


include()
————
It includes a spcified file.
It will produce a a warning if it fail to find the file and execute the remaining scripts

require
———–
It includes a spcified file.
It will produce a a fatal error if it fail to find the file and stops the ececution

include_once()
——————-
It includes a spcified file.
a file has already been included, it will not be included again.
It will produce a a warning if it fail to find yhe file and execute the remaining scripts.

require_once()
———–
It includes a spcified file.
a file has already been included, it will not be included again.
It will produce a a fatal error if it fail to find the file and stops the ececution



ucwords function in php


ucwords — Uppercase the first character of each word in a string

Example:

$foo = 'hello world!';
$foo = ucwords($foo); // output:Hello World!



chunck_split function in php


The chunk_split() function splits a string into a series of smaller parts.

Example:

$str = "Hello world!";
echo chunk_split($str,1,".");

//output:H.e.l.l.o. .w.o.r.l.d.!.




How to find out the difference between two dates in php ?


$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2); //this date->diff() is applicable for PHP 5.3.0 and above version
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

//output: difference 2 years, 3 months, 2 days



Ternary Operator in php ?


Another conditional operator is the "?:" (or ternary) operator.

Example:// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}


What is markup language

Markup languages are designed for the processing, definition and presentation of text. The language specifies code for formatting, both the layout and style, within a text file. The code used to specify the formatting are called tags. HTML is a an example of a widely known and used markup language.


What is CSS 2.1

CSS is an abbreviation for Cascading Style Sheets. Style sheets are simply text files (.css ), composed of lines of code that tell browsers how to display an HTML page. They give the designer more control over the appearance of a webpage by allowing to specifically define styles for elements, such as fonts, on the page. By using CSS one could separate HTML content from its appearance, distinguishing style from structure.

There are three types of CSS styles:

* inline styles
Inline styles are styles that are written directly in the tag on the document. Inline styles affect only the tag they are applied to.


* embedded styles
Embedded styles are styles that are embedded in the head of the document. Embedded styles affect only the tags on the page they are embedded in.


* external styles
External styles are styles that are written in a separate document and then attached to various Web documents. External style sheets can affect any document they are attached to.



What is JavaScript 1.8.1?

JavaScript is scripting language used for client side scripting. JavaScript developed by Netscape in 1995 as a method for validating forms and providing interactive content to web site. Microsoft and Netscape introduced JavaScript support in their browsers.

Benefits of JavaScript
Following are the benefits of JavaScript.

* associative arrays
* loosely typed variables
* regular expressions
* objects and classes
* highly evolved date, math, and string libraries
* W3C DOM support in the JavaScript

Disadvantages of JavaScript

* Developer depends on the browser support for the JavaScript
* There is no way to hide the JavaScript code in case of commercial application


What is Dreamweaver CS3?

Dreamweaver CS3 is a powerful Hypertext Markup Language (HTML) editor used by
professionals, as well as beginners. The program makes it easy for designers to create visually
attractive, interactive Web pages without having to know HTML or JavaScript. However,
Dreamweaver CS3 enables the experienced professional to write and edit HTML using the code
editor. Dreamweaver also gives the opportunity to create web pages and learn HTML coding as
you go along, by giving you the option of a split screen with code and design.


What is AJAX?

AJAX is about updating parts of a web page, without reloading the whole page.
AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

How AJAX Works


How to enable mod_rewrite in apache2 (debian/ubuntu)

First install the apache with this command:

apt-get install apache2

Now use locate to find if the mod_rewrite.so is availble on your server:

updatedb
locate mod_rewrite.so

it will found in “/usr/lib/apache2/modules”

New apache follow some folders to enable and disable mods so now do this:

cd /etc/apache2/mods-enabled
touch rewrite.load
vim rewrite.load (you may use any editor to edit this file)

Now paste this following line:

LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so

Then edit:
/etc/apache2/sites-available/default

Find the following:

Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all

and change it to

Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all

and finally restart Apache:

/etc/init.d/apache2 restart


OOPS Concepts in PHP


1) Access control modifiers:

Public: used from anywhere in the script
Private:only be used by the object it is part of; it cannot be accessed elsewhere
Protected:used by the object it is part of, or descendants of that class
Final:This variable or function cannot be overridden in inherited classes
Abstract:This function or class cannot be used directly - you must inherit from them first

2) interfaces:

interfaces :

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

EXampleL:


// Declare the interface 'iTemplate'

interface iTemplate

{

public function setVariable($name, $var);

public function getHtml($template);

}

// Implement the interface

// This will work

class Template implements iTemplate

{

private $vars = array();

public function setVariable($name, $var)

{

$this->vars[$name] = $var;

}

public function getHtml($template)

{

foreach($this->vars as $name => $value) {

$template = str_replace('{' . $name . '}', $value, $template);

}



return $template;

}

}

// This will not work

// Fatal error: Class BadTemplate contains 1 abstract methods

// and must therefore be declared abstract (iTemplate::getHtml)

class BadTemplate implements iTemplate

{

private $vars = array();

public function setVariable($name, $var)

{

$this->vars[$name] = $var;

}

}

?>

3) Encapsulation:

ENCAPSULATION IN PHP CALSSES



example :

class Hide {

private $myname;

function getmyname()

{

$myname = "damodharan";

return $myname;

}

}

class damu {

private static $name;

public function name()

{

if( $this->name == null ) {

$this->name = new Hide();

}

return $this->name;

}

}

$run = new damu();

echo $run->name()->getmyname();

4) Polymorphism:

example code for


class Base

{

function mytext()

{

echo "hi am damu from base class ";

}

}



class myFirstClas extends Base

{

function mytext()

{

echo "hi am damu from myFirstClas class ";

}

}

class mySecondClas extends Base

{

function mytext()

{

echo "hi am damu from mySecondClas class ";

}

}

//create the object for the calss using poly marpisam



$objects = array ( $baseIns = new Base(),$myFirstClasIns = new myFirstClas(),$mySecondClasIns = new mySecondClas()

);



foreach ($objects as $object) {

echo $object->mytext();

echo "
\n";

}


differnce between $HTTP_GET_VARS and $HTTP_POST_VARS


$HTTP_GET_VARS (this is deprecated) - $_GET (both are same)
$HTTP_POST_VARS (this is deprecated) - $_POST (both are same)


md5() and crypt()


md5() -Calculate the md5 hash of a string using MD5 Message-Digest Algorithm, and returns that hash.


crypt() - One-way string hashing


session_unregister(),session_unset(),session_start(),session_register()


session_unregister()
-- Unregister a global variable from the current session

syntax: bool session_unregister ( string $name )

session_unset()
-- Free all session variables

syntax: void session_unset ( void )

session_start()
-- Initialize session data

syntax: bool session_start ( void )

session_register()
-- Register one or more global variables with the current session

syntax:bool session_register ( mixed $name [, mixed $... ] )

eg: $barney = "A big purple dinosaur.";

session_register("barney");

session_destroy()
-- Destroys all data registered to a session

syntax: bool session_destroy ( void )


error_reporting()


error_reporting()- Sets which PHP errors are reported syntax:int error_reporting ([ int $level ] )

1) error_reporting(0); - Turn off all error reporting
2) error_reporting(E_ERROR | E_WARNING | E_PARSE) - Report simple running errors
3) error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE)- Reporting E_NOTICE can be good too (to report uninitialized
4) error_reporting(E_ALL ^ E_NOTICE) - Report all errors except E_NOTICE
5) error_reporting(E_ALL) - Report all PHP errors (see changelog)


ini_set(),ereg()


ini_set()
-- Sets the value of a configuration option

syntax: string ini_set ( string $varname , string $newvalue )

ereg()
-- Regular expression match

syntax:int ereg ( string $pattern , string $string [, array &$regs ] )


E_WARNING,E_ERROR ,E_PARSE,E_NOTICE


E_WARNING - Run-time warnings (non-fatal errors). Execution of the script is not halted.
E_ERROR - Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.
E_PARSE - Compile-time parse errors. Parse errors should only be generated by the parser.
E_NOTICE - Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.


Difference b/w Website and Webapplication

A web site is like a foundation and can host several web applications.

A web application serves a specific function such a shopping cart or a blogging application.

So a web site can have a message board, a blog, a photo gallery and many other types of web applications under it's cloud.

WEB APPLICATION

An application that is delivered using Internet technology and meets one or more of the following conditions:

1) Utilizes a database
2) Is developed using an application development tool

Extracts data from multi-record files

Requires a constantly running server process (such as Newsgroups and Chatrooms)

Stores input data from data entry screens or web forms

Depending on its requirements, a web application may be an Internet Application or an Intranet Application.

WEBSITE

The entire collection of web pages and other information (such as images, sound, and video files, etc.) that are made available through what appears to users as a single web server


Magic Methods in PHP


1) __call() is triggered when invoking inaccessible methods in an object context.

2) __callStatic() is triggered when invoking inaccessible methods in a static context.

example:


class MethodTest {
public function __call($name, $arguments) {
// Note: value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(', ', $arguments). "\n";
}

/** As of PHP 5.3.0 */
public static function __callStatic($name, $arguments) {
// Note: value of $name is case sensitive.
echo "Calling static method '$name' "
. implode(', ', $arguments). "\n";
}
}

$obj = new MethodTest;
$obj->runTest('in object context');

MethodTest::runTest('in static context'); // As of PHP 5.3.0

3) Constructor and Destructor(_construct and _destruct)

Every class has two special functions, constructor and destructor. Even if you do not explicitly declare and define them, they exist (they are empty).

Constructor is a function which is called right after you create a new object. This makes constructor suitable for any object initialization you need.

Destructor is a function which is called right after you release an object. Releasing object means that you do not need it or use it anymore. This makes destructor suitable for any final actions you want to perform.

4) __set() is run when writing data to inaccessible properties.

5) __get() is utilized for reading data from inaccessible properties.

6) __isset() is triggered by calling isset() or empty() on inaccessible properties.

7) __unset() is invoked when unset() is used on inaccessible properties.

8) __sleep() and __wakeup()

The intended use of __sleep() is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.

Conversely, unserialize() checks for the presence of a function with the magic name __wakeup(). If present, this function can reconstruct any resources that the object may have.

The intended use of __wakeup() is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
9) __toStirng():

The __toString() method allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.

10) __invoke()

The __invoke() method is called when a script tries to call an object as a function.


Change the Session Timeout Value

Change the Session Timeout Value

ini_set(’session.gc_maxlifetime’, 30*60);

session expires min time: 1 minute
session expires max time: 1440 minute


__autoload()


__autoload - automatically including the definition file when a class is called.

example:

function __autoload($class_name)
{
include('classes/' . $class_name . '.class.php');
}

$time = new time();

$time->fn1();


Types of Browser Cookies

Browser cookies are used to store small pieces of information on a client machine. A cookie can store only up to 4 KB of information. Generally cookies are used to store data which user types frequently such as user id and password to login to a site.

There are two types of browser cookies - session and persistent. Session cookies, also called as temporary cookies are stored in a browsers memory and stay alive as long as a browser session is live. When you close a browser, these cookies die.

Any amount of data can be stored there because the session is kept on the server side.

The only limitation is sessionId length, which shouldn't exceed ~4000 bytes -


create a class in javascript


var Animal = Class.create({
initialize: function(name, sound) {
this.name = name;
this.sound = sound;
},

speak: function() {
alert(this.name + " says: " + this.sound + "!");
}
});

// subclassing Animal
var Snake = Class.create(Animal, {
initialize: function($super, name) {
$super(name, 'hissssssssss');
}
});

var ringneck = new Snake("Ringneck");
ringneck.speak();
//-> alerts "Ringneck says: hissssssssss!"


Static Keyword


Declaring class properties or methods as static makes them accessible without needing an instantiation of the class

1) static property:
class Foo
{
public static $my_static = 'foo';

public function staticValue() {
return self::$my_static;
}
}

class Bar extends Foo
{
public function fooStatic() {
return parent::$my_static;
}
}


print Foo::$my_static . "\n";

$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n"; // Undefined "Property" my_static

print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // As of PHP 5.3.0

print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";


2) static method:

class Foo {
public static function aStaticMethod() {
// ...
}
}

Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0


Difference b/w Interface and Abstract Class


Simple abstract class looks like this:

public abstract class KarateFight{

public void bowOpponent(){

//implementation for bowing which is common for every participant }

public void takeStand(){

//implementation which is common for every participant

}

public abstract boolean fight(Opponent op);

//this is abstract because it differs from person to person

}

The basic interface looks like this:

public interface KarateFight{

public boolean fight(Opponent op);

public Integer timeOfFight(String person);

}

The differences between abstract class an interface as fallows:

1. Abstract class has the constructor, but interface doesn’t.

2. Abstract classes can have implementations for some of its members (Methods), but the interface can’t have implementation for any of its members.

3. Abstract classes should have subclasses else that will be useless..

4. Interfaces must have implementations by other classes else that will be useless

5. Only an interface can extend another interface, but any class can extend an abstract class..

6. All variable in interfaces are final by default

7. Interfaces provide a form of multiple inheritance. A class can extend only one other class.

8. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.

9. A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.

10. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.

11. Accessibility modifier(Public/Private/internal) is allowed for abstract class. Interface doesn’t allow accessibility modifier

12. An abstract class may contain complete or incomplete methods. Interfaces can contain only the signature of a method but no body. Thus an abstract class can implement methods but an interface can not implement methods.

13. An abstract class can contain fields, constructors, or destructors and implement properties. An interface can not contain fields, constructors, or destructors and it has only the property’s signature but no implementation.

14. Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but not in interfaces.

15. Abstract scope is upto derived class.

16. Interface scope is upto any level of its inheritance chain.


Inheritance in PHP


Similar to Java, PHP supports single inheritance. There is no multiple inheritance in php. Single inheritance means a class can extend only one parent class.

PHP also has interfaces which can be implemented if bunch of classes need to have similar functionality. An interface can be created containing methods with empty body. Implementing classes then must provide body to those methods.

PHP does support Multi-level inheritance.
example:

class A {
// more code here
}

class B extends A {
// more code here
}

class C extends B {
// more code here
}


$someObj = new A(); // no problems
$someOtherObj = new B(); // no problems
$lastObj = new C(); // still no problems

PHP supports only overloading concept..


Lamp server installation in Ubuntu 10.04


Install the Apache Web Server

apt-get install apache2

Install the MySQL Database Server

apt-get install mysql-server

Install and Configure PHP

apt-get install php5 php-pear

If you need support for MySQL in PHP, then you must install the php5-mysql package with the following command:

apt-get install php5-mysql

Installing phpMyAdmin

apt-get install phpmyadmin

Configuring Apache to Recognize phpMyAdmin

gedit /etc/apache2/apache2.conf

Insert the following line:

Include /etc/phpmyadmin/apache.conf

After making changes to the PHP configuration file, restart Apache by issuing the following command:

/etc/init.d/apache2 restart

if u got any error while restart apache do below things

To fix that problem, you need to edit the httpd.conf file. Open the terminal and type,

gedit /etc/apache2/httpd.conf

By default httpd.conf file will be blank. Now, simply add the following line to the file.

ServerName localhost

install git-version controller

apt-get install git-core


Create a new Git Remote Repository from some local files

#On local machine (foo_project is project name)

cd foo_project
git init
git add *
git commit -m "My initial commit message"

#On remote machine (Git remote repository)

mkdir foo-project.git
cd foo-project.git/
git --bare init

#On local machine, in your git project

git remote add origin username@example.com:/home/username/foo_project.git

Removing Invalid Remote Origins

you can remove invalid remote origins using this below command

git remote rm origin

Read XML using php

Using SimpleXML:

test.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>


php code:

<?php
$xml = simplexml_load_file("test.xml");

echo $xml->getName() . "<br />";

foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child . "<br />";
  }
?>

OO Design Principles There are five principles of class design

(SRP) The Single Responsibility Principle

      A class should have one, and only one, reason to change.

      (If a change to the business rules causes a class to change, then a change to the database schema, GUI, report format, or any other segment of the system should not force that class to change. )

(OCP) The Open/Closed Principle

      Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

(LSP) The Liskov Substitution Principle

      Derived classes must be usable through the base class interface without the need for the user to know the difference.

(DIP) The Dependency Inversion Principle

      Abstractions should not depend upon details. Details should depend upon abstractions.

      High level modules should not depend upon low level modules. Both should depend upon abstractions.

(ISP) The Interface Segregation Principle

      Many client specific interfaces are better than one general purpose interface.

      The dependency of one class to another one should depend on the smallest possible interface.

0 comments: