Kevin Kevin - 7 months ago 25
PHP Question

How to prevent php script number value getting negative

I found a very useful script on the internet. Anyway I don't want it to go below 0. So it won't showing negative numbers. Also I want that when the number increases, it can increase until a value. For example, I don't want the number to be more than 20 and less than 0.

How can I do that?

The script is this



<?php
// gets current value
if(isset($_POST['output'])){
$value = $_POST['output'];
} else {
$value = 0;
}
if($_POST['Add']){
// opens the file for reading
$read = fopen("file.txt", 'r');
// stores the file as variable cNumAdd
$cNumAdd = fread($read, 512);
// closes file
fclose($read);

// opens file again
$write = fopen("file.txt", "w+");
// adds 1 to the data on the file
$cNumAdd = $cNumAdd + 1;
// writes the data into the file
fwrite($write, $cNumAdd);
// closes file
fclose($write);
}
// comments are the same as above except for subtracting 1 from file
if($_POST['Remove']){
$read = fopen("file.txt", 'r');
$cNumRemove = fread($read, 512);
fclose($read);

$write = fopen("file.txt", "w+");
$cNumRemove = $cNumRemove - 1;
fwrite($write, $cNumRemove);
fclose($write);
}
?>


<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="submit" name="Add" value="Add Career">
<input type="submit" name="Remove" value="Remove Career">
<input type="text" name="output" value="<?php include("file.txt"); ?> ">
</form>




Answer

I hope this will work for you.

// opens file again 
$write = fopen("file.txt", "w+"); 
// adds 1 to the data on the file 
$cNumAdd = $cNumAdd + 1; 
// writes the data into the file 
if($cNumRemove > 20) $cNumRemove = 20;
fwrite($write, $cNumAdd); 
// closes file 
fclose($write); 
} 
// comments are the same as above except for subtracting 1 from file 
if($_POST['Remove']){ 
$read = fopen("file.txt", 'r'); 
$cNumRemove = fread($read, 512); 
fclose($read); 

$write = fopen("file.txt", "w+"); 
$cNumRemove = $cNumRemove - 1; 
if($cNumRemove < 0) $cNumRemove = 0;
fwrite($write, $cNumRemove); 
fclose($write); 
} 
?>
Comments