PHP Math Pythagoras - php

Okay, I've coded this pythagoras-solver kind of thing, and I was wondering any ways I could improve it, or make it more efficient?
<?php
$sides = array('1' => 'Hypotenuse',
'2' => 'Adjacent',
'3' => 'Opposite');
function createSideDropdown($name) {
global $sides;
$option = "<select name='".$name."'>";
if(!empty($sides)) {
foreach($sides as $id => $sideDesc) {
$option .= "<option value='".$id."'>".$sideDesc."</option>";
}
} else {
die("Error fetching sides!");
}
$option .= "</select>";
echo $option;
}
try {
if(!empty($_POST['submit'])) {
if(empty($_POST['val1']) || empty($_POST['val2'])) {
throw new Exception("Please enter an integer in both boxes.");
}
if(!is_numeric($_POST['val1']) || !is_numeric($_POST['val2'])) {
throw new Exception("One of the numbers you entered is not a valid integer.");
}
$val1 = $_POST['val1'];
$val2 = $_POST['val2'];
$val1numtype = $_POST['val1type'];
$val2numtype = $_POST['val2type'];
$val1nametype = $sides[$val1numtype];
$val2nametype = $sides[$val2numtype];
if($val1numtype == $val2numtype) {
throw new Exception("The two sides of the triangle must be different");
}
if($val1nametype == "Hypotenuse" || $val2nametype == "hypotenuse") {
// work out a small side
$bignum = max($val1, $val2);
$smallnum = min($val1, $val2);
$sqTotal = ($bignum * $bignum) - ($smallnum * $smallnum);
$total = sqrt($sqTotal);
echo $bignum."² - ".$smallnum."² = ".$sqTotal."<br />
√".$sqTotal." = ".$total.$_POST['mes'];
} else {
// work out the hypotenuse
$sq1 = $val1 * $val1;
$sq2 = $val2 * $val2;
$sqTotal = $sq1 + $sq2;
$total = sqrt($sqTotal);
echo $val1."² + ".$val2."² = ".$sqTotal."<br />
√".$sqTotal." = ".$total.$_POST['mes'];
}
echo "<br /><br />"; // Seperate the working out from the input
}
} catch(Exception $e) {
echo $e->getMessage()."<br/><br/>";
}
?>
<form method='POST' action='index.php'>
Value 1: <input type='text' name='val1' />
<?php createSideDropdown("val1type"); ?>
<br /><br />
Value 2: <input type='text' name='val2' />
<?php createSideDropdown("val2type"); ?>
<br />
<select name="mes">
<option name="mm">mm</option>
<option name="cm">cm</option>
<option name="m">m</option>
<option name="cm">km</option>
</select>
<br />
<input type="submit" name="submit" />
</form>
?>

Well, one thing you can certainly do is:
HTML on its own and PHP on its own - separate that. And then, I would continue having a look at the rest.
Also, you could do your exceptions with JavaScript - I mean, use JavaScript to parse the text fields and write the errors with JavaScript. Rather than always submitting the form. - Still you should parse the fields in PHP as well.
Then, make a class out of it and make a proper documentation of it such as
/**
* This method does bla
* #param Int a
*/
Don't use globals - could be done with class attributes.

Related

PHP - Having a placeholder 'echo' so to speak

