Monday, April 19, 2010

Workshop 4 : MANIPULATING FILES and DIRECTORIES

Files




1. Testing files, lets test for some existence and status of a file called text1.txt



<?php



// Checking its existence

if (file_exists("text1.txt")) {

echo "The file text1.txt exists!";

}



// checking the status of files

if (is_readable("text1.txt")) {

echo "The file text1.txt is readable";

}



if (is_writeable("text1.txt")) {

echo "The file text1.txt is writeable";

}



if (is_executable("text1.txt")) {

echo "The file text1.txt is exectuable";

}

?>



You probably only see "The file text1.txt exists". If you only see this, you will need to chmod the read,write and execute settings on that file.



2. Reading data from files



<?php



$filename = "text1.txt";

$fp = fopen($filename, "r") or die ("Could not open $filename");

while (!feof($fp)) { // While not end of file

$data = fread($fp, 16); // Reading the file in chunkcs of 16 bytes

echo "$data <br>";

}

?>



There are multiple ways you can read from a file includes

Fgets() : Reading line by line

Fgetc() : Reading a character







3. Writing to a file



<?php



$filename = "text1.txt";

echo "Begin writing to file $filename <br>";

$fp = fopen($filename, "w") or die ("Could not open $filename"); // OPen for writing

fwrite ($fp, "I'm making changes \n");

fclose($fp);

?>



If you have trouble writing to the file, it could be a permission setting. Try chmod 777 <filename>. This will give all permissions to the file only. Chmod 777 to the directory give all permissions to the directory and not advisable.



4. Appending to a file



<?php



$filename = "text1.txt";

echo "Appending to a file $filename <br>";

$fp = fopen($filename, "a") or die ("Could not open $filename"); // OPen for writing

fputs ($fp, "\n Another thing I want to add \n");

fclose($fp);

?>



The file text1.txt will have a new line called Another thing I want to add.





Directories



1. Creating a new directory



<?php



mkdir ("testdir", 0755);

?>



If you failed to create a directory, again it usually means you have incorrect permissions settings.





2. Directory listing



<?php



$dirname = ".";

$dn = opendir($dirname) or die ("Could not open directory");



while (!(($file = readdir($dn)) === false ) ) {

if (is_dir("$dirname/$file")) {

echo "(D) "; // To signify a folder

}

echo "$file <br>";

}

closedir ($dn);

?>

Workshop 3 : STRINGS, DATES, FORMS and SESSIONS

Working with Strings




1. Up to now, we've only been working on the echo statement. The printf() statement does the same thing except it can accept arguments passed onto the function.



<?php



// This outputs the integer as a decimal number instead of part of a string

