Popular Posts

Tuesday, 20 July 2010

Encryption


Encryption is the conversion of data into a form, called a ciphertext, that cannot be easily understood by unauthorized people.

In PHP when we save the password from user we need to encrypt then only we save in our database the encrypted form of the password is called ciphertext of the password.

In some case we need to decrypt the data to get in original formate but in some cases like in case of password management we don’t need as in this case we need to compare only so in first case when user save provide password we save after encyption and in second case when user provided we again encrypted and the compare with the stored ciphertext of the password.

Consider in our case the password is susheel here first time when user provide susheel we encrypted and got 3a5ef784e9a57bb44c70f3680f0f2ec0 and then next time when he again provide the password susheel we again encrypt and find 3a5ef784e9a57bb44c70f3680f0f2ec0 in both cases these must be same if yes then we assume that the password is right. and thus allow.

In the below section we provide some encryption function of mysql and then we provided the PHP functions of the encryption.

Encryption in MySQL
md5
It is a strong method to get encrypted version any data as this is very simple to use so most people prefer to use this.

Example
mysql> select md5("susheel");
+----------------------------------+
| md5("susheel") |
+----------------------------------+
| 3a5ef784e9a57bb44c70f3680f0f2ec0 |
+----------------------------------+
1 row in set (0.02 sec)
password
This is another method of encryption as md5 this is also simple

Example
mysql> select password("susheel");
+-------------------------------------------+
| password("susheel") |
+-------------------------------------------+
| *1E79509ADA928DAE075CF1113838BB8D791EA8A4 |
+-------------------------------------------+
1 row in set (0.00 sec)

SHA1(Secure Hash Algorithm)
As per wiki
SHA-1 is the original 160-bit hash function. Resembling the earlier MD5 algorithm, this was designed by the National Security Agency (NSA) to be part of the Digital Signature Algorithm. Originally just called "SHA", it was withdrawn shortly after publication due to an undisclosed "significant flaw" and replaced by the slightly revised version SHA-1. The original withdrawn algorithm is now known by the retronym SHA-0.

SHA1() can be considered a cryptographically more secure equivalent of MD5()

Example

mysql> SELECT SHA1('abc');
+------------------------------------------+
| SHA1('abc') |
+------------------------------------------+
| a9993e364706816aba3e25717850c26c9cd0d89d |
+------------------------------------------+
1 row in set (0.00 sec)

We can do the same by using

mysql> SELECT SHA('abc');
+------------------------------------------+
| SHA('abc') |
+------------------------------------------+
| a9993e364706816aba3e25717850c26c9cd0d89d |
+------------------------------------------+
1 row in set (0.00 sec)

Encryption in PHP

As you have studied the encryption in MySQL now i am giving you a simple procedure to under stand about it’s implementation in PHP. First of all i suggest you to execute the below example script

$ctx = hash_init('sha1');
hash_update($ctx, 'susheel');
echo hash_final($ctx);
?>


When you will run this script the out put will be
bb30860cc6ca086c154bc9178c89f15114e3b954

Here you notice that the word “susheel” have been encrypted to bb30860cc6ca086c154bc9178c89f15114e3b954

In the above script i use sha1 as an encryption algorithm so what will i needed to do when we wish to use md5 as an encryption algorithm for this i just need to change the name of algorithm sha1 to md5 below i am giving you the same example after the changing of algo

$ctx = hash_init('md5');
hash_update($ctx, 'susheel');
echo hash_final($ctx);
?>
here in this case the out put is

3a5ef784e9a57bb44c70f3680f0f2ec0

By above two examples you noticed that the implementation of the encryption algorithms in php is quite simple

In the example i use three functions in hash_init() in this function we provide the name of the algorithm in which we want to encrypt and the hash_update() function in this we pass the string name which we want to encrypt and the next one hash_final() this was the function which finalize the incremental value and return the resulted encrypted value.

As you have saw the complete process to implement the encryption in php but the question is still remain about the list supported algorithm in php so for this i am giving an script which will list all the supported algorithm


print_r(hash_algos());
?>

Just run this, this will print the all supported algorithm and let you know all the supported alogorithm
when i implemented on our server the out put was

[0] => md2
[1] => md4
[2] => md5
[3] => sha1
[4] => sha256
[5] => sha384
[6] => sha512
[7] => ripemd128
[8] => ripemd160
[9] => ripemd256
[10] => ripemd320
[11] => whirlpool
[12] => tiger128,3
[13] => tiger160,3
[14] => tiger192,3
[15] => tiger128,4
[16] => tiger160,4
[17] => tiger192,4
[18] => snefru
[19] => gost
[20] => adler32
[21] => crc32
[22] => crc32b
[23] => haval128,3
[24] => haval160,3
[25] => haval192,3
[26] => haval224,3
[27] => haval256,3
[28] => haval128,4
[29] => haval160,4
[30] => haval192,4
[31] => haval224,4
[32] => haval256,4
[33] => haval128,5
[34] => haval160,5
[35] => haval192,5
[36] => haval224,5
[37] => haval256,5