<?
//LUHN ALGORITHM PHP CONVERSION
// CREDIT CARD NUMBER CHECKER BY JACK BELLAMY - JACKBELLAMY.CO.UK
//----------- RETREIVE THE STRING FROM THE FORM POST -------------//
$var = $_POST['cardnumber'];
//----------- SPLIT THE 16 CHARACTOR STRING INTO INDIVIDUAL CHARACTERS AND ASSIGN TO INDIVIDUAL VARIABLES ---------------//
$n0 = $var[0];
$n1 = $var[1];
$n2 = $var[2];
$n3 = $var[3];
$n4 = $var[4];
$n5 = $var[5];
$n6 = $var[6];
$n7 = $var[7];
$n8 = $var[8];
$n9 = $var[9];
$n10 = $var[10];
$n11 = $var[11];
$n12 = $var[12];
$n13 = $var[13];
$n14 = $var[14];
$n15 = $var[15];
// ---------------------CHECKING THE CARDNUMBER FORM POST SUBMITS ALL VALUES PROPERLY
/*
echo $n0;
echo $n1;
echo $n2;
echo $n3;
echo $n4;
echo $n5;
echo $n6;
echo $n7;
echo $n8;
echo $n9;
echo $n10;
echo $n11;
echo $n12;
echo $n13;
echo $n14;
echo $n15;
*/
//-------ASSIGNING THE NEW VARIABLE VALUES ------------//
$n14_new = ($n14*2);
$n12_new = ($n12*2);
$n10_new = ($n10*2);
$n8_new = ($n8*2);
$n6_new = ($n6*2);
$n4_new = ($n4*2);
$n2_new = ($n2*2);
$n0_new = ($n0*2);
//!-----!------!//
//------------------------TESTING WITH THE NEW VARAIBLE *2
/*
echo $n0_new;
echo $n1;
echo $n2_new;
echo $n3;
echo $n4_new;
echo $n5;
echo $n6_new;
echo $n7;
echo $n8_new;
echo $n9;
echo $n10_new;
echo $n11;
echo $n12_new;
echo $n13;
echo $n14_new;
echo $n15;
*/
//--------- THE MATHS FOR THE COMPLETE SUM ------------ //
$isitlegit = ($n0_new+$n1+$n2_new+$n3+$n4_new+$n5+$n6_new+$n7+$n8_new+$n9+$n10_new+$n11+$n12_new+$n13+$n14_new+$n15);
//!----MATHS-----!//
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="veri-styles.css"
</head>
<body>
<div class="container">
<div class="main-wrapper">
<div id ="verification-wrapper">
<form action="" method="post" enctype="application/x-www-form-urlencoded">
<div id="input-holder">
<input name="cardnumber" type="text" class="input-style" placeholder=""> </input>
<button class="button-style">Verify my card</button>
</div>
</form>
<div class="result-class">
<?php
if(isset($isitlegit) && ($isitlegit % 5 == 0)) { // it's good
$new = "<img src='correct.jpg' />";
} elseif(isset($isitlegit) && ($isitlegit % 5 != 0)) { // it's bad
$new = "<img src='incorrect.jpg' />";
} elseif(!isset($isitlegit)) { // make sure this is not set
$new = "<img src='card-number-required.jpg' />";
}
echo $new;
?>
</div>
</div>
</div>
</body>
</html>
You have three states you need to account for, 'open', 'correct', and 'incorrect' To do that you start with an 'open' state.
$new = "<img src='please_enter your card number.jpg' />";
echo $new;
You would use that in the first condition of your test -
if(isset($var) && ($isitlegit % 5 == 0)) { // it's good
$new = "<img src='correct.jpg' />";
} elseif(isset($var) && ($isitlegit % 5 != 0)) { // it's bad
$new = "<img src='incorrect.jpg' />";
} else { // the default view
$new = "<img src='please_enter your card number.jpg' />";
}
echo $new;
Once submitted you can only have one of two states, never to return to the default.
In addition you have left your stylesheet declaration un-closed. Please change it to this -
<link rel="stylesheet" type="text/css" href="veri-styles.css" />
if(false===$submitted){
echo "Please type your card details here";
} else {
if($isitlegit % 5 == 0) {
$new = "<img src='correct.jpg' />";
echo $new;
}
else {
$new = "<img src='incorrect.jpg' />";
echo $new;
}
}
The best way I can think of to achieve this is with AJAX. Create a div on your page where your initial message is displayed, and then use an AJAX call to submit the form data to a script you'll use to validate it, and within that script, echo either a "Success! Your card has been verified" or a "Unable to validate your card" message. Then have your AJAX function change the .innerHTML of the div to the responseText element. You can see this answer for a good starting point, as well as a note about using the jQuery library to simplify your AJAX implementation.
Edit: In response to another user's downvote, here's some code.
First, let's give your HTML form a call to an AJAX object we'll create. So change your HTML form code to this:
<form onSubmit="return process()">
process() is a javaScript function we're going to set up later with the AJAX call. You already have a div established where you want this data to appear, but we need to give it an id, so change:
<div class="result-class">
please enter your card number<img src='correct.jpg' />
</div>
to this:
<div class="result-class" id="result">
Please enter your card number.
</div>
And also assign an id to your text input:
<input name="cardnumber" type="text" class="input-style" placeholder="" id="cardnumber"> </input>
Now we'll create the javaScript function. (This is easier with jQuery, but I wrote it in plain javaScript so you won't need the dependancy if you're not familiar with how to use jQuery.
function process(){
var xmlhttp = new XMLHttpRequest();
var cardnumber = document.getElementById("cardnumber").value;
var result = document.getElementById("result");
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
result.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","validate.php?cardnumber=" + cardnumber,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
return false;
}
Now, use whatever php script you were going to use to validate the cc# and save it as a separate script called validate.php Use $_GET['cardnumber'] variable to fetch the cardnumber data sent from the form, run it through whatever validation process you are using. Use an if statement to create the responseText element for our AJAX function. You might have your script set some variable to boolean true or false to check this. I'll use $validated here.
if($validated){
echo 'Your card has been verified!';
} else {
echo 'Unable to validate your card.';
}
The AJAX function will change the text inside the "result" div to whatever text is echoed by your validate.php script.
This should get you on the right track, barring any syntax errors, I just wrote this all off the cuff.

