PHP code for calculator. validated but not working - php

So I have a calculator coded in PHP and I have validated it but there is a problem with this, its not working. I have used server side validation. Validation works well. But it doesn't do any work,for example, when I give an input like 2+8, it gives an output of 8888. This is very confusing. Please help me out with this. Thanks.
HTML page is here:
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form method = "post" action = "calc.php">
<input type = "text" name = "val_1"/>
<select name="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type = "text" name = "val_2"/>
<input type = "submit" value = "calculate" name = "checker"/>
</form>
</body>
</html>
And here is the PHP code.
<?php
if(isset($_POST['checker'])) {
#Clean all values
function cleanStr($str){
$str = trim($str);
$str = addslashes($str);
$str = htmlspecialchars($str);
return $str;
}
$val_1=cleanStr($_POST['val_1']);
$val_2=cleanStr($_POST['val_2']);
$operator=$_POST['operator'];
function emptyFileds($ar){
if(!is_array($ar)){
echo "It must be an array";
return false;
}
#loop through each field to check for empty values
foreach($ar as $key => $value){
$value = CleanStr($value);
if(empty($value)){
echo $key . " must not be empty";
return false;
}
}
return true;
}
if(!emptyFileds($_POST)){
exit();
}
if($operator==="+"){
echo "Sum is " . $val_1+$val_2;
}
}
?>

Please change the original line
echo "Sum is " . $val_1+$val_2;
to
echo "Sum is " . ($val_1+$val_2);
It's a operator precedence issue as . is executed first. Therefore you append 2 to "Sum is " and then increment the string by 8 which results in this odd behavior.
Also, some nitpicking on your code, I will just name 3 issues:
requesting a parameter with cleanStr() is not a good idea, it's better to use
$val_1 = (int)trim($_POST['val_1']);
as $val_1 will be an integer after that line. This might be important for later development e.g. to compare numbers.
indent correctly, reading your code is hurting my eyes
the whole emptyFileds()thing is unnecessary, simply check whether the 3 parameters are filled or not, it's simple and it's readable.

Related

PHP -- How to replace string value to user input?