So you can see that there the 37 algorithms of encryption which php supporting so when ever we wish to encrypt any string we just need to select an algorithm and then pass it to hash_init() and then pass the string in the function hash_update() and then get the encrypted string by the has_final . This process is straight forward and we easily can do it.

Now i am giving you an example and gor better understanding i suggest you execute this script on your server however this script is also uploaded in our server you can see by visiting on http://www.apepoint.com/demo/hashalogs.php page

The script is

/* Get the posted value of the form if there is one */
$p = empty($_POST['p']) ? null : $_POST['p'];
?>

Hash testing


String hashing












Table of hash values for based on algorithm









class="on">




Algorithm Hashed value of





Encryption of a file in PHP

Now coming to another important thing which is how to encrypt a file. for this we have very good function which we may use to encrypt a file below is an example script

echo hash_file('md5', 'test.php');
?>

here md5 is the name of the algorithm and the test.php is the name of the file as usual it is also a simple task .In this way we can encrypt a complete file.


In this chapter we explain the encryption in php by using various php functions .

Friday, 2 July 2010

other resources @apepoint

For orignial post kindly visit www.apepoint.com

File manager
A file manager or file browser is a computer program that provides a user interface to work with file systems. The most common operations used are create, open, edit, view, print, play, rename, move, copy, delete, attributes, properties, search/find, and permissions. Files are typically displayed in a hierarchy. Some file managers contain features inspired by web browsers, including forward and back navigational buttons.This software is very useful when we access our webserver from remote. Whern we use a third party hosting hosting provider provide us a file manager but we can install our own file manager as our requirement may vary from the features provided.

The below are the some open source download link you can download

http://sourceforge.net/projects/phpfilemanager/
http://sourceforge.net/projects/phpfm/
http://sourceforge.net/projects/ajaxplorer/
http://sourceforge.net/projects/file/


phpMyAdmin
phpMyAdmin is a tool written in PHP intended to handle the administration of MySQL over the Web. Currently it can create and drop databases, create/drop/alter tables, delete/edit/add fields, execute any SQL statement, manage keys on fields.

http://sourceforge.net/projects/phpmyadmin/

Email server

you must have studied about pop 3 imap4 protocols in your networking class. These protocols are used to access our emails .There are a number of software are available which used these protocols such as MS outlook thundermail and gmail. Here i am providing you a link of php3 you simply can download and install to access your mails.

http://sourceforge.net/projects/squirreloutlook/files/squirreloutlook-1.0.3/1.0.3/squirreloutlook-1.0.3.tar.gz/download


Search engine optimization
Search engine optimization (SEO) is the process of improving the volume or quality of traffic to a web site or a web page (such as a blog) from search engines via "natural" or un-paid ("organic" or "algorithmic") search results as opposed to other forms of search engine marketing ("SEM") which may deal with paid inclusion. The theory is that the earlier (or higher) a site appears in the search results list, the more visitors it will receive from the search engine. SEO may target different kinds of search, including image search, local search, video search and industry-specific vertical search engines. This gives a web site web presence.

Here i am giving you a link of SEO tutorials

http://www.netmechanic.com/products/SE-Tutorial.shtml


Add your URL to Google


In order to include the site in google search you need to add your site in google and the same is for other search engines below is the url for the same

http://www.google.com/addurl/

Server and execution environment information

For orignial post kindly visit www.apepoint.com

In a number of website you might have seen that the gadget which says that your IP Address is 202.3.77.111 etc not only this you also have seen in Google. They easily identify you web browsers name and tell whether it is mozila or chrome.



This stuff seems difficult but actually these are not. In PHP some constants are defined and by using these we can easily track these details let see a simple example



echo "your IP is ".$_SERVER['REMOTE_ADDR'];

?>

The above program is a very small program but does and awesome job. This program tell visitor's their IP



I must suggest you to visit Google to see the site www.ijaal.org and see how this accessing and telling the IP address of your PC.



In this site you notice that their are tracking user data so simply.



As We already explain that there are done by using some predefined constant .Now we wish to provide you complete list



Lets see a result i run a script which contain the variable name and got the our






