HAL-PC Scheduled Classes TWiki > Classes > IntroPHP4 ( vs. r1.1) TWiki webs:
AIX| Classes | HALBOD | HLUG | Helpdesk | Library | Main | Samba | TWiki |
Classes . { TWikiGuest | Index | Changes | Search | Go }
 <<O>>  Difference Topic IntroPHP4 (r1.1 - 17 Sep 2004 - RickArchibald)
Added:
>
>
%META:TOPICINFO{author="RickArchibald" date="1095393871" format="1.0" version="1.1"}% %META:TOPICPARENT{name="IntroPHP3"}% Houston Area League of PC Users Education System <BODY BGCOLOR="#e2e3ed" TEXT="#07070a" LINK="#777bb4" ALINK="#777bb4" VLINK="#777bb4">
php logoPHP stands for PHP: Hypertext Preprocessor.
http://www.php.net
We know our records don't show anything yet.

Lets create a text file to contain our data called: names.txt

Inside names.txt let's put one line: 1.Pidaclaburger Jones

Please put names.txt on the web server.

We must set the permissions on names.txt in order for this example to work:

ftp> site chmod 666 names.txt
200 CHMOD command successful.

Next we will want to see if we can read the contents of that file.

Let's insert the following lines in our code to read and display the contents of the file:

//file -- Reads entire file into an array

$newsplit2 = file("names.txt");

// count -- Count elements in a variable (typically an array)

$total = count($newsplit2);

if ($total>0)
{
for($y=0; $y < $total; $y++)
{
echo "<br>".$newsplit2[$y]."<br>";<br> }
}

Your code should now look like this:
<?php

// Initialize variables to a known value:

$name_entered="";
$name3="";
$newsplit="";
$to_do=0;

/*
use the predefined PHP variables $HTTP_POST_VARS to acquire the data that the client entered into their browser:
*/

$name_entered=$HTTP_POST_VARS["name2"];
$name3=$HTTP_POST_VARS["name2"];

// Standard HTML tags are needed for the form:
?>

<html>
<body>

<?php

// Check to see if we got any data:

if($name3!="")
{

/*
Use the PHP predefined function trim() to Strip whitespace from the beginning and end of $name3:
*/

$name3=trim($name3);

// Use the PHP predefined function strtolower() to make $name3 all lowercase:

$name3=strtolower($name3);

/*
Use the PHP predefined function explode() to split $name3 where there are spaces and return each peice of $name3 in an element of an array named $newsplit:
*/

$newsplit = explode(" ", $name3);

/*
$name3 is now stored as elements in the array we named $newsplit. We can set $name3 to our know value, a blank string:
*/

$name3="";

/*
Use the PHP predefined function count to get the number of elements in $newsplit.
Use the addition operator (+) to increase the count by 1.
Assign that number to a new variable called $to_do:
*/

$to_do=count($newsplit)+1;

/*
Use a PHP control structure called a for loop to get each element of our array, $newsplit.

The first expression ($y=0) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 ($y < $to_do) is evaluated.

If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 ($y++) is evaluated (executed).

We use the Post-increment Operator $y++. The Post-increment Operator returns $y, then increments $y by one:
*/

for($y=0; $y < $to_do; $y++)
{

/*
Use the PHP predefined function ucfirst() to make the first character of our array element $newsplit[$y] uppercase:
*/

$newsplit[$y]=ucfirst($newsplit[$y]);

/*
Get whatever has been stored in $name3

Use the string concatenation operator (.) to add a blank space and then the contents of $newsplit[$y].

Use the assignment operator (=) to assign this new value to $name3.

Note: on the first time through the loop we add a blank space to the beginning of $newsplit[0]:
*/

$name3=$name3." ".$newsplit[$y];

/*
This is the end of our for loop. If $y is still less than $to_do we will increment $y and repeat the loop:
*/
}

/*
Use the PHP predefined function trim() to strip whitespace from the beginning of $name3:
*/

$name3=trim($name3);

/*
Use the PHP predefined function ereg_replace to replace most special characters with nothing:
*/

$name3 = ereg_replace('[^._ 0-9a-zA-Z]', '', $name3);

/*
Use the PHP language construct echo() to display the literal string "<br>You entered: " and (.) the value of $name_entered and (.) "<br><br>":
*/

echo "<br>You entered: ".$name_entered."<br><br>";

// Use the PHP assignment operator to reset the variable $name_entered to our known value "":

$name_entered="";

/*
Use the PHP language construct echo() to display the literal string "<br>Our records show your name is: " and (.) the value of $name3 and (.) "<br><br>":
*/

echo "<br>Our records show your name is: ".$name3."<br><br>";

/*
This is the ending of our if statement (if($name3!="")).

Nothing inside these curly brackets will execute if $name3 was equal to "" ($name3=="").

We would execute the else part of the statement instead:
*/

} else {

echo "<br>Please enter your name.<br><br>";

// This is the end of the else part of our if statement:

}