Passing information using post method without session variables

I will admit immediately that this is homework. I am only here as a last resort after I cannot find a suitable answer elsewhere. My assignment is having me pass information between posts without using a session variable or cookies in php. Essentially as the user continues to guess a hidden variable carries over all the past guesses up to that point. I am trying to build a string variable that holds them all and then assign it to the post variable but I cannot get anything to read off of the guessCounter variable i either get an undefined index error at the line of code that should be adding to my string variable or im just not getting anything passed over at all. here is my code any help would be greatly appreciated as I have been at this for awhile now.
<?php
if(isset($_POST['playerGuess'])) {
echo "<pre>"; print_r($_POST) ; echo "</pre>";
}
?>
<?php
$wordChoices = array("grape", "apple", "orange", "banana", "plum", "grapefruit");
$textToPlayer = "<font color = 'red'>It's time to play the guessing game!(1)</font>";
$theRightAnswer= array_rand($wordChoices, 1);
$passItOn = " ";
$_POST['guessCounter']=$passItOn;
$guessTestTracker = $_POST['guessCounter'];
$_POST['theAnswer'] = $theRightAnswer;
if(isset($_POST['playerGuess'])) {
$passItOn = $_POST['playerGuess'];
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$guessTestTracker = $_GET['guessCounter'];
$theRightAnswer = $_GET['theAnswer'];
}
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['playerGuess'])) {
if(empty($_POST['playerGuess'])) {
$textToPlayer = "<font color = 'red'>Come on, enter something(2)</font>";
}
else if(in_array($_POST['playerGuess'],$wordChoices)==false) {
$textToPlayer = "<font color = 'red'>Hey, that's not even a valid guess. Try again (5)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if(in_array($_POST['playerGuess'],$wordChoices)&&$_POST['playerGuess']!=$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>Sorry ".$_POST['playerGuess']." is wrong. Try again(4)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if($_POST['playerGuess']==$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>You guessed ".$_POST['playerGuess']." and that's CORRECT!!!(3)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
}
}
}
$_POST['guessCounter'] = $passItOn;
$theRightAnswer=$_POST['theAnswer'];
for($i=0;$i<count($wordChoices);$i++){
if($i==$theRightAnswer) {
echo "<font color = 'green'>$wordChoices[$i]</font>";
}
else {
echo $wordChoices[$i];
}
if($i != count($wordChoices) - 1) {
echo " | ";
}
}
?>
<h1>Word Guess</h1>
Refresh this page
<h3>Guess the word I'm thinking</h3>
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
<input type = "text" name = "playerGuess" size = 20>
<input type = "hidden" name = "guessCounter" value = "<?php echo $guessTestTracker; ?>">
<input type = "hidden" name = "theAnswer" value = "<?php echo $theRightAnswer; ?>">
<input type = "submit" value="GUESS" name = "submitButton">
</form>
<?php
echo $textToPlayer;
echo $theRightAnswer;
echo $guessTestTracker;
?>
This is a minimal functional example of what you need to do. There are still a couple of minor bugs (like duplicate entries in the history), but I've left these as an exercise for you. Treat this as a starting point and build up what you need from it.
I've added comments to explain what's happening, so hopefully it is clear to you.
$answer = null;
$history = [];
$choices = ['apple', 'grape', 'banana'];
$message = '';
// check if a guess has been made.
if (!empty($_POST) && !empty($_POST['guess'])) {
// check if previous guesses have been made.
if (!empty($_POST['history'])) {
$history = explode(',', $_POST['history']);
}
// check guess.
if (!empty($_POST['answer']) && !empty($_POST['guess'])) {
// check guess and answer are both valid.
if (in_array($_POST['guess'], $choices) && isset($choices[$_POST['answer']])) {
if ($_POST['guess'] == $choices[$_POST['answer']]) {
// correct; clear history.
$history = [];
$message = 'correct!';
} else {
// incorrect; add to history and set previous answer to current.
$history[] = $_POST['guess'];
$answer = $_POST['answer'];
$message = 'incorrect!';
}
} else {
// invalid choice or answer value.
}
}
}
if (empty($answer)) {
// no answer set yet (new page load or correct guess); create new answer.
$answer = rand(0, count($choices) - 1);
}
?>
<p>Guess the word I'm thinking:</p>
<p><?php echo implode(' | ', $choices) ?></p>
<form method="POST">
<input type="hidden" name="answer" value="<?php echo $answer; ?>">
<input type="hidden" name="history" value="<?php echo implode(',', $history); ?>">
<input type="text" name="guess">
<input type="submit" name="submit" value="Guess">
</form>
<p><?php echo $message; ?></p>