printf("This is my number : "%d", 60) ;



?>





2. You can also specify the start position of your string displayed



<?php



echo "<pre">;

// This will leave 15 spaces before printing

printf ("%15s\n", " Name");

printf ("%15s\n", " Address");

printf ("%15s\n", " Mobile Number");

printf ("%15s\n", " Email");

echo "<pre">;

?>



3. You can look up more string functions on www.php.net

• strlen() , to determine the length of a string

• strstr (), to determine the existence of a string within a string

• strpos(), to find the position of a substring





Working with Time and Date



1. PHP stores time as number of seconds that have elapsed since GMT midnight 1 January 1970. This is the time stamp



<?php



// This is the timestamp, It is the number of seconds since Unix Epoch (Midnight GMT 1 Jan 1970)



echo "The number of seconds that have passed since Midninght GMT 1 January 1970 is ";

echo time();

echo "<br>";



?>



2. With the timestamp you can convert it to date using getdate(). This is a an array that stores the vales of date.



<?php

$date_array = getdate(); // no argument passed so today's date will be used

foreach ($date_array as $key => $val) {

echo "$key = $val<br>";

}

?>

<hr>

<?

echo "Today's date: ".$date_array['mday']."/".$date_array['mon']."/".

$date_array['year']."<p>";

?>



Creating Forms



1. Use the following files for testing.

1.1 Listing 9.1.html

<html>

<head>

<title>Listing 9.1 A simple HTML form</title>

</head>

<body>

<form action="listing9.2.php" method="POST">

<p><strong>Name:</strong><br>

<input type="text" name="user">

<p><strong>Address:</strong><br>

<textarea name="address" rows="5" cols="40"></textarea>

<P><input type="submit" value="send"></p>

</form>

</body>

</html>



1.2 Listing 9.2.php

<html>

<head>

<title>Listing 9.2 Reading input from a form </title>

</head>

<body>

<?php

echo "<p>Welcome <b>$_POST[user]</b></p>";

echo "<p>Your address is:<br><b>$_POST[address]</b></p>";

?>

</body>

</html>



There are two input boxes available from listing9.2.html called text and address. When the user submits the form it will invoke the script called listing9.2.php. The $_POST command will grab the value values corresponding to the text boxes value in listing9.1.html.





2. Getting data from a multi valued text box

2.1 Listing9.3.html

<html>

<head>

<title>Listing 9.3 An HTML form including a SELECT element</title>

</head>

<body>

<form action="listing9.4.php" method="POST">

<p><strong>Name:</strong><br>

<input type="text" name="user">



<p><strong>Address:</strong><br>

<textarea name="address" rows="5" cols="40"></textarea>



<p><strong>Select Some Products:</strong> <br>

<select name="products[]" multiple>

<option value="Sonic Screwdriver">Sonic Screwdriver</option>

<option value="Tricoder">Tricorder</option>

<option value="ORAC AI">ORAC AI</option>

<option value="HAL 2000">HAL 2000</option>

</select>



<p><input type="submit" value="send"></p>

</form>

</body>

</html>



2.2 Listing9.4.php

<html>

<head>

<title>Listing 9.4 Reading input from the form in Listing 9.3</title>

</head>

<body>

<?php

echo "<p>Welcome <b>$_POST[user]</b></p>";

echo "<p>Your address is:<br><b>$_POST[address]</b></p>";

echo "<p>Your product choices are:<br>";

if (!empty($_POST[products])) {

echo "<ul>";

foreach ($_POST[products] as $value) {

echo "<li>$value";

}

echo "</ul>";

}

?>

</body>

</html>



3. Sending out emails



3.1 Listing9.10.html

3.2 Listing.9.11.php

Sessions



Sessions are unique identifier of a user, which can be used to store and retrieve information attached to the user. Therefore enabling the website to know what the user have seen, browse through etc. The user would need to have cookies enabled for session to work.



1. Initializing a session



<?php

session_start();



echo "<p>Your session ID is ".session_id()."</p>";

?>



Your session id stays the same all the time.



2. Storing and accessing session variables

We'll store the variables first in a separate file



<?php

session_start();



$_SESSION[product1] = "Sonic Screwdriver";

$_SESSION[product2] = "HAL 2000";

echo "The products have been registered.";



?>





Once you have executed this script, run the next script. The above script will attached the data onto session variables.



<?php

session_start();



echo "Your chosen products are:";

echo "<ul><li>$_SESSION[product1] <li>$_SESSION[product2]\n</ul>\n";

?>





3. Destroying sessions and variables. Once executed it would remove the session and the corresponding variables



<?php

session_start();

session_destroy();

unset($session[product1]); // Remove product 1

unset($session[product2]); // Remove product 2



// This should print nothing

echo "Your chosen products are:";

echo "<ul><li>$_SESSION[product1] <li>$_SESSION[product2]\n</ul>\n";

?>

Workshops 2 : Beginning PHP Coding

1. All PHP files have an extension of .php

2. All PHP will start with the following code


<?php


code

?>


3. In order to comment a code, it begins with two forward slashes // or a # sign. PHP engine usually ignores these lines. Comments can be used to annotate codes to make them more readable




# This starts the comments

// This also starts the comments



Multi lines comment is also possible. It stars /* and ends with */.



/*

This is the start of the comment.

Anything within this lines will not

Be interpreted by the PHP engine

*/





4. Every line in PHP needs a terminator. The terminator is a semicolon ;



<?php

echo "This is my first PHP program " ;

?>





Variables



1. In PHP variables starts with $ sign followed by the name.



$variable1



<?php

// Adding two numbers together



// Assigning the variable with the value 88

$num1 = 88;

$num2 = 100;



echo "The first number is", $num1;

echo " The second number is ", $num2 ;



// Adding the two numbers

echo " The total is ", $num1 + $num2;

?>



For the list of logical and mathematical operators, please refer to the prescribed text.



Data Types



The six standard data types in PHP are



• Integer - Whole number, 10

• Double - Floating point number , 9.999

• String - AlphaNumeric characters, " This is PHP "

• Boolean - True/False values, TRUE

• Object - Instance of class

• Array - An ordered set of keys and values



Testing the variable types



<html>

<head>

<title>Listing 4.1 Testing the type of a variable</title>

</head>

<body>

<?php

$testing; // declare without assigning

print gettype($testing); // null

print "<br>";

$testing = 5;

print gettype($testing); // integer

print "<br>";

$testing = "five";

print gettype($testing); // string

print("<br>");

$testing = 5.0;

print gettype($testing); // double

print("<br>");

$testing = true;

print gettype($testing); // boolean

print "<br>";

?>

</body>

</html>



FLOW CONTROL





1. If Statements

<?php



$subject = "ITC382" ;

If ($subject == "ITC382") {

Echo " I am in ITC382 class";

}

?>





2. If .. else statements



<?php



$subject = "ITC254" ;

If ($subject == "ITC382") {

Echo " I am in ITC382 class";}

Else {echo " I am in the wrong class";) }