// HTML form to get the data follows:
?>
<form name=see_name action=name.php method=post>
Name:
<input type="text" name="name2">
</form>

<?php

//file -- Reads entire file into an array

$newsplit2 = file("names.txt");

// count -- Count elements in a variable (typically an array)

$total = count($newsplit2);

if ($total>0)
{
echo "<br>Our Records:<br>";

for($y=0; $y < $total; $y++)
{
echo "<br>".$newsplit2[$y]."<br>";
}
}
?>

</body>
</html>


What if we wanted to automatically add the new name to our text file, names.txt?

We could use PHP's predefined function fopen to open the file

We will also want to set the mode to (w) so that we can write to the file.

Then we could insert the contents of our array, newsplit, and the new name we just acquired into the file

Let's add the following lines of code and some comments:

/*
Use the PHP function file to read the file names.txt into an array:
*/

$newsplit3 = file("names.txt");

/*
Use the PHP predefined function count to get the number of elements in $newsplit3 and assign that value to a new variable called $total.
*/

$total = count($newsplit3);

/*
Use the PHP addition operator (+) to increase $total by 1 and assign that value to a new variable called $idnumber.
*/

$idnumber=$total+1;

/*
Use the PHP assignment operator (=) to append a new element to our array, $newsplit3 and assign it the value of $idnumber . ":" . $name3 . "\n":
*/

$newsplit3[$total] = $idnumber . ":" . $name3 . "\n";

/*
fopen() binds a named resource (names.txt), specified by filename, to a stream.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file.

The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access.
*/

$fp = fopen("names.txt","w");

/*
The while statement tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration:
*/

while($i2 <= $idnumber){

/*
fwrite() writes the contents of string to the file stream pointed to by handle ($fp):
*/

fwrite($fp,$newsplit3[$i2]);

// increment $i2 by 1

$i2++;

// Close the while loop:

}

// Close the stream to the text file:

fclose($fp);

Our script should now look like this:

<?php

// Initialize variables to a known value:

$name_entered="";
$name3="";
$newsplit="";
$to_do=0;
$newsplit2="";
$newsplit3="";
$total=0;
$idnumber=0;
$i2=0;

/*
use the predefined PHP variables $HTTP_POST_VARS to acquire the data that the client entered into their browser:
*/

$name_entered=$HTTP_POST_VARS["name2"];
$name3=$HTTP_POST_VARS["name2"];

// Standard HTML tags are needed for the form:
?>

<html>
<body>

<?php

// Check to see if we got any data:

if($name3!="")
{

/*
Use the PHP predefined function trim() to Strip whitespace from the beginning and end of $name3:
*/

$name3=trim($name3);

// Use the PHP predefined function strtolower() to make $name3 all lowercase:

$name3=strtolower($name3);

/*
Use the PHP predefined function explode() to split $name3 where there are spaces and return each peice of $name3 in an element of an array named $newsplit:
*/

$newsplit = explode(" ", $name3);

/*
$name3 is now stored as elements in the array we named $newsplit. We can set $name3 to our know value, a blank string:
*/

$name3="";

/*
Use the PHP predefined function count to get the number of elements in $newsplit.
Use the addition operator (+) to increase the count by 1.
Assign that number to a new variable called $to_do:
*/

$to_do=count($newsplit)+1;

/*
Use a PHP control structure called a for loop to get each element of our array, $newsplit.

The first expression ($y=0) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 ($y < $to_do) is evaluated.

If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 ($y++) is evaluated (executed).

We use the Post-increment Operator $y++. The Post-increment Operator returns $y, then increments $y by one:
*/

for($y=0; $y < $to_do; $y++)
{

/*
Use the PHP predefined function ucfirst() to make the first character of our array element $newsplit[$y] uppercase:
*/

$newsplit[$y]=ucfirst($newsplit[$y]);

/*
Get whatever has been stored in $name3

Use the string concatenation operator (.) to add a blank space and then the contents of $newsplit[$y].

Use the assignment operator (=) to assign this new value to $name3.

Note: on the first time through the loop we add a blank space to the beginning of $newsplit[0]:
*/

$name3=$name3." ".$newsplit[$y];

/*
This is the end of our for loop. If $y is still less than $to_do we will increment $y and repeat the loop:
*/
}

/*
Use the PHP predefined function trim() to strip whitespace from the beginning of $name3:
*/

$name3=trim($name3);

/*
Use the PHP predefined function ereg_replace to replace most special characters with nothing:
*/

$name3 = ereg_replace('[^._ 0-9a-zA-Z]', '', $name3);

/*
Use the PHP language construct echo() to display the literal string "<br>You entered: " and (.) the value of $name_entered and (.) "<br><br>":
*/

echo "<br>You entered: ".$name_entered."<br><br>";

// Use the PHP assignment operator to reset the variable $name_entered to our known value "":

$name_entered="";

/*
Use the PHP language construct echo() to display the literal string "<br>Our records show your name is: " and (.) the value of $name3 and (.) "<br><br>":
*/

echo "<br>Our records show your name is: ".$name3."<br><br>";


/*
Use the PHP function file to read the file names.txt into an array:
*/

$newsplit3 = file("names.txt");

/*
Use the PHP predefined function count to get the number of elements in $newsplit3 and assign that value to a new variable called $total.
*/

$total = count($newsplit3);

/*
Use the PHP addition operator (+) to increase $total by 1 and assign that value to a new variable called $idnumber.
*/

$idnumber=$total+1;

/*
Use the PHP assignment operator (=) to append a new element to our array, $newsplit3 and assign it the value of $idnumber . ":" . $name3 . "\n":
*/

$newsplit3[$total] = $idnumber . ":" . $name3 . "\n";

/*
fopen() binds a named resource (names.txt), specified by filename, to a stream.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file.

The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access.
*/

$fp = fopen("names.txt","w");

/*
The while statement tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration:
*/

while($i2 <= $idnumber){

/*
fwrite() writes the contents of string to the file stream pointed to by handle ($fp):
*/

fwrite($fp,$newsplit3[$i2]);

// increment $i2 by 1

$i2++;

// Close the while loop:

}

// Close the stream to the text file:

fclose($fp);


/*
This is the ending of our if statement (if($name3!="")).

Nothing inside these curly brackets will execute if $name was equal to "" ($name=="").

We would execute the else part of the statement instead:
*/


} else {

echo "<br>Please enter your name.<br><br>";

// This is the end of the else part of our if statement:

}

