Reading value from text file into Php Variable

Associate
Joined
6 Mar 2009
Posts
495
Hi Guys

I have a testing website that checks tests done on products to see if they have passed or failed. So for example the user may type into the table and it will check if it has passed/failed. For example to pass the value may have to be in the range of 5-20. At the minute i have it checking the inputted value with if statements and < > signs to check if the value is in the range of 5-20.

Now and again the range/spec may change and i would like a way of having the range stored in a text file or excel file and for the program to read the value from there so it could be easily changed if need be.

I can read values from a text file and print them but not sure how i could save it in a php variable and then use that value in my testing check.

For example this is how i check if the value is in a certain range to pass or fail

Code:
if(($_POST[field1] >0) && ($_POST[field2]<=20) && ($_POST[field3] >=80) && ($_POST[field4] <=100))

Could anyone help me on this please?

Thanks
 
Associate
OP
Joined
6 Mar 2009
Posts
495
Ok i created this piece of code:

PHP:
$file = "testFile.txt";
	$lines = file( $file ); 
			
if(($_POST[field1] > $lines[0]) && ($_POST['field2'] <= $lines[1] ) && ($_POST['field3'] >= $lines[2] ) && ($_POST['field4'] <=$lines[3]))

I have a text file with the numbers 20,30,70,80 in it. This code will pass the product if the values are between 20-30 in one field and 70-80 in the second field.

This will only pass the test if i input 30 in the first field and 80 in the second. It wouldnt pass anything that is inside the range.

Can anyone help me please??
 
Associate
Joined
12 Nov 2012
Posts
1,075
Location
Gloucestershire, UK
Im at work so only a quick reply and I have not worked with php for quite a while now.

PHP:
//create an array to store your values in.
$arr = array();
//Create a reference to the file
//The "r" flag means read only. 
$file = fopen("file path", "r");
//Iterate over the file until you reach the end
while(!feof($handle)) 
{
       //currLine holds the current line in the file.
       $currLine = fgets($file);
       //Add the line to the array arr
       array_push($arr, $currLine);
}
fclose($file);

your values are now in the array and you can either further process them or use them by referencing them arr[0] -> arr[n]

this approach is relying on each value being on its own line, you could alternatively use comma separated values and use the explode function on the line you read in to generate an array of values.
 
Last edited:
Back
Top Bottom