VARIABLE NAME OUTPUT
PATH /usr/local/bin:/usr/bin:/bin
REDIRECT_STATUS 200
UNIQUE_ID ogrAT9iXpEIAAHw1fLwAAAAH
SCRIPT_URL /server.php
SCRIPT_URI http://www.apepoint.com/server.php
HTTP_HOST www.apepoint.com
HTTP_USER_AGENT Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Gecko/2008051206 Firefox/3.0
HTTP_ACCEPT text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_LANGUAGE en-us,en;q=0.5
HTTP_ACCEPT_ENCODING gzip,deflate
HTTP_ACCEPT_CHARSET ISO-8859-1,utf-8;q=0.7,*;q=0.7
HTTP_KEEP_ALIVE 300
HTTP_CONNECTION keep-alive
SERVER_SOFTWARE Apache/2.0.52 (Red Hat) FrontPage/5.0.2.2635
SERVER_NAME www.apepoint.com
SERVER_ADDR 216.151.164.66
SERVER_PORT 80
REMOTE_ADDR 112.196.130.213
DOCUMENT_ROOT /usr/local/pem/vhosts/107976/webspace/httpdocs
SERVER_ADMIN [no address given]
SCRIPT_FILENAME /usr/local/pem/vhosts/107976/webspace/httpdocs/server.php
REMOTE_PORT 61777
REDIRECT_URL /server.php
GATEWAY_INTERFACE CGI/1.1
SERVER_PROTOCOL HTTP/1.1
REQUEST_METHOD GET
QUERY_STRING

REQUEST_URI /server.php
SCRIPT_NAME /server.php
ORIG_SCRIPT_FILENAME /usr/libexec/php5-cgi/bin/php-cgi
ORIG_PATH_INFO /server.php
ORIG_PATH_TRANSLATED /usr/local/pem/vhosts/107976/webspace/httpdocs/server.php
ORIG_SCRIPT_NAME /cgi-php5/php-cgi
PHP_SELF /server.php
REQUEST_TIME 1275749739
argv Array
argc 0



Here is one more example of the same just run the below script

echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "";
echo "
" .$_SERVER['argv'] ."argv
" .$_SERVER['argc'] ."argc
" .$_SERVER['GATEWAY_INTERFACE'] ."GATEWAY_INTERFACE
" .$_SERVER['SERVER_ADDR'] ."SERVER_ADDR
" .$_SERVER['SERVER_NAME'] ."SERVER_NAME
" .$_SERVER['SERVER_SOFTWARE'] ."SERVER_SOFTWARE
" .$_SERVER['SERVER_PROTOCOL'] ."SERVER_PROTOCOL
" .$_SERVER['REQUEST_METHOD'] ."REQUEST_METHOD
" .$_SERVER['REQUEST_TIME'] ."REQUEST_TIME
" .$_SERVER['QUERY_STRING'] ."QUERY_STRING
" .$_SERVER['DOCUMENT_ROOT'] ."DOCUMENT_ROOT
" .$_SERVER['HTTP_ACCEPT'] ."HTTP_ACCEPT
" .$_SERVER['HTTP_ACCEPT_CHARSET'] ."HTTP_ACCEPT_CHARSET
" .$_SERVER['HTTP_ACCEPT_ENCODING'] ."HTTP_ACCEPT_ENCODING
" .$_SERVER['HTTP_ACCEPT_LANGUAGE'] ."HTTP_ACCEPT_LANGUAGE
" .$_SERVER['HTTP_CONNECTION'] ."HTTP_CONNECTION
" .$_SERVER['HTTP_HOST'] ."HTTP_HOST
" .$_SERVER['HTTP_REFERER'] ."HTTP_REFERER
" .$_SERVER['HTTP_USER_AGENT'] ."HTTP_USER_AGENT
" .$_SERVER['HTTPS'] ."HTTPS
" .$_SERVER['REMOTE_ADDR'] ."REMOTE_ADDR
" .$_SERVER['REMOTE_HOST'] ."REMOTE_HOST
" .$_SERVER['REMOTE_PORT'] ."REMOTE_PORT
" .$_SERVER['SCRIPT_FILENAME'] ."SCRIPT_FILENAME
" .$_SERVER['SERVER_ADMIN'] ."SERVER_ADMIN
" .$_SERVER['SERVER_PORT'] ."SERVER_PORT
" .$_SERVER['SERVER_SIGNATURE'] ."SERVER_SIGNATURE
" .$_SERVER['PATH_TRANSLATED'] ."PATH_TRANSLATED
" .$_SERVER['SCRIPT_NAME'] ."SCRIPT_NAME
" .$_SERVER['REQUEST_URI'] ."REQUEST_URI
" .$_SERVER['PHP_AUTH_DIGEST'] ."PHP_AUTH_DIGEST
" .$_SERVER['PHP_AUTH_USER'] ."PHP_AUTH_USER
" .$_SERVER['PHP_AUTH_PW'] ."PHP_AUTH_PW
" .$_SERVER['AUTH_TYPE'] ."AUTH_TYPE
"
?>


The tracking the details is very simple for every there is a variable very soon we will add some more good example for better explanation

PHP with MYSQL

For orignial post kindly visit www.apepoint.com

When we work with MySQL we need to execute a number of query .We can execute almost all these queries by using PHP. For this PHP have provided some of inbuild function In the below list i have provided details of some of the inbuild functions.

mysql_connect()

