Using Functions - Please help!


#1

I have this project and so far this is what it’s suppose to do:
There are 4 pages. The first page asks the user to enter their username and password (these are finite and defined by the second page) and asks the user to choose a file they want to work with. The second page verifies the username and password are correct and echoes the information from the chosen file into a table and has two links underneath: one to take the user back to page 1, and the second to take the user to page 3. Page 3 calls in two functions from page 4 to loop through all the information in that same file using regex to make sure Student Numbers and email addresses are in the correct format. If it’s correct, it will alert the user that all the information is legitimate, or else it will write the errors to a log file. What I’m having trouble with is on page 3 and 4. The functions aren’t working because Apache says there are undefined variables, and on page 3 I can’t seem to get rid of the array to string conversion notice. This is driving me nuts. Here’s the code for all four pages:

Page 1

[code]<?php
/* File: page1.php
This file is first major assignment in the PHP level 1 course.
The purpose: “To write a php application that helps an instructor set up a website for their courses.”

Author: name
Last modified: May 04, 2007.

*/

echo ‘’;

echo ‘’;

echo ‘’;

echo ‘’;

echo ‘Comp 1920 - Assignment 1’;

echo ‘’;

echo ‘’;

echo ‘’;

echo 'Please enter your username:

';

echo 'Please enter your password:

';

$directory = “./courses/”;
$fileslist = scandir($directory);
echo “Please Select a File:
”;
echo ‘’;
foreach($fileslist as $filenames) {

	//The following code splits the string into 'filename' and 'extension'.

	list($name, $extension) = explode('.txt', $filenames);
	

	if (is_dir ($directory)){
		//I'll think of something to put here later...
	}
	else {
		die ("Directory 'courses' or required files do not exist.");
	}


	
	if (is_dir($filenames)) {
		continue;
	}

	elseif (!ereg("^.*.(txt)$", $filenames)	){
		continue;
	}
	
	
	echo "<option value="$filenames">$name</option><br />";

}

echo “

”;

echo ‘’;

echo ‘’;

echo ‘’;

echo ‘’;

?>[/code]

Page 2

[code]<?php
/* File: page2.php
This file is first major assignment in the PHP level 1 course.
The purpose: “To write a php application that helps an instructor set up a website for their courses.”

Author: name
Last modified: May 04, 2007.

*/

/* The following code determines if the username field has a value. If it doesn’t, it will kill the script.
*/

if (!($_GET[“username”])){
die (“Please enter your username.”);

}
elseif ($_GET[“username”] !=“comp1920”){
die (“Invalid username, sorry.”);
}

/* The following code determines if the password name field has a value/valid value. If it doesn’t, it will kill the script.
*/

if (!($_GET[“password”])) {
die (“Please enter a password.”);
}
elseif ($_GET[“password”] != “php”) {
die (“Invalid password, sorry.”);
}

/*
The following script determines which file was chosen and will echo out the contents in a table for the user to review. It provides links back to page1 or onto page3, depending if they decide to use the file.
*/

$resultfile = $_GET[“filename”];

if (!($_GET[“filename”])) {
die (“Please select a course file to work with.”);

} else {
$file = file("./courses/".$resultfile);
echo “You chose file: $resultfilen

n”;
foreach ($file as $newPiece) {
echo “tn”;
$newStr = trim($newPiece);
$tempArr = split(",",$newStr);
foreach ($tempArr as $tempStr) {
if (ereg("^[a-zA-Z0-9]$",$tempStr)){
$finaloutput=ucfirst($tempStr);
} elseif (ereg("^[a-zA-Z0-9_.
]@[a-z].[a-z]{2,}",$tempStr)){
$finaloutput=strtolower($tempStr);
}
echo “ttn”;
}
echo “tn”;
}
	echo "</table>n";
	echo '<br /><br />';
	echo '<a href="./page1.php">Choose another course file</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="./page3.php?filename=',urlencode($resultfile),'">Work with this course file</a>';

}

echo ‘’;

echo ‘’;

?>[/code]

Page 3

