Category Archives: synapse india jobs

SynapseIndia Part 4 – Displaying Data Php Development

Introduction

So far in this tutorial, you have created a database and put information into it. In this part I will show you how to create an input page for your database, and how to display the whole contents.

HTML Input

Inputing the data using HTML pages is almost identical to inserting it using a PHP script. The benefit, though, is that you do not need to change the script for each piece of data you want to input and you can also allow your users to input their own data.

The following code will show an HTML page with textboxes to enter the appropriate details:

<form action=”insert.php” method=”post”>
First Name: <input type=”text” name=”first”><br>
Last Name: <input type=”text” name=”last”><br>
Phone: <input type=”text” name=”phone”><br>
Mobile: <input type=”text” name=”mobile”><br>
Fax: <input type=”text” name=”fax”><br>
E-mail: <input type=”text” name=”email”><br>
Web: <input type=”text” name=”web”><br>
<input type=”Submit”>
</form>

This page could, of course, be formatted and have other changes made to it. It is just a basic form to get you started. Next you will need to edit the script from last week. Instead of using information to input into the database, you will instead use variables:
<?
$username=”username”;
$password=”password”;
$database=”your_database”;

$first=$_POST[‘first’];
$last=$_POST[‘last’];
$phone=$_POST[‘phone’];
$mobile=$_POST[‘mobile’];
$fax=$_POST[‘fax’];
$email=$_POST[’email’];
$web=$_POST[‘web’];

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( “Unable to select database”);

$query = “INSERT INTO contacts VALUES (”,’$first’,’$last’,’$phone’,’$mobile’,’$fax’,’$email’,’$web’)”;
mysql_query($query);

mysql_close();
?>

This script should then be saved as insert.php so that it can be called by the HTML form. It works because, instead of the data being entered locally, it is being entered into the form and stored in variables which are then passed to the PHP.

You could also add to this script a message confirming the data input. This is basic PHP, though, and you should read the PHP tutorial if you do not know how to do this.

Outputting Data

Now you have at least one record, if not many more, in your database you will be wanting to know how you can output this data using PHP. Before beginning, though you should be familiar with loops in PHP (you can find out about them in the tutorial on Free Webmaster Help) as they are used for this way of outputting data.

The first command you will need to use is a MySQL query made up like this:

SELECT * FROM contacts

This is a basic MySQL command which will tell the script to select all the records in the contacts table. Because there will be output from this command it must be executed with the results being assigned to a variable:

$query=”SELECT * FROM contacts”;
$result=mysql_query($query);

In this case the whole contents of the database is now contained in a special array with the name $result. Before you can output this data you must change each piece into a separate variable. There are two stages to this.

Counting Rows

Before you can go through the data in your result variable, you must know how many database rows there are. You could, of course, just type this into your code but it is not a very good solution as the whole script would need to be changed every time a new row was added. Instead you can use the command:

$num=mysql_numrows($result);

This will set the value of $num to be the number of rows stored in $result (the output you got from the database). This can then be used in a loop to get all the data and output it on the screen.

Setting Up The Loop

nYou must now set up a loop to take each row of the result and print out the data held there. By using $num, which you created above, you can loop through all the rows quite easily. In the code below, $i is the number of times the loop has run and is used to make sure the loop stops at the end of the results so there are no errors.

$i=0;
while ($i < $num) {

CODE

$i++;
}

This is a basic PHP loop and will execute the code the correct number of times. Each time $i will be one greater than the time before. This is useful, as $i can be used to tell the script which line of the results should be read. As the first line in MySQL output is 0, this will work correctly.

Assigning The Data To Variables

The final part of this output script is to assign each piece of data to its own variable. The following code is used to do this:

$variable=mysql_result($result,$i,”fieldname”);

So to take each individual piece of data in our database we would use the following:

$first=mysql_result($result,$i,”first”);
$last=mysql_result($result,$i,”last”);
$phone=mysql_result($result,$i,”phone”);
$mobile=mysql_result($result,$i,”mobile”);
$fax=mysql_result($result,$i,”fax”);
$email=mysql_result($result,$i,”email”);
$web=mysql_result($result,$i,”web”);