This function is use to establish a connection with PHP SCRIPT and MySQL.

mysql_select_db()

This function is used to select database on which we will execute query

mysql_query()

This function execute a mysql query in selected database

mysql_fetch_row()

This function return a row of data from result as a numeric array

mysql_num_row()

This return number of rows in the result set.

mysql_error()

This function let us know the exact error in our mysql query if any.

mysql_close()

This function close the mysql connection

Now we are going to make a connection with our database (MySQL) and execute a query

This process is done in four steps

Step 1: Establishing connection
Step 2: Selecting database
Step 3: Executing a query
Step 4: Closing connection

As earlier I have explained the inbuild function lets take an example for excuting a query of create table in database "apepoint".


mysql_connect("hostname","username","password");
mysql_select_db("apepoint");
mysql_query("create table visitors(id int(4), ipaddress varchar(20))");
mysql_close($link);
?>


This is enough and the above query will execute and a table visitors will create in database apepoint. In some case there may be some error for example error in query so for this we need a proper error handling this is quite simple the below example add this also

mysql_connect("hostname","username","password") or die(mysql_error());
mysql_select_db("apepoint")or die(mysql_error());
mysql_query("create table visitors(id int(4), ipaddress varchar(20))")or die(mysql_error());
mysql_close();
?>


In this example we use

mysql_connect("hostname","username","password") this function is used to connect with our database this take 3 parameters and establish a connection with our database.

In case you have any problem in executing above script we suggest you to execute the below script

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

This tell you where the connection is established or not.


mysql_select_db("database_name")

This function is used to select database name a in mysql there may be so many database so we must provide the database name before executing any query.

mysql_query($sql)

This function is used to execute a mysql query in our database we can pass any query in this function

Some time we may want to know the total no. of affected row so we can get by using

int mysql_affected_row($result);

The below is an example of this

mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db('mydb');
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());
?>
mysql_close()

After completing the process we mysql close a mysql connecion this can be done by this function

In the previous example we study how to execute a query

But what about the cases when we execute query which return some result for example when we want to display result on web page.This process is little complex as it requre some extra effort

Consider we have a table which contents
visitors
ipaddress ID
localhost 122.0.0
google.com 209.85.227.147
apepoint.com 216.151.164.66




for this we will repeat first 3 steps

step 1 extablish connection
step 2 select database
step 3-a execute query
step 3-b process result
step 4 close connection

here you can under stand that step 3 has been expended

mysql_connect("hostname","username","password") or die(mysql_error());
mysql_select_db("apepoint")or die(mysql_error());
$result=mysql_query("select*from visitors")or die(mysql_error());

while($row=mysql_fetch_row($result))
{
echo "ID :";
echo $row[0];
echo "IP Address :";
echo $row[1];
echo "\n":
}

mysql_close();
?>


In this we use function mysql_fetch_row($result) this function return result as an enumerated array.

In some case we may need to save the result in array

we can do it by useing array_push() function below is the implementation of the same

$id= array;
$ip=array;
mysql_connect("hostname","username","password") or die(mysql_error());
mysql_select_db("apepoint")or die(mysql_error());
$result=mysql_query("select*from visitors")or die(mysql_error());

while($row=mysql_fetch_row($result))
{
array_push($id,$row[0]);
array_push($ip,$row[1]);
}

mysql_close();
?>


the above example store resulted data in arrays of id and ip address.

Apart from these there are so many more functions are available some of these are explained by below examples


mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}
mysql_free_result($result);
?>

In this example we use mysql_fetch_object function this function fetch results in the form of object



mysql_connect("hostname","username","password") or die(mysql_error());
mysql_select_db("apepoint")or die(mysql_error());
$result=mysql_query("select*from visitors")or die(mysql_error());

while($row=mysql_fetch_assoc($result))
{
echo "ID :";
echo $row->id;
echo "IP Address :";
echo $row->ipaddress;
echo "\n":
}

mysql_close();
?>


In the above example we use mysql_fetch_assoc() function this fetch the result is in the form of an associative array


For more example kindly click on the link script tute from main menu.
In this i explained about the visitors tracking by using php mysql

Electronic mail

Electronic mail

For orignial post kindly visit www.apepoint.com




Electronic mail, most commonly abbreviated email or e-mail, is a method of exchanging digital messages. E-mail systems are based on a store-and-forward model in which e-mail server computer systems accept, forward, deliver and store messages on behalf of users



An electronic mail message consists of two components, the message header, and the message body, which is the email's content.



message header usually state the senders name, email address, and the date that it was sent.




Internet e-mail messages consist of two major sections:
Header — Structured into fields such as summary, sender, receiver, and other information about the e-mail.
Body — The message itself as unstructured text; sometimes containing a signature block at the end. This is exactly the same as the body of a regular letter.