Can someone help me to figure out how to replace a defined string value with user input value? I am quite new in PHP programming and could not find an answer. I saw a lot of ways to replace string on the internet by using built-in functions or in arrays, but I could not find out the right answer to my question.
Here is my code:
$text = "Not found";
if ( isset($_GET['user'])) {
$user_input = $_GET['user'];
}
// from here I I tried to replace the value $text to user input, but it does not work.
$raw = TRUE;
$spec_char = "";
if ($raw) {
$raw = htmlentities($text);
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>"; *# displays "Not found"*
} elseif (!$raw == TRUE ) {
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
I appreciate your answers.
Lets run over your code, line by line.
// Set a default value for $text
$text = "Not found";
// Check if a value has been set...
if (isset($_GET['user'])) {
// But then create a new var with that value.
// Why? Are you going to change it?
$user_input = $_GET['user'];
}
// Define a few vars
$raw = TRUE;
$spec_char = "";
// This next line is useless - Why? Because $raw is always true.
// A better test would be to check for $user_input or do the
// isset() check here instead.
if ($raw) {
// Basic sanity check, but $text is always going to be
// "Not found" - as you have never changed it.
$raw = htmlentities($text);
// render some HTML - but as you said, always going to display
// "Not found"
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>";
} elseif (!$raw == TRUE ) {
// This code is never reached.
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
// I have no idea what this HTML is for really.
// Guessing this is your "input" values.
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
Just a guess I think you really wanted to do something more like this:
<?php
// Check if a value has been posted...
if (isset($_POST['user'])) {
// render some HTML
echo '<p style="font-style:bold"> PIN '.htmlspecialchars($_POST['user']).'</p>';
}
?>
<form method="post" action="?">
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>

how to add a parameter to the url in php?

I'm trying to add the parameter cs with a value of 1 to the url using a form and hidden type input. When I execute this, I have a simple if statement that checks to see if $_GET['cs'] is = to 1, but I get a Notice: Undefined index. I'm a php beginner, any help, explanations, or alternatives is very much appreciated.
echo '<form>';
echo '<input type="hidden" name="cs" value="1">';
echo '</form>';
if($_GET['cs'] == 1) {
echo'working';
}
else {
echo 'not working';
}
Only after form is submitted you will see 'cs' in $_GET array.
The $_GET array contains all parameters on the URL line.
For example if a URL is: https://example.com?param1=1&param2=2
You will get a $_GET array with two entries ('param1' and 'param2') with values 1 and 2.
You should add a check using the isset function (https://www.php.net/manual/en/function.isset.php). Otherwise it will try to access the parameter if it isn't sent. In your case the parameter was probably not sent.
Url in html:
test the get method
The url test
<?php
if ($_GET['varaible'] == true) {
$varaible = 'Its work';
$value = false;
}else{
$varaible = 'Oooppss';
$value = true;
}
echo $varaible . '<br>';
?>
Full code:
<?php
if ($_GET['varaible'] == true) {
$varaible = 'Its work';
$value = false;
}else{
$varaible = 'Oooppss';
$value = true;
}
echo $varaible . '<br>';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>get varaible</title>
</head>
<body>
test the get method
</body>
</html>

How to add GET and remove

I have more GET variables. I want the variables to be added after clicking. And after clicking again I want them to be removed from GET. I am a beginner and I don't know how to do it.
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url=$_SERVER[QUERY_STRING];
if(!empty($url)){
$url="&".$url;
}
?>
<form action="" method="GET">
<?php
foreach($tab_array as $key => $val){
?>
<?php echo $key;?>
<?php
}
?>
</form>
Someone will help?
Sorry for my bad English...
Code
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url='?'; // this will call the current url
// $_GET is the array your submitted data will be strored in - initially empty []
?>
<form method='GET'><!-- you actually don't need a form, since only input, textarea, etc get submitted -->
<?php
// save current state, so you can modify it for every possible click
$current_get = $_GET;
foreach($tab_array as $key => $value) {
$new_get = $current_get;
// check if the current key is already in your set ($new_get)
if (array_key_exists($key, $new_get)) { // it is, so remove
unset($new_get[$key]);
} else { // it is not, so add
$new_get[$key] = $value;
}
// build your query_string (from $new_get array)
$query_string = http_build_query($new_get);
// you can use variables in string when its encapsulated in double quotes: "text $var"
echo "<a href='$url$query_string'>$key</a>";
// more readable:
// echo "<a href='{$url}{$query_string}'>{$key}</a>";
// not need but looks better :P
echo '<br />' . PHP_EOL;
}
?>
</form>
A little more
there is a shortcut for <php echo $var ?> which is just <?= $var ?>
Links
array_key_exists
unset
http_build_query

PHP echo doesn't show up in webpage

So im fairly new in coding HTML CSS and PHP and now im focusing PHP.
Our professor asked us to incorporate PHP codes in our website (no database) and im trying to print a an array using a for loop and echo.
the problem is that the echo doesn't show in the webpage and I am now lost
below is my codes:
<html>
<head>
<title>PHP Loops and Sorts</title>
<body>
<h1>PHP Loops and Sorts</h1>
<div class="container">
<?php
$dogs=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu");
$cats=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin");
$birds=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds");
$fishes=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp");
function countsize($array,$size){
$size = count($array);
return $size;
}
if(isset($_POST['btnShow']) )
{
$arraypick=$_POST['formAnimal'];
$arrsize = countsize($arraypick,$size);
for(&x = 0,$x<$arrsize,$x++){
echo $arraypick[$x] . "<br>";
}
}
?>
Breeds of different kinds of animals. Select what animal's breed to be shown:<br>
<select name="formAnimal">
<option value="">Choose animal</option>
<option value="dogs">Dog</option>
<option value="cats">Cat</option>
<option value="birds">Bird</option>
<option value="fishes">Fish</option>
</select><br><br>
<div style="margin:auto,text-align:center;text-align:center">
<INPUT TYPE = "Submit" Name = "btnShow" VALUE = "Show List"> 
<INPUT TYPE = "Submit" Name = "btnAsc" VALUE = "Show Ascending"> 
<INPUT TYPE = "Submit" Name = "btnDes" VALUE = "Show Descending">
</div>
<?php
echo $size
?>
</div>
</body>
</html>
You need to close your head tag before your body tag.
You also don't need to pass in size to your method count size.
function countsize (&array) {
return count(&array);
}
if(isset($_POST['btnShow']) ) are you sure it is set ?
From what we have in your code you can't even POST, you are missing your form tags
Try wrapping your inputs with :
<form method="POST">
<!--inputs-->
</form>
Your syntax for the for loop is incorrect. Check out the php documentation
Also the $size variable is never declared in the scope you are using it.
Didn't get how you're using $arrsize but you used &x instead of $x while initializing loop.
for($x = 0,$x<$arrsize,$x++){
echo $arraypick[$x] . "<br>";
}
change this lines of code:
$dogs=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu");
$cats=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin");
$birds=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds");
$fishes=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp");
function countsize($array,$size){
$size = count($array);
return $size;
}
$arraypick=$_POST['formAnimal'];
$arrsize = countsize($arraypick,$size);
for(&x = 0,$x<$arrsize,$x++){
echo $arraypick[$x] . "<br>";
}
To :
$animalArray['dogs']=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu");
$animalArray['cats']=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin");
$animalArray['birds']=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds");
$animalArray['fishes']=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp");
function countsize($index){
return count($animalArray[$index]);
}
$arraypick=$_POST['formAnimal'];
$arrsize = countsize($arraypick);
for($x = 0;$x<$arrsize;$x++){
echo $animalArray[$arraypick][$x] . "<br>";
}

Working with strings and variables from html forms to php

I have been struggling with a problem working in both html and php.
in my html, i have a form tag that includes:
<input type="text" name="car1" size="4" value="" /> car1
In my php, i have this:
$car1 = 'my favorite car is ' . $_POST['car1'];
echo $car1;
I am trying to figure out a way so that when the user does not input anything into the car1 field in html, echo $car1; will print nothing or blank but when the user does input something, $car1 will echo my favorite car is $car1.
I tried using if(empty() and if(isset() but i am having issues to make it work for some reason.
Any ideas to do this properly? thanks for the help!
if(!empty($_POST['car1'])){
$car1 = 'my favorite car is ' . $_POST['car1'];
echo $car1;
}
Try:
if ($_POST["car1"] !== "") {
$car1 = "my favourite …";
} else {
$car1 = "";
}
As simple as:
if (!empty($_POST['car1'])) {
echo 'my favorite car is ' . htmlentities($_POST['car1']);
}
See here which values are regarded as empty. If you want more control, use something like:
if (isset($_POST['car1']) && $_POST['car1'] !== '')
You should
always check whether keys in $_POST are !empty or isset before using them
always HTML escape user supplied data for output
use labels:
<input type="text" name="car1" size="4" id="car1Input" value="" />
<label for="car1Input">car1</label>
if(isset($_POST["car1"]))
$car1 = "my favorite car is $_POST["car1"]";
else
$car1 = "";
return $car1 //if function or
echo $car1; //if general

Categories