We do not need to get the ID field (although we could have done) because we have no use for it in the current output page.

Combining The Script

We can now write a full script to output the data. In this script the data is not formatted when it is output:

<?
$username=”username”;
$password=”password”;
$database=”your_database”;

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( “Unable to select database”);
$query=”SELECT * FROM contacts”;
$result=mysql_query($query);

$num=mysql_numrows($result);

mysql_close();

echo “<b><center>Database Output</center></b><br><br>”;

$i=0;
while ($i < $num) {

$first=mysql_result($result,$i,”first”);
$last=mysql_result($result,$i,”last”);
$phone=mysql_result($result,$i,”phone”);
$mobile=mysql_result($result,$i,”mobile”);
$fax=mysql_result($result,$i,”fax”);
$email=mysql_result($result,$i,”email”);
$web=mysql_result($result,$i,”web”);

echo “<b>$first $last</b><br>Phone: $phone<br>Mobile: $mobile<br>Fax: $fax<br>E-mail: $email<br>Web: $web<br><hr><br>”;

$i++;
}

?>

SynapseIndia Part 3 – Inserting Information Php Development

Introduction

Over the past two parts I have explained what I am planning to do in this tutorial and have shown you how to create a database to use with the tutorial. In this part I will be showing you how to insert some information into your database so that it is more useful.

Connecting To The Database

The first thing you must do before you can do any work at all is to connect to the MySQL database. This is an extremely important step as, if you are not connected, your commands to the database will fail.

Good practice for using databases is to specify the username, password and database name first so that if you change any of them at a later date you will only have to change one line:

$username=”username”;
$password=”password”;
$database=”your_database”;

At this point you may be wondering if it is a security risk, keeping your password in the file. You don’t need to worry, though, because the PHP scource code is processed aby the server before being sent to the browser so it is impossible for the user to see the script’s source.

Next, you will need to issue the command to start a database connection:

mysql_connect(localhost,$username,$password);