In these days e-mail is the most popular Internet service today. A plenty of emails are sent and delivered each day. The goal of this tutorial is to demonstrate how to generate and send emails in PHP.





So, you want to send automated email messages from your PHP application. This can be in direct response to a user's action, such as signing up for your site, or a recurring event at a set time, such as a monthly newsletter. Sometimes email contains file attachments, both plain text and HTML portions, and so on. To understand how to send each variation that may exist on an email, we will start with the simple example and move to the more complicated.



Note that to send email with PHP you need a working email server that you have permission to use: for Unix machines, this is often Sendmail; for Windows machines, you must set the SMTP directive in your php.ini file to point to your email server.



For sending mail we need to use mail function

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )


The below is an example of simple mail

Example : A simple mail function

mail('recipient@some.net', 'Subject', 'Your message here.');
?>

Example : Here is one more example of the same



$to = 'susheel1104@gmail.com';
$subject = 'the subject';
$message = 'hi';
$headers = 'From: webmaster@apepoint.com' . "\r\n" .
'Reply-To: webmaster@apepointcom' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

Example An example of sending mail with attachement.



In the below example the variable $filename is the file name which will get attached with the message



$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";


if (mail($mailto, $subject, $body, $header))
{
echo = "mail send ... OK";
}
else
{
echo = "mail send ... ERROR!";
}

}
?>



To add mail priority we need to add few more line in mail header

$headers .= "X-Priority: 1 (Higuest)\n";
$headers .= "X-MSMail-Priority: High\n";
$headers .= "Importance: High\n";

During mail sending we need to provide complete header for more of this i recommend to study MIME Header

Object Oriented Programming PHP

Object Oriented Programming PHP

For orignial post kindly visit www.apepoint.com


Object oriented programming is the dominant programming paradigm these days, having replaced the "structured procedure based programming techniques".

In oop the program is made of objects, with certain properties and operations that the object can perform oop reverses the order and puts data first then looks at the algorihms that seperates on the data

once you understand the oop concept I ensure you that the developing a big projects will be an ordinary task for you I must write haere that if you are developing an application that is small and you can develop alone then you can go for procedure programming but if your application is big and in tean no of peoples are plural so you must use this befor moving any example is i recommend you to under stand some more concepts


Classes

A class definition begins with the keyword class followed by whatever name assign to it and variable and methods within braces.

Properties and method

when we define a class we define some of the variable's inside that are accessible in its functions are knowns as properties. These variable maintain the state of object.


In class as variable are define we define function these function are called methods they are aas a method for communicating with and manipulating the data within the object Methods provided the object with a standard interface that any one can use.

Public Private

The visibility of the properties and methods of a class can be set as public or provate. Those that are marked wiht the private keywork are only accessibel from within the class itself . Those marked with the public keywork on the other hand are accessible from both inside and outside of the class.


Constructors and Destructors
In some cases we need to initialize the some of properties of a class we can do it by using constructors they are methods which are written inside class define and the name of this method is same as class name.

In some cases we want to close some resources before moving from that class object we can do so by using destructors.

Example

class MyDestructableClass {

function MyDestructableClass () {
print "In constructor\n";
$this->name = "MyDestructableClass";
}


function __destruct() {
print "Destroying " . $this->name . "\n";
}

}

$obj = new MyDestructableClass();
?>

here in above example method function MyDestructableClass () { } is a constructor and the another method is a Destructors



For more example kindly click on the link script tute from main menu.
In this i explained about the visitors tracking by using php mysql

session cookies header

For orignial post kindly visit www.apepoint.com

for the original contents kindly visit www.apepoint.com

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site A visitor accessing your web site is assigned a unique id, the so-called session id.

A normal HTML website will not pass data from one page to another. In other words, all information is forgotten when a new page is loaded. A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, e-mail id , etc). However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions

Sessions work by creating a unique identification(UID) number for each visitor and storing variables based on this ID. This helps to prevent two users' data from getting confused with one another when visiting the same webpage

starting a php session

Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.

PHP Code:
session_start();
?>

Creating and reading session variables

Variables can be assigned to a session by using the $_SESSION global variable. Any value that is assigned to a $_SESSION variableis readable by any script that is served by your web server and is viewed in the same session.

session_start();
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data
?>

Cleaning and destroying your session.

some time we want to clear a session data so we can use the below function

unset($_SESSION['userid']);

You can also completely destroy the session entirely by calling the session_destroy function.

PHP Code:

session_start();
session_destroy();
?>

HTTP Headers

There are several things importance of HTTP header but generally in php we use in re-direct and in graphics below is an example of a redirect code

header("Location:home.php");

the script will redirect to home.php page


Cookies

PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser setcookie — Send a cookie

php start
$value = 'something from somewhere';
setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600); /* expire in 1 hour */
php close


php start
// Print an individual cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];
// Another way to debug/test is to view all cookies
print_r($_COOKIE);
php close