[code]<?php
/* File: page3.php
This file is first major assignment in the PHP level 1 course.
The purpose: “To write a php application that helps an instructor set up a website for their courses.”

Author: Irene Thanh
Last modified: May 04, 2007.

*/
date_default_timezone_set(“America/Vancouver”);
$fileN = $_GET[“filename”];
$resultingf = “./courses/”.$fileN;
$date_time = date(“F j, Y (h:i:s)”);

if (!($fileN)){
die (“Please specify a file.”);
} else {
$fileorg = file($resultingf);
$ContentsArr = array();
if (is_file ($resultingf)){

	foreach ($fileorg as $infos) {
		$ContentsArr[] = $infos;	
	}
	
	echo "<table border="1">n";
	echo "t<tr>n";
	$newArrs = split(",",$ContentsArr);
	//$newL = array();
	foreach($newArrs as $separated) {
		require_once("page4.php");
		
		isStudentNumberWellFormed($separated);
		isEmailAddressWellFormed($separated);
		
		if (!(ereg("^[a-zA-Z]*$",$separated))){
			//This is to pass the names.			
			}

		else {
			$newResult = $separated;
		}
		echo "tt<td>".$newResult."</tdn";
					
	}
	echo "t</tr>n";
}
	
 	else {
			die ("No such file, sorry.");
		}

}

?>[/code]

Page 4

[code]<?php
/* File: page4.php
This file is first major assignment in the PHP level 1 course.
The purpose: “To write a php application that helps an instructor set up a website for their courses.”

Author: name
Last modified: May 04, 2007.

*/

date_default_timezone_set(“America/Vancouver”);
$fileN = $_GET[“filename”];
$resultingf = “./courses/”.$fileN;
$date_time = date(“F j, Y (h:i:s)”);

function isStudentNumberWellFormed($studentnumber){

if (!(ereg("^[aA][0-9]{8}$",$studentnumber))){
			if ($filehandle = @fopen("./courses/errors.log", "a+")){
				$writetext = fwrite($filehandle, "<br />-----");
				$writetext = fwrite($filehandle, "<br />$date_time.");
				$writetext = fwrite($filehandle, "<br />Improper student number from $fileN:");
				$writetext = fwrite($filehandle, "<br />$studentnumber");
				fclose($filehandle) or die ("Error closing file <br />");
			} else {
				die("Cannot open file 'errors.log', an error has occured.");
			}
			}
else {
		$newResult = $separated;
}

}

function isEmailAddressWellFormed($emailaddress){

if (!(ereg("^[a-zA-Z0-9_.]*@[a-z]*.[a-z]{2,5}$",$emailaddress))){
			if ($filehandle = @fopen("./courses/errors.log", "a+")){
				$writetext = fwrite($filehandle, "<br />-----");
				$writetext = fwrite($filehandle, "<br />$date_time.");
				$writetext = fwrite($filehandle, "<br />Improper email address from $fileN:");
				$writetext = fwrite($filehandle, "<br />$emailaddress");
				fclose($filehandle) or die ("Error closing file <br />");
			} else {
				die("Cannot open file 'errors.log', an error has occured.");
			}
			}
else {
		$newResult = $separated;
}

}

?>[/code]

The script runs fine up until page 2 where you select the link to page 3. This is what happens when I try to access page 3 (that loops through the information using regex functions to check if certain information is in the proper format, for further info, read first paragraph at top)

Notice: Array to string conversion in C:…page3.php on line 29

Notice: Undefined variable: date_time in C:…page4.php on line 20

Notice: Undefined variable: fileN in C:…page4.php on line 21

Notice: Undefined variable: date_time in C:…page4.php on line 40

Notice: Undefined variable: fileN in C:…page4.php on line 41

”.$finaloutput.“
Array

Someone please help! I really can’t figure out how to get page 3 to so what it’s supposed to do!

Link to the project description:
http://php1920.redirectme.net/res_COMP1 … nment1.htm


#2

$newArrs = split(",",$ContentsArr); <-- That’s line 29 of page 3. $ContentsArr is an array, and split() expects a string.