This line tells PHP to connect to the MySQL database server at ‘localhost’ (localhost means the server that the site is running one. Unless you web host tells you otherwise you should use localhost. If you are given a server address (such as sql.myserver.com you should replace localhost with “sql.myserver.com” (including the quotes)) using the username stored in $username and the password in $password.

Before I show you how to work with the database, I will show you one more command:

mysql_close();

This is a very important command as it closes the connection to the database server. Your script will still run if you do not include this command but too many open MySQL connections can cause problems for a web host. It is good practice to always include this line once you have issued all your commands to the database, to keep the server running well.

Selecting The Database

After you have connected to the database server you must then select the database you wish to use. This must be a database to which your username has access. The following command:

@mysql_select_db($database) or die( “Unable to select database”);

is used to do this. This tells PHP to select the database stored in the variable $database (which you set earlier). If it cannot connect it will stop executing the script and output the text:

Unable to select database

This extra ‘or die’ part is good to leave in as it provides a little error control but it is not essential.

Executing Commands

Now you have connected to the server and selected the database you want to work with you can begin executing commands on the server.

There are two ways of executing a command. One is to just enter the command in PHP. This way is used if there will be no results from the operation.

The other way is to define the command as a variable. This will set the variable with the results of the operation.

In this part of the tutorial we will use the first way as we are not expecting a response from the database. The command will look like this:

mysql_query($query);

The useful thing about using this form of the command is that you can just repeat the same command over and over again without learning new ones. All you need to do is to change the variable.

Inserting Data

For this part of the tutorial I will return to the contacts database which we created in the last part. We will now add our first information to the database:

First: John
Last: Smith
Phone: 01234 567890
Mobile: 00112 334455
Fax: 01234 567891
E-
mail: johnsmith@gowansnet.com
Web: http://www.gowansnet.com

This will all be put in with one command:

$query = “INSERT INTO contacts VALUES (”,’John’,’Smith’,’01234 567890′,’00112 334455′,’01234 567891′,’johnsmith@gowansnet.com’,’http://www.gowansnet.com&#8217;)”;

This may look a little confusing at first so I will explain what it all means.

Firstly $query= is there because we are assigning this to the variable $query (see the section above). The next part:

INSERT INTO contacts VALUES

is quite easy to understand. It tells the PHP to insert into the table called contacts the values in the brackets which follow.

The part in the brackets contains all the information to add. It uses all the fields in order and inserts the information from between the quotes. For example:

John

will be inserted into the 2nd field which, in this table, is the ‘first’ field.

You may have noticed that you are not inserting any value into the first field in the database (id). This is because this field is going to act as an index field. No two records in the database will have the same ID. Because of this, when we set up the database we set ID to ‘Auto Increment’. This means that if you assign it no value it will take the next number in the series. This means that this first record will have the ID 1.

SynapseIndia Php Development – File Write

Now that you know how to open and close a file, lets get on to the most useful part of file manipulation, writing! There is really only one main function that is used to write and it’s logically called fwrite.

php – file open: write

Before we can write information to our test file we have to use the functionfopen to open the file for writing.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');

php – file write: fwrite function

We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite’s first parameter is the file handle and its second parameter is the string of data that is to be written. Just give the function those two bits of information and you’re good to go!

Below we are writing a couple of names into our test file testFile.txt and separating them with a carriaged return.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);

The $fh variable contains the file handle for testFile.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.

We wrote to the file testFile.txt twice. Each time we wrote to the file we sent the string $stringData that first contained Bobby Bopper and second containedTracy Tanner. After we finished writing we closed the file using the fclose function.

If you were to open the testFile.txt file in NOTEPAD it would look like this:

Contents of the testFile.txt File:

Bobby Bopper
Tracy Tanner

php – file write: overwriting

Now that testFile.txt contains some data we can demonstrate what happens when you open an existing file for writing. All the data contained in the file is wiped clean and you start with an empty file. In this example we open our existing filetestFile.txt and write some new data into it.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Floppy Jalopy\n";
fwrite($fh, $stringData);
$stringData = "Pointy Pinto\n";
fwrite($fh, $stringData);
fclose($fh);

If you now open the testFile.txt file you will see that Bobby and Tracy have both vanished, as we expected, and only the data we just wrote is present.

Contents of the testFile.txt File:

Floppy Jalopy
Pointy Pinto

In the next lesson we will show you how to get information out of a file by using PHP’s read data function

SynapseIndia Php Development – ile close

The next logical step after you have opened a file and finished your business with it is to close that file down. You don’t want an open file running around on your server taking up resources and causing mischief!

php – file close description

In PHP it is not system critical to close all your files after using them because the server will close all files after the PHP code finishes execution. However the programmer is still free to make mistakes (i.e. editing a file that you accidentally forgot to close). You should close all files after you have finished with them because it’s a good programming practice and because we told you to!

php – file close function

In a previous tutorial, we had a call to the function fclose to close down a file after we were done with it. Here we will repeat that example and discuss the importance of closing a file.

PHP Code:

$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

The function fclose requires the file handle that we want to close down. In our example we set our variable “$fileHandle” equal to the file handle returned by thefopen function.

After a file has been closed down with fclose it is impossible to read, write or append to that file unless it is once more opened up with the fopen function.

SynapseIndia Pass Values Across Multiple Forms Using PHP Development

HTML forms — what would the web be without them? After you complete and submit a form, the input is usually sent to some script that processes it. The script may send the input via e-mail or insert it into a database.

Creating this type of functionality is usually a snap. First, you create an HTML form with whatever fields you want the user to fill out. Then you create a script that does something with the user input it receives from the form. The final step is to make the form’s ACTION attribute point to the script, like this:

<form action="process_form.php3">

That’s it. User input is collected via the form and processed by the script. Piece of cake, right?

But what if the user has to complete more than one form?

The tricky part is transferring the user’s input from one form to the next until it reaches the script. We must somehow store the user’s input from previous forms as fields in the current form the user is on. That way all the answers will be carried over when the user submits the form. To help accomplish this task, we’ll use hidden input fields. If you’ve played around with forms before you’re probably already familiar with them. They look like this:

<input type="hidden" value="somevalue" name="somename">

The hidden input fields will store the names and values of form elements from previous forms in the current form the user is on.

We’ll also use a little PHP, which will generate the hidden input fields for us on-the-fly.

Using the POST Method, hidden input fields, and PHP, we can easily carry user input across multiple forms. It just takes a few lines of code. Here’s the actual script:

<?php

while (list($name, $value) = each($HTTP_POST_VARS))
  {
   echo "<input type=\"hidden\" value=\"$value\" name=\"$name\">\n"; 
  }

?>

Here’s what we find when we break it down:


while (list($name, $value) = each($HTTP_POST_VARS))

The code above is a loop that accesses the elements stored in $HTTP_POST_VARS.

  {
   echo "<input type=\"hidden\" value=\"$value\" name=\"$name\">\n"; 
  }

All we’re doing here is getting the name and value of an element and using them to construct a hidden input field. This segment of code serves as a template for generating the hidden input fields.

To sum it up, the script will loop through each element stored in $HTTP_POST_VARS and generate a hidden input field for it.

Just make sure you do the following:

1. Copy and paste the script somewhere between the

<form></form>

tags in whatever form(s) you want.

2. Use POST in the form’s METHOD attribute. If you don’t specify anything, it will use GET and the script won’t work.

The following is the uncut version of the script, with comments and all. Feel free to modify the script to suit your needs.

<?php

/* ---------------------
    Declare Variable(s) 
   --------------------- */

$name; 	// Represents the name of the elements in $HTTP_POST_VARS
$value;	// Represents the value of the elements in $HTTP_POST_VARS


// ---------------------

// Do while there is an element in $HTTP_POST_VARS... 

while (list($name, $value) = each($HTTP_POST_VARS))

  /* ...get the name and value of the element and use it to construct a hidden input field.  
      Then go back to the beginning of the loop and do the same thing with the next element. */

  {
   echo "<input type=\"hidden\" value=\"$value\" name=\"$name\">\n"; 
  }

?>

Until next time, happy coding!

SynapseIndia Persistent Session (Server-Side Cookie) with PHP Development

Hello !!

If somoene wonder what is a persistent session or server-side cookie, then I will give you an introduction :

“Persistent Session is a session that is stored on your server, but the data will persist even when user disconect from your web server until the expired date comes”

This persistent session, some people called with “Server-Side Cookie” because how it works is really like cookie but it is stored in server side.

To simulate persistent session, we still need cookie (just like original Session technology does). This cookie is not to store the data itself, but to store the SESSION ID which will be different among every users.

We also need a temporary directory in server to store the Session data with read/write permission (in UNIX/Linux, you can use chmod 777 to change the permission).

Ok, first you have to define the temp directory, for example : /temp/

Then, we can make persistent session management module :


file    : mod_PSession.php
purpose : module of Persistent Session
**************************************
<?
// your temp directory :
$SESSION_DIR = "/temp/";

// The expired date.
$expired_date = 30*3;  // 30 days times 3 (3 months)

srand((double)microtime()*1000000);
$SES_VAR = array();

function generate_SID()
 {
 return md5(rand(0,32000) . $REMOTE_ADDR . rand(0,32000));
 }

function sess_start()
 {
 global $MYSID, $CKDOMAIN, $SES_VAR, $SESSION_DIR;
 if (!$MYSID) 
    $MYSID = generate_SID();

 setcookie("MYSID",$MYSID,time()+365*24*3600,"/");

 if (file_exists($SESSION_DIR.$MYSID))
    {
    $arr = file($SESSION_DIR.$MYSID);

    // if session is expired, then skip ...
    if ( time() > $arr[0] )
         {
         unlink($SESSION_DIR.$MYSID); 
         return;
         }

    // read content of session from file system ... 
    for ($i=1;$i<count($arr);$i++)
        {
        $arr2=explode(":",$arr[$i]);
        $arr2[1]=base64_decode($arr2[1]);
        $SES_VAR[$arr2[0]]=1;
        GLOBAL ${$arr2[0]};
        ${$arr2[0]} = $arr2[1];
        }
    }
 }

function sess_register($name)
 {
 global $SES_VAR;
 $SES_VAR[$name]=1;
 }

function sess_close()
 {
 global $MYSID, $CKDOMAIN, $SES_VAR, 
        $SESSION_DIR, $expired_date;

 reset($SES_VAR);
 $fp = fopen($SESSION_DIR.$MYSID,"w");
 fputs($fp,(time() + $expired_date * 24 * 3600)."\n");
 while (list($key,$val)=each($SES_VAR))
       {
       GLOBAL ${$key}; 
       $val = ${$key};
       fputs($fp,$key.":".base64_encode($val)."\n");
       }
 fclose($fp);
 }
?>

Now, let’s try how to implement the module :


file : index.php
****************
<?
include("mod_PSession.php");

// sess_start must be called on the beginning of your code !!
sess_start();

// register variables you want to store in persistent session :
sess_register("myname");
sess_register("myage");
sess_register("mygender");

// now, put the values ...
$myname   = "Alexander";
$myage    = "22";
$mygender = "Male of course !!";

print "
<HTML>
<BODY>
Session is saved ! 
<A HREF='next.php'>Go to next page</A>
</BODY>
</HTML>
";

// sess_close must be called after all is done
sess_close();
?>

In sequence :
1. You must include file mod_PSession.php.
2. You must call sess_start() to start the session support.
3. You must call sess_register() to register any variables that you want the session to remember.
4. You must call sess_close() if you want to save the session to file system. Usually, this is called in the last part of your code.

To see if the persistent session works, create the “next page” :


file : next.php
***************
<?
include("mod_PSession.php");
// must be started !!
sess_start();

print "<HTML><BODY>";
print "Hello !! My name is $myname, 
\n";
print "I am $myage years old, and I am $mygender 
\n";

print "<A HREF='next.php'>Go to last page</A>"
print "</BODY></HTML>";

// I increase my age ... :P
// Each time you refresh the page, my age will be added
$myage++;
sess_close();
?>

SynapseIndia LDAP, Apache, and PHP Development Installation

Here's how I finally got LDAP to install with PHP and Apache, but I haven't tested how well it works yet:

# installing OpenLDAP
gzip -cd openldap-stable-20010524.tgz | tar -xvf -
cd openldap-2.0.11
./configure --prefix=/usr/local/ldap
make depend
make install


# install apache
gzip -cd apache_1.3.19.tar.gz | tar -xvf -
cd apache_1.3.19
./configure --prefix=/usr/local/apache
make
# STOP HERE TO DO THE PHP INSTALLATION


# install PHP
cd ..
gzip -cd php-4.0.4pl1.tar.gz | tar -xvf -
cd php-4.0.4pl1
./configure --with-mysql=/usr/local/mysql --with-apache=/usr/local/download/apache_1.3.19 --with-snmp --enable-track-vars --with-ldap=/usr/local/ldap/bin
gmake
gmake install
cp php.ini-dist /usr/local/lib/php.ini

# Continue with Apache installation
cd ..
./configure --prefix=/usr/local/apache --activate-module=src/modules/php4/libphp4.a
#in /usr/local/download/apache_1.3.19/src
	#You need to change these these lines to show this:
	EXTRA_LDFLAGS=-lldap -llber
	EXTRA_LIBS=-L/usr/local/lib -R/usr/local/lib
make
make install
#Add to the startup
	cp /usr/local/apache/bin/apachectl /etc/init.d
	ln /etc/init.d/apachectl /etc/rc3.d/S99apache
	ln /etc/init.d/apachectl /etc/rc2.d/K99apache
#The Web Server user will be "nobody"

#in /usr/local/apache/conf/httpd.conf set "UseCanonicalNames" #directive to "Off"
#	and uncomment "AddType application/x-httpd-php .php"