Any cookies sent to you from the client will automatically be included into a $_COOKIE auto-global array if variables_order contains "C". If you wish to assign multiple values to a single cookie, just add [] to the cookie name.

Form processing in PHP

Form processing in PHP

kindly visit www.apepoint.com for the original content of this blog


Before moving to this chapter i must suggest you to go through the basis form designing tutorial of HTML here i am giving you an example of a simple form which let revise your HTML concept.



<br />Say Hellow <br />



Kindly proivde us your E-mail ID













You can understand that the form HTML code let user to enter his email ID and submit to process for saving in our database. You also noticed that for form action i passed emailsave.php file and method is "get". It means emailsave.php will process the form and by using GET it will fetch the values and save in our database.

Here is a code of emailsave.php


$mail=$_GET['mail']; // here by this form field is saved in variable and now we can //process

// now we will write code to save in our database

mysql_connect("localhost","username","password") ;

mysql_select_db("test");
mysql_query("insert into request values(email)");

mysql_close();

echo " Email saved in our data base";

?>

In the above code you noticed by that by using $_GET[' '] the value of form field was picked and by 5 lines of mysql code email was saved in our database. in case you have not studied these code I recommend to study at http://www.apepoint.com/php_mysql.php


You may ask if we take POST as form method in file emailrequest.html then what changes we require in file emailsave.php In this case we need a small change i case of $_GET we will require $_POST[' '] and the remaining code will remain unchanged

see what about cases when we forget to recall about the form action wether it was get or post then no issue we may use $_REQUEST you must be happy to know that $_REQUEST can be used

One more thing you must notice that by using $_GET the alue which user enter in the form get saved in variable $mail . In the eamilsave.php we write code to save in database but we can use this variable for any other purpose

I must write here that in above example i show how user let to provide his email but in real it require some more effort. this effort is called validation you need to write script to validate this form in 3 different stage one by using JavaScript or Jquery and by PHP and mysql

Very soon some more example will be uploaded for this and this will help you understand more and more.

PHP array

 



PHP array


In c like language we all studied that an array is a collection of similar elements. These similar elements could be all int or all floats or all chars . Ber here we prefer to define that array in such a way that are nothing more then lists of information mapped with keys and stored under one variable name.

In PHP the arrays are quite different and even more simple to manage

Array Syntax

php start 

$employee=array("pfn"="c567","name"="rahul");

echo $emaployee['name'];
?>

The same can be done by this also