The scope of variables does not reach into functions. Use the ‘global’ keyword to make them available inside functions (I’m not sure if passing it as a parameter is best-practice in cases such as these).

Same as above.

Same as above.

Same as above.


#3

How do you propose that I fix the Array to String notice on line 29 then? I have to split the information found in the file to display and to run regex checks on.

Thanks.


#4

split returns an array from a string, but you don’t have a string, you already have an array. So there’s no need to use split.


#5

Actually, this is what I’m trying to do with page 3: Page three opens up the file that the user selects on page1 and has passed page 2 - the files are text files which contain a varying number of lines that contain information delimited by commas which I have to separate so that I can A) run regex checks on them and B) put each piece of information in a table in the correct rows and cells. So yes, I think I’d need to split them…the problem is how…Technically I should be doing the same thing I did in page 2, except that I don’t know how to do it properly in page 3 because I tried to do exactly the same thing from page 2 onto page 3 regarding the split function and foreaches and it still gives me the same error.


Edit:

Here are the instructions from Page 2 to page 4. (I provided page 2 for reference):

Page 2:

The ONLY valid username is ?comp1920? and the ONLY valid password is ?php?. If the data entered by the user is incorrect, terminate the application with the message ?username/password combination is not correct, sorry?.

This script, page2.php, must show the contents of the text file specified by the form in page1.php.

Here is the format of the text files:

studentnumber,lastname,firstname,emailaddress

For example:

a00123456,harrison,jason,comp1920@telus.net

a00456789,baloney,tony,t_baloney@shaw.ca

a00111111,lasty,firsty,e@mail.ca

Use the file( ), trim( ) and split( ) functions to get the contents from the text file into an array.

All of the contents must be formatted using ucfirst( ) UNLESS they match the pattern for an email address (email addresses must be lowercased using strtolower( )), and displayed in a table, like this:

Now the instructor can make a choice: is this the correct file they want to use, or not? Offer the choice using two different URLs:

Choose another course file

and

Work with this course file

BUT?the page3.php option must have a query string appended to it: the name of the text file that was selected in page 1, so instead of ./page3.php, the url should be something such as ./page3?filename=comp1920.txt

Use ?filename? as the GET parameter name. Ensure the GET parameter value is urlencoded using the urlencode( ) function.

Page 3:

Page 3 is reached from page 2, and should have a GET parameter called filename:

$_GET[?filename?] should contain the name of the text file selected on page 2.

If there is no GET parameter called ?filename?, terminate the application with a message ?must specify a file, sorry?.

If there is a value in $_GET[?filename?], ensure that the file actually exists inside the courses folder. If it does not exist, terminate the application with a message ?no such file, sorry?.

If there is a value in $_GET[?filename?] AND it exists inside the courses folder, put all of the file contents into an array, one line of data per element.

Loop through the array and ensure that all of the student numbers are well formed: they must start with a or A, followed by 8 digits.

Loop through the array and ensure that all of the email addresses are well formed: alphanumeric characters followed by @ followed by alphanumeric characters followed by . followed by 2 ? 4 more alphanumeric characters (your check should be at least this good).

If a student number or email address is NOT well formed, add the entire line of data into a new textfile called ?errors.log?, along with the current date and time. An example log file looks like this (in this example, the student numbers have been repaired sometime between 12:20:02 pm and 10:07:55 pm on April 22, 2005):

Alert the user whether ?All data is fine? or ?Errors have been found in comp1920.txt. A report, errors.log has been generated?. Show a hyperlink to the errors.log file, (click here for the log).

The errors.log must be created/saved in the courses folder.

If and only if there are no errors in the textfile, generate a report showing all the valid data in a table sorted by student number, like this:

Page 4:

NOTE: The student number and email address checks must be accomplished using two functions written by you:

isStudentNumberWellFormed($studentnumber)

and

isEmailAddressWellFormed($emailaddress)

These functions return true if they pass your tests; false otherwise. These functions must reside in an external file called page4.php. page3.php must use page4.php with the require_once( ) function.[/img]


#6

Sounds like a school/homework assignment to me :wink:

I see why you want to use split() now. An array is still not correct for a parameter for split() though. If you know what arrays of strings are (and that there are arrays of integers, booleans, etc. too), and how to loop through them, you should be able to come up with a decent solution for getting the proper data. Just make sure you realize what you’re doing with split() and that the provided data is what you expect it to be (and I’m talking about the variable, not the file).


#7

Yes, it is a homework – well…major assignment sigh

Well, I sort have got it working:

Page 3:

[code]<?php
/* File: page3.php
This file is first major assignment in the PHP level 1 course.
The purpose: “To write a php application that helps an instructor set up a website for their courses.”

Author: name
Last modified: May 27, 2007.

*/

date_default_timezone_set(“America/Vancouver”);
$fileN = $_GET[“filename”];
$resultingf = “./courses/”.$fileN;
$date_time = date(“F j, Y (h:i:s)”);

if (!($fileN)){
die (“Please specify a file.”);
} else {
$fileorg = file($resultingf);
if (is_file ($resultingf)){

	foreach ($fileorg as $infos) {
		$newString = split(",",$infos);	
	}
	
	echo "<table border="1">n";
	echo "t<tr>n";
	
	
	foreach ($newString as $newInf){
		require_once("page4.php");
		
		isStudentNumberWellFormed($newInf);
		
		if (isStudentNumberWellFormed($newInf) == "false"){
			if ($filehandle = @fopen("./courses/errors.log", "a+")){
				$writetext = fwrite($filehandle, "<br />-----");
				$writetext = fwrite($filehandle, "<br />$date_time.");
				$writetext = fwrite($filehandle, "<br />Improper student number from $fileN:");
				$writetext = fwrite($filehandle, "<br />$newInf");
				fclose($filehandle) or die ("Error closing file <br />");
			} else {
				die("Cannot open file 'errors.log', an error has occured.");
			}
			}
else {
		$newResult = $newInf;
}


		isEmailAddressWellFormed($newInf);
		
		if (isEmailAddressWellFormed($newInf) == "false"){
			if ($filehandle = @fopen("./courses/errors.log", "a+")){
				$writetext = fwrite($filehandle, "<br />-----");
				$writetext = fwrite($filehandle, "<br />$date_time.");
				$writetext = fwrite($filehandle, "<br />Improper email address from $fileN:");
				$writetext = fwrite($filehandle, "<br />$newInf");
				fclose($filehandle) or die ("Error closing file <br />");
			} else {
				die("Cannot open file 'errors.log', an error has occured.");
			}
			}
else {
		$newResult = $newInf;
}
	
		

if (!(ereg("^[a-zA-Z]*$",$newInf))){
			//This is to pass the names.			
			}

		else {
			$newResult = $newInf;
		}
		echo "tt<td>".$newResult."</tdn";
					
	}
	echo "t</tr>n";
}
	
 	else {
			die ("No such file, sorry.");
		}

}

?>[/code]

Page 4:

[code]<?php
/* File: page4.php
This file is first major assignment in the PHP level 1 course.
The purpose: “To write a php application that helps an instructor set up a website for their courses.”

Author: name
Last modified: May 04, 2007.

*/

function isStudentNumberWellFormed($studentnumber){

if (ereg("^[aA][0-9]{8}$",$studentnumber)){
			return(true);
			}
else {
		return(false);
}

}

function isEmailAddressWellFormed($emailaddress){

if (ereg("^[a-zA-Z0-9_.]*@[a-z]*.[a-z]{2,5}$",$emailaddress)){
			return(true);
			}
else {
		return(false);
}

}

?>[/code]

Now the error I’m getting is: the errors.log file that should end up in the folder “./courses/” is actually ending up in the main folder. I don’t know why. Plus: I think my regexes are wrong–I only get one line of information that “passed” in a table. How would you do this: run a regex to pass an email address (with the criteria of: alphanumeric characters followed by @ followed by alphanumeric characters followed by period followed by 2 ? 4 more alphanumeric characters) and a student number (they must start with a or A, followed by 8 digits) and still be able to pass the names? Right now there’s only ONE line of results despite that there should be more and the one line that DOES show up is incorrect.