?>



3. If..elseif ..else statements



<?php



$subject = "ITC254" ;

If ($subject == "ITC382") {

Echo " I am in ITC382 class";}

Else if ($subject == "ITC254") {

echo "I am in ITC254 class ";}

else { echo " I'm not too sure which class I should be in. Maybe I should be in $subject"; }

?>





4. Switch statements

Switch is commonly used to execute different codes based on each expression used.



<?php



$subject = "ITC382";



switch ($subject) {



case "ITC254":

echo "I am in ITC254 class";

break;

case "ITC382":

echo "I am in ITC382 class";

break;

default:

print "I must have gotten lost again, I am suppose to be in $subject";

break;

}

?>





5. While statements

A continuos loop until a condition is reached.



<?php



$count = 1;



while ($count < 10) {

echo " This is line $count", "<br>";

$count++; // Increment count by 1

}

?>



6. Do..While statements

It is similar to the Do statement except that termination is at the end of the code.



<?php



$count = 0;



do {

echo " This is line $count", "<br>";

$count++; // Increment count by 1

} while ($count < 10);

?>



7. For statements

For statements are also similar to while statements, it is a more structured way to write looping statements with the initialization, testing and modification expression nested within the command.



<?php

for ($count =1; $count <10; $count++) {

echo "This is line $count", "<br>";

}

?>





FUNCTIONS



Functions are blocks of code that you can call from the main program.



<?php



function print2lines() {

echo "This is line 1", "<br>";

echo "This is line 2", "<br>";

}

print2lines();

?>





You can also pass arguments into a function



<?php



function printlines($txt) {

echo " $txt <br>";

}

printlines("This is line 1");

printlines("This is line 2");

printlines("This is line 3");

?>



You can also get the function to return an argument



<?php



function addnums ($num1, $num2) {

$result = $num1 + $num2;

return $result;

}

echo addnums(5,9);

// print 14



?>



Variables declared in a function remains only in the function. You can however use global variables should you wish to use variables within a function.



<?php



$value = 100;



function currentmoney() {

global $value;

echo " I currently have RM $value <br>";

}

currentmoney();

?>



ARRAYS



Creating arrays



In order to create an array, you would need to you the array function:



$lecturers = array("Yann", "Sam", "Ven Yu", "Tony", "Anitha");



You can also do this as well



$lecturers[] = "Yann" ;

$lecturers[] = "Sam";

$lecturers[] = "Ven Yu";

$lecturers[] = "Tony";

$lecturers[] = "Anitha";



Both will create an array called lecturers with 5 elements. By default the first element starts at position 0.



<?php

$lecturers = array("Yann", "Sam", "Ven Yu", "Tony", "Anitha");

echo $lecturers(1) ; // This will print Sams name

?>



Associative Arrays



Instead of using numbers, you can also use named keys to number the arrays instead as illustrated in the following example.



$lecturers = array (

"name" => "Yann",

"dept" => "VIGIM",

"subjects" => "ITC382"

);



If you write



Echo $lecturers['dept']; // this will return VIGIM



You can also make additions to an already existing associative array.



$lecturers['interests'] = "Video Games";





Multidimensional Arrays



This holds arrays of an array.



<?php