// HTML form to get the data follows:
?>

<form name=see_name action=name.php method=post>
Name:
<input type="text" name="name2">
</form>

<?php

//file -- Reads entire file into an array

$newsplit2 = file("names.txt");

// count -- Count elements in a variable (typically an array)

$total = count($newsplit2);

// check to see if there were any elements in the array

if ($total>0)
{

echo "<br>Our Records:<br>";

// If there were any elements in the array we will display them with a for loop:

for($y=0; $y < $total; $y++)
{

echo "<br>".$newsplit2[$y]."<br>";

// Close our loop:

}

// Close our if:

}
?>

</body>
</html>

Here are a couple of ideas for what to add to this script next:
1. Create another text file called authorized_users.txt and only display the list if name is in authorized users.

2. Do an additional loop to check and see if $name3 is already in names.txt before you add it. Only add it if it is not.

3. Alphabetize the records before you display them. Hint: PHP has a function called sort()

4. Get some additional information like a telephone number and an email address. Use a delimiter to seperate the fields so you can put them in an array when you get them out of the file.

5. Insert the data into a PostgreSQL? database and display the data from there
<?php

$database = "php_class";
$db_host = "jeeves";
$db_user = "php_class";
$db_user_pass = "php";
$realm = "";

$db_connect_string = sprintf("dbname=%s", $database);
if(strlen($db_user)) $db_connect_string=
sprintf("%s user=%s", $db_connect_string, $db_user);
if(strlen($db_user_pass)) $db_connect_string =
sprintf("%s password=%s", $db_connect_string, $db_user_pass);
if(strlen($db_host)) $db_connect_string=
sprintf("%s host=%s", $db_connect_string, $db_host);
$conn = pg_connect($db_connect_string) or pg_die();

echo "<br>".$db_connect_string."<br>";

$newsplit4 = file("names.txt");

$total = count($newsplit4);

if ($total>0)
{
for($y=0; $y < $total; $y++)
{
$sql="INSERT INTO phpx VALUES ('$newsplit4[$y]');" ;
pg_exec($sql);
}
}
$sql2="SELECT * FROM phpx ORDER BY name";
$RS_query = pg_exec($sql2);

if (pg_numrows($RS_query) > 0)
{
for($x=0; $x < pg_numrows($RS_query); $x++)
{
$RS_query_result = pg_fetch_row($RS_query, $x);
echo "<br>From the database: ".$RS_query_result[0]."<br>";
}
}
pg_close($conn);
?>


-- Main.RickArchibald - 17 Sep 2004

Topic IntroPHP4 . { View | Diffs | r1.1 | More }
Revision -
Revision r1.1 - 17 Sep 2004 - 04:04 GMT - RickArchibald
Copyright © 2003-2007 by F. A. Archibald III & the contributing authors