php start
$employee['pfn"]="c567";
$employee["name"]="rahul";
php end

In php each array element can contain another array as a value, which in turn can hold other arrays as well. In such a way you can create two-dimensional or three-dimensional array.

The below is an example of this

php start 
$employee= array( array("richa", "mca"),
               array("divya", "btech"),
               array("rahul", "mca") 
             ); 
php end

If we discuss about array and ignore to discuss of array function will bot be fair so below are some basis function of array

--sort($array)
            As name suggest it sort array
--rsort($array)
            As name suggets it sort array in reverse order
--count($array)
            It return total no. of element in an array

Emaple which sort element of array

php start
$color[]="red";
$color[]="green";
$color[]="white";


sort($color);

foreach($color as $c)
echo $c."\n";

php end
           
This will print array in sorted manner

green
red
white

As you have seen that an array has been iterated by foreach apart from this there are so many ways to iterate it for example for loop while loop.


If require we can print whole array without iteration we can use print_r($array)  the below is an example of the same;

php start

// Create a simple array.

$array = array(1, 2, 3, 4, 5);

print_r($array);

php end

out put will

Array

(

[0] = 1

[1] = 2

[2] = 3

[3] = 4

[4] = 5

)



I suggest you to go through the list of array functions for more http://in2.php.net/manual/en/ref.array.php

PHP basis programming

PHP basis programming


kindly visit www.apepoint.com for the original content of this blog.

Here in this chapter we will learn how to write simple php program and will also let you know various basis and helpful thing

In this chapter you will learn

First PHP script
Integration of PHP code in HTML CSS
Require and include
Date function
SERVER Varibles
How to run PHP

PHP is a server side programming language. So in order to run we need an installed server in our machine. There are so many servers are availbale we can download any in our system for example you can go for wamp(WINDOW APACHE MYSQL PHP) for window and on linux you can go for LAMP (LINUX APACHE MYSQL PHP)

After downloading and installing the server try to find the www folder in the installation directory for example in for WAMP it should be at c://wamp/www for linux /var/www/ and save your file in this directory and then open web browser and type the address

http://localhost/{ file-name}

For example you make file test.php and then open the web browser and type http://localhost/test.php in address bar this will display the out put of your script

As you can see the process is very simple in case any problem you can mail me at susheel@apepoint.com

Integrating HTML with PHP

In web we not only need to think about it's functionality but also about it's look s HTML , CSS are being most simple things to provide the looks on web and fortunely PHP provide very good support to these programming language these can be included at any time at any case

Below is an example which explain how H1 ta is can be included in PHP


echo "

Apepoint welcome you

";

?>

Here you saw how HTML is included in PHP to formate the out put this is very simple at any time we can include it there is one more example of this

Require and Include

Some time we need to write a specific code again and again for this as oter programming script language PHP provide function by using we can save our time. But in some case we need to write the same code in multiple pages thus this method does not help too much for this we have a very good solution of include/require

Here we are taking a very good example we need to type host name user name in password in all the time whenever we need to connect with database for example mysql in database specific applications consider in our application there are over 500 pages we can do so but what about the cases when we want to change the password in this case we will require to cahnge the password in all 500+ pages . So it is very tough task for any one. so for this we suggest to write a seperate file containging these details and include this in all files whenever require by syntax

include "config.php";

and when we require just make chnage in the single file it will make changes in all files
The same work can be done by using require function by below syntax
require "config.php";

Here their is different that in case file in finf in "include" case it will ignore and let script excute but in "require" case it will return fatel error and stop excution of script


file hi.php

echo "hi";
?>

another file

include "hi.php";

echo "susheel";

?>
DATE in PHP

There are several cases when we need to use date for example calendar based application, scheduling E-mail. Calendar is part of our life as it is part of our project for example in project of News PUBLISHING IT REQUIRE TO send news along with the date and when user visited our side it tell that it is 4 days old apart from this there are so many other needs We must recall a very standard thing here that in web technology there are so many data n time feature.



PHP have a great advantage over other script as in java script, Macromedia flash they fetch data time form the user's pc but the php fetch it from server. Thus it provides a most trusted date and time as it can be adjusted from server.



Jave script we can design some animated watch but if we provide time to these watch by PHP(through AJAX) then we can get these time form most updated



Before going through the details of this we wish to provide an example


$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
echo $today;
?>

The above script will print March 10, 2001, 5:16 pm here in this example you notice that Date object we passed F J Y g i a constants and get the date March 10, 2001, 5:16 pm in format so in case you just passed F only it will print March
if you passed j it will return 10 and so on here you notic that data and time printing is very simple in PHP By using require constant and date() we can get date and time in any format

Here we are giving one more example for this



// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the

$today = date("F j, Y, g:i a"); // return March 10, 2001, 5:16 pm
$today = date("m.d.y"); // return 03.10.01
$today = date("j, n, Y"); // return 10, 3, 2001
$today = date("Ymd"); // return 20010310
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // return it is the 10th day.
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // return 17:03:18 m is month
$today = date("H:i:s"); // return 17:16:18
?>



Here i a brief list of these constant
d
Day of the month, 2 digits with leading zeros
01 to 31

D
A textual representation of a day, three letters
Mon through Sun

j
Day of the month without leading zeros
1 to 31

l (lowercase 'L')
A full textual representation of the day of the week
Sunday through Saturday

N
ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)
1 (for Monday) through 7 (for Sunday)

S
English ordinal suffix for the day of the month, 2 characters
st, nd, rd or th. Works well with j

w
Numeric representation of the day of the week
0 (for Sunday) through 6 (for Saturday)

z
The day of the year (starting from 0)
0 through 365




We suggest you to try one after another to under this.

Installing Apache Mysql PHP

On window


Here the process is straight forward just download WAMP server and double click it will automatically install and you can run you php scripts by saving in C:/wamp/www/ directory
On Ubuntu



The process is little time taking but straight forward so just follow the below steps and install LAMP(Linux apache Mysql PHP)

Install Apache

To start off we will install Apache.
1. Open up the Terminal (Applications > Accessories > Terminal).
2. Copy/Paste the following line of code into Terminal and then press enter:
sudo apt-get install apache2

3. The Terminal will then ask you for you're password, type it and then press enter.
Testing Apache


To make sure everything installed correctly we will now test Apache to ensure it is working properly.
1. Open up any web browser and then enter the following into the web address:
http://localhost/
You should see a folder entitled apache2-default/. Open it and you will see a message saying "It works!" , congrats to you!
Install PHP


In this part we will install PHP 5.
Step 1. Again open up the Terminal (Applications > Accessories > Terminal).
Step 2. Copy/Paste the following line into Terminal and press enter:
sudo apt-get install php5 libapache2-mod-php5
Step 3. In order for PHP to work and be compatible with Apache we must restart it. Type the following code in Terminal to do this:
Restart Apache


Type the following code in Terminal to do this:
sudo /etc/init.d/apache2 restart


Test PHP


To ensure there are no issues with PHP let's give it a quick test run.
Step 1. In the terminal copy/paste the following line:
sudo gedit /var/www/testphp.php
This will open up a file called phptest.php.
Step 2. Copy/Paste this line into the phptest file:

Step 3. Save and close the file.
Step 4. Now open you're web browser and type the following into the web address:
http://localhost/testphp.php
The page should look like this:

Congrats you have now installed both Apache and PHP!
Install MySQL


To finish this guide up we will install MySQL. (Note - Out of Apache and PHP, MySQL is the most difficult to set up. I will provide some great resources for anyone having trouble at the end of this guide.)
Step 1. Once again open up the amazing Terminal and then copy/paste this line:
sudo apt-get install mysql-server

Step 2 (optional). In order for other computers on your network to view the server you have created, you must first edit the "Bind Address". Begin by opening up Terminal to edit the my.cnf file.
gksudo gedit /etc/mysql/my.cnf
Change the line
bind-address = 127.0.0.1
And change the 127.0.0.1 to your IP address.
Step 3. This is where things may start to get tricky. Begin by typing the following into Terminal:
mysql -u root
Following that copy/paste this line:
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('yourpassword');
(Make sure to change yourpassword to a password of your choice.)
Step 4. We are now going to install a program called phpMyAdmin which is an easy tool to edit your databases. Copy/paste the following line into Terminal:
sudo apt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin

After that is installed our next task is to get PHP to work with MySQL. To do this we will need to open a file entitled php.ini. To open it type the following:


gksudo gedit /etc/php5/apache2/php.ini
Now we are going to have to uncomment the following line by taking out the semicolon (;).
Change this line:
;extension=mysql.so
To look like this:
extension=mysql.so
Now just restart Apache and you are all set!
sudo /etc/init.d/apache2 restart

PHP: Hypertext Preprocessor HISTORY

PHP: Hypertext Preprocessor is a widely used, general-purpose scripting language that was originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document


PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus Lerdorf in 1995, initially as a simple set of Perl scripts for tracking accesses to his online resume. He named this set of scripts 'Personal Home Page Tools'.

PHP/FI, which stood for Personal Home Page / Forms Interpreter, It had Perl-like variables, automatic interpretation of form variables and HTML embedded syntax.

PHP is a general-purpose scripting language that is especially suited to server-side web development where PHP generally runs on a web server. Any PHP code in a requested file is executed by the PHP runtime, usually to create dynamic web page content. It can also be used for command-line scripting and client-side GUI applications. PHP can be deployed on most web servers, many operating systems and platforms, and can be used with many relational database management systems. It is available free of charge, and the PHP Group provides the complete source code for users to build, customize and extend for their own use

It was riginally designed to create dynamic web pages, PHP now focuses mainly on server-side scripting, and it is similar to other server-side scripting languages that provide dynamic content from a web server to a client, such as Active Server Pages, JavaServer Pages.

An example of PHP

"http://www.w3.org/TR/html4/loose.dtd">


Example



echo "Hi, I'm a PHP script!";
?>





PHP only parses code within its delimiters. Anything outside its delimiters is sent directly to the output and is not processed by PHP


The most common delimiters are to close PHP sections.


With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.

One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple.


Fore such article kindly visit www.apepoint.com

What is a web Site

A set of interconnected webpages, usually including a homepage, generally located on the same server, and prepared and maintained as a collection of information by a person, group, or organization.



A website is a collection of related web pages, images, videos or other digital assets .



A web page or webpage is a document or resource of information that is suitable for the World Wide Web and can be accessed through a web browser and displayed on a monitor or mobile device.



Web pages are accessed and transported with the Hypertext Transfer Protocol (HTTP), which may optionally employ encryption (HTTP Secure, HTTPS) to provide security and privacy for the user of the web page content. The user's application, often a web browser, renders the page content according to its HTML markup instructions onto a display terminal.



We can divide the website into two major section:--



Static website



A static website is one that has web pages stored on the server in the format that is sent to a client web browser. It is primarily coded in Hypertext Markup Language (HTML).



they present pre-defined, static information to the user. This may include information about a company and its products and services via text, photos, animations, audio/video and interactive menus and navigation.



There are many websites on the inernet you won’t be able to tell immediately if it is static , but the chances are, if the site looks basic and is for smaller company and simple delivers information . it could be website



Static websites are cheapest to develop and host and can be quicked develop. Many companies made their static website to make their online presence.



Dynamic website



A dynamic website is one that changes or customizes itself frequently and automatically, based on certain criteria.



The main purpose of a dynamic website is automation. A dynamic website can operate more effectively, be built more efficiently and is easier to maintain, update and expand.



At the basic level , dynamic website gives the admin the facility of frequently updation through simpale web interface. A an ex. In any news poral there is regular updation of latest news. Some of the features of dynamic websites are content management system, bulletin board, user management, discussion forum, file, image,video uploading, social networking,e-commerse appliation etc.



Dynamic website can let the end user to perform several control task and get the relevant result.



Dyanamic website contains much more web functionality and let admin change the theme , layout , functionality in easy way. This website takes a good team effort in order to develop and also expensive in development and hosting.