$lecturers = array (

array (

"name" => "Yann",

"dept" => "VIGIM",

"subjects" => "ITC382"

),

array (

"name" => "Sam",

"dept" => "VIGIM",

"subjects" => "ITC211"

),

array (

"name" => "Tony",

"dept" => "MT",

"subjects" => "ITC123"

),

);



echo $character[1]['subjects']; // this will print out ITC211



?>



OBJECTS



An object is typically a sort of container that consists of

• variables

• functions

• etc

It is similar to a class ohject in JAVA



<?php



class lecturers {

var $name = "Yann";

var $subjectcode = "ITC382" ;

var $subjectname = "Client Server Applications";

}



$mylecturer = new lecturers();

echo "My name is ".$mylecturer -> name. " and I teach " .$mylecturer -> subjectcode." " .$mylecturer -> subjectname;



?>



You can also change the properties of an object in the code as illustrated.



<?php



class lecturers {

var $name = "Yann";

var $subjectcode = "ITC382" ;

var $subjectname = "Client Server Applications";

}



$mylecturer = new lecturers();

echo "My name is ".$mylecturer -> name. " and I teach " .$mylecturer -> subjectcode." " .$mylecturer -> subjectname;





// changing the object properties

echo "<br> This is to relfect the changes in object properties <br>";

$mylecturer -> name = "Sam";

$mylecturer -> subjectcode = "ITC211";

$mylecturer -> subjectname = "Multimedia Systems";



echo "My name is ".$mylecturer -> name. " and I teach " .$mylecturer -> subjectcode." " .$mylecturer -> subjectname;



?>



You can also add methods into your class objects as illustrated.



<?php



class displayname {

function name() {

echo "My name is Yann " ;

}

}



$name = new displayname();

$name -> name();

?>

Workshops 1 : PHP

Writing PHP scripts

1. You can download many PHP editors that is freely available online. I recommend PHP Designer which can be downloaded from www.download.com

2. If you prefer you can also write using notepad and naming the file with *.php

3. Lets start using notepad to write a simple PHP script to test the following tasks.

4. Click on Start >> Programs >> Accessories >> Notepad

5. Write the following code


<?php


echo "Hello World";

?>


6. Save the file with the name helloworld.php. Remember to save it as helloworld.php since by default Notepad can save it as helloworld.php.txt.

Access to PHP

In order to get access to PHP server, you will need to run telnet from the labs. The IP address to telnet to is 10.1.1.200 or 192.168.68.42. You will need to upload your files from this telnet access.

A. Configuring your Linux account


1. From Start-Run, type telnet 10.1.1.200. Click OK button.

2. At the prompt, enter your Student ID (e.g aXXXXXXX or bXXXXXXX - case sensitive) as login name and welcome for password.

YOUR ID starts with lowercase.

3. Type passwd to set the password for your account. (Recommended so that you can have a unique password)

4. Type cd ..

5. Type ls -l, you will see a list of directories, ensure that you have your own directory based on your student id

6. Type chmod 755 this will set permissions for your directory to enable read access.

7. Type mkdir public_html to create a new directory (folder) called public_html.

8. Type chmod 755 public_html (Set permissions for the user, the group, and the others to access public_html directory )


B. Uploading files to the Linux account

1. From Start-Run, type ftp 10.1.1.200. Click OK button. Enter your login name(student ID) and password.

2. Type cd public_html. (Change to public_html directory)

3. Type put path\(source file name) (destination file name).

E.g. put a:\tutorial1.html tutorial1.html.

(You can upload any the HTML files)

4. Omit destination file name if you want to use the same file name. E.g. put a:\tutorial1.html

5. Type bye to quit ftp.

6. Alternatively if you find it troublesome to use telnet, you can also use Netscape to FTP to your site

7. Simply start Internet Explorer with the following address,

ftp://:@10.1.1.200

8. Drag the files you wish to upload onto the FTP window.


C. Using Web Browser to view HTML files in the Linux account

1. Launch Netscape/IE

2. In the location bar, type 10.1.1.200/~(your student ID)/(destination HTML file name).

E.g. 10.1.1.200/~a1234567/helloworld.php

3. You should be able to view your HTML file.

Access to MYSQL

1. You will need to start a telnet session before logging onto MYSQL>

2. Type the following command mysql -u -p, therefore the command line would look something like this mysql -u lohky -p