PHP compare values not working

i have a form that i've made a custom security question for.
It randomizes a question with the code
$rand1 = rand ( 1,20 );
$rand2 = rand ( 1,20 );
$randsvar = $rand1 + $rand2;
$securefråga = "Vad blir " . $rand1 . "+" . $rand2;
and i then parse it in to my code as
$_POST["secure"]
after that i convert them both to integers and compare both the converted $randsvar and the form value with eachother with the code
$intSecure = intval($secure);
$intRand = intval($randsvar);
if($intSecure == $intRand)
{
$errorNummer++;
}
else
{
$secureErr = "wrong answer";
}
however even if i type the correct answer it gives me the error message, what am i doing wrong?
You can use sessions to save the current operation. If submitted, compare the user input to the saved session total. Rough example:
if(!isset($_POST['submit'])) {
$_SESSION['rand1'] = rand(1, 20);
$_SESSION['rand2'] = rand(1, 20);
$_SESSION['randsvar'] = $_SESSION['rand1'] + $_SESSION['rand2'];
} else {
$input = $_POST['input'];
if($input == $_SESSION['randsvar']) {
echo 'correct';
} else {
echo 'incorrect';
}
exit;
}
?>
<form method="POST">
<label>
<?php echo $_SESSION['rand1'] . ' + ' . $_SESSION['rand2'] . ' = '; ?>
<input type="text" name="input" />
<input type="submit" name="submit" />
</label>
</form>

$_POST within the class

I've got a class Posts which has public function displayPosts:
public function displayPosts($numberOf = 50){
$result = $this->mysqlResult($this->id);
$i = 1;
while ($post = mysql_fetch_object($result)) {
$added = new Time;
$elapsed = $added->displayElapsedSignificant($post->data);
echo "
<h1>$post->title</h1>
<i>$elapsed</i>
<p>$post->text</p>
<h3>...komentarze...</h3>";
$this->displayComments($post->id);
"<hr />";
if($i == $numberOf) break;
else $i++;
}
}
And the private function displayComments:
private function displayComments($id){
$postComments = new Comments;
switch($this->getElement($id, "comment_type")){
case 1:
if($_POST) {
echo addSecurity($_POST['comment']);
}
else {
echo '
Zostaw komentarz:
<form action="#" method="post">
<textarea id="comment"></textarea><br />
<input type="submit" value=" Dodaj komentarz " />
</form>
';
}
break;
case 2:
//kod dla fb
break;
case 3:
//kod dla obu
break;
default:
break;
}
}
My problem is that the form doesn't work: the $_POST is always empty. Any solution?
You need name attribute for form values to be send to server - like this:
<textarea id="comment" name="comment"></textarea>
$_POST is filled with name (not id) attributes as keys and values as values :)

How to display answer to a form?

If im trying to post the answer on the same page would it look something like this? Not too sure whether I have used the correct functions, please check my code:
<form method="post" action="activity.php">
<input type="text" name= "num1" value="Enter a number"/>
<select name= "conversion">
<option>Select a conversion</option>
<option name="lb to kg">lbs to kgs</option>
<option name="kgs to lbs">kgs to lbs</option>
<option name="cm to in">cms to inchs</option>
<option name="inchs to cms">inchs to cms</option>
<option name="pints to litres">pints to litres</option>
<option name="litres to pints">litres to pints</option>
<option name="faranheit to centigrade">faranheit to centigrade</option>
<option name="centigrade ti faranheit">centigrade to faranheit</option>
</select>
<input type="submit" value="convert" />
</form>
Then the php after the form:
$num1 = $_GET["num1"];
$conversion = $_POST["conversion"];
if($conversion == "lbs to kgs")
{
$answer_lb = $num1 * 0.45;
echo $answer_lb;
}
if($conversion == "kgs to lbs")
{
$answer_kg = $num1 * 2.2;
echo $answer_kg;
}
if($conversion == "cms to inchs")
{
$answer_inch = $num1 * 2.54;
echo $answer_inch;
}
if($conversion == "inchs to cms")
{
$answer_cm = $num1 * 0.393;
echo $answer_cm;
}
if($conversion == "pints to litres")
{
$answer_pints = $num1 * 0.568;
echo $answer_pints;
}
if($conversion == "litres to pints")
{
$answer_litres = $num1 * 1.579;
echo $answer_litres;
}
if($conversion == "faranheit to centigrade")
{
$answer_faranheit = ($num1 - 32) * (5/9);
echo $answer_faranheit;
}
if($conversion == "centigrade to faranheit")
{
$answer_centigrade = ($num1 * 9/5) + 32;
}
?>
<em>
I wasnt sure whether or not the php code has to come before or after the form and was unsure about the form action.
//EDITED the answer according to your needs:
Here's a working example of the code below: http://codepad.viper-7.com/vu6j0N
<?php
$calculation_models = array();
$calculation_models[] = array('description'=>'lb to kg',
'calculation' => function($val) { return $val * 0.45; }
);
$calculation_models[] = array('description'=>'kgs to lbs',
'calculation' => function($val) { return $val * 2.2; }
);
$calculation_models[] = array('description'=>'cm to in',
'calculation' => function($val) { return $val * 2.54; }
);
$calculation_models[] = array('description'=>'inchs to cms',
'calculation' => function($val) { return $val * 0.393; }
);
$calculation_models[] = array('description'=>'pints to litres',
'calculation' => function($val) { return $val * 0.568; }
);
$calculation_models[] = array('description'=>'litres to pints',
'calculation' => function($val) { return $val * 1.579; }
);
$calculation_models[] = array('description'=>'faranheit to centigrade',
'calculation' => function($val) { return ($val - 32) * (5/9); }
);
$calculation_models[] = array('description'=>'centigrade to faranheit',
'calculation' => function($val) { return ($val * 9/5) + 32; }
);
if (isset($_GET['val']) && isset($_GET['model'])) {
$result = $calculation_models[$_GET['model']]['calculation']($_GET['val']);
echo 'The result is ' . $result;
}
?>
<!-- build the form dynamically from the array above -->
<form method="get" action="#">
<input type="text" name="val" placeholder="Enter a number"/>
<select name="model">
<?php foreach($calculation_models as $key => $model) : ?>
<option value="<?php echo $key; ?>"><?php echo $model['description']; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="convert" />
</form>
if you are asking this question, then it is not exactly simple. To change the content of the page without reloading a new page usually involves a technique known as AJAX,
basically, it uses javascript to submit the request, and javascript will again process the response after it is received.
I assume you have to files like: calculator.html and calculator.php
calculator.html is the form.
The first solution to make the result display on the same page is simple:
put everything into caclculator.php like this
<?php
if($_GET["submit"]){
#your code
}
?>
<html>
<!-- your html -->
</html>
If this was not what you asked for, the next method is using an iframe "with the result" and javascript to send your data to the iframe.
And the last solution is plain-ajax.

Categories