Simple calc – php example code

Example of using form input for two numbers and selection of one of nine possible arithmetic operation or function.

Our php application frontend is on next picture:

Our code is located in one index.php file and consist from:

  • HTML part with input form – obtain data from user, contain submit button and last part show result in two posiblle way. If there is no error message and result ist generated, then well formatted number (2 decimal numbers) is shown. Else (if number was not calculated and result is not prepared or error output message was set) warning text of red color take output (formating is created with alert message of bootstrap linked style).
  • PHP code – obtain numbers from submitted post form, controll if data available with filter_has_var(); prevent for injecting sql with simple htmlspecialchars($_POST[‚nr1‘]); and calculate result along submitted $operator = htmlspecialchars($_POST[‚operation‘]); . As demonstration for controll of user inputed data dividing by zero check take place.

Form code part of index.php follow.

<form method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“>
          <div class=“form-group“>
              <label>First number – n1:</label>
              <input type=“text“ name=“nr1″ class=“form-control“ value=“<?
                    php echo isset($_POST[‚nr1‘]) ? $nr1 : ‚0‘; ?>“>
          </div>
          <div class=“form-group“>
            <label>Second number – n2:</label>
            <input type=“text“ name=“nr2″ class=“form-control“ value=“<?
            php echo isset($_POST[‚nr2‘]) ? $nr2 : ‚0‘; ?>“>
          </div>
          
          <div class=“form-group“>
              <label>Select your operation:</label> <br>
              <table class=“table table-secondary „>
                <tr>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“+“ name=“operatio
                      n“ value=“+“  checked> 
                    <label> <h4> n1 + n2 </h4></label>
                    </td>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“-
                     “ name=“operation“ value=“-“  <?php echo ($operator == „-„) ?
                       „checked“ : “; ?> >  
                    <label><h4> n1 – n2</h4></label>
                    </td>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“Power“ 
                     name=“operation“ value=“Power“  <?php echo ($operator ==
                     „Power“) ? „checked“ : “; ?> > 
                    <label><h4> Power n1 on n2 </h4></label> 
                    </td>
               </tr>
                <tr>        
                    <td>
                    
                    <input class=“inputSelector“ type=“radio“ id=“*“ 
                   name=“operation“ value=“*“  <?php echo ($operator == „*“) ?
                   „checked“ : “; ?>  >  
                    <label><h4> n1 * n2</h4></label>
                    </td>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“/“ name=“operation
                     “ value=“/“  <?php echo ($operator == „/“) ? „checked“ : “; ?> > 
                    <label><h4>/</h4></label> 
                    </td>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“Log10″ 
                      name=“operation“ value=“Log10″  <?php echo ($operator ==
                      „Log10“) ? „checked“ : “; ?> >  
                    <label><h4>log10(n1)</h4></label>
                    </td>
                </tr>   
                <tr>        
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“sin“ 
                     name=“operation“ value=“sin“  <?php echo ($operator == „sin“) ?
                     „checked“ : “; ?>  >  
                    <label><h4> sin(n1)</h4></label>
                    </td>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“cos“ 
                      name=“operation“ value=“cos“  <?php echo ($operator == „cos“)
                        ? „checked“ : “; ?> > 
                    <label><h4>cos(n1)</h4></label> 
                    </td>
                    <td>
                    <input class=“inputSelector“ type=“radio“ id=“tg“ 
                     name=“operation“ value=“tg“  <?php echo ($operator == „tg“) ?
                      „checked“ : “; ?> >  
                    <label><h4>tg(n1)</h4></label>
                    </td>
                </tr>   
              </table>
            </div>
          <br>
          <button type=“submit“ name=“submit“ class=“btn btn-primary“> Calculate result </button>
          <?php   //($is_result == „true“) ? {          
                
                 if ($is_result && $msg == “) {
                    $result = number_format($result, 2, ‚,‘, ‚ ‚); // formating number refer to https://www.php.net/manual/en/function.number-format.php
                        echo „<br> <br>“;
                         echo “ <table class=\“table table-success\“> „;
                        echo “ <tr>
                               <td><h3> = $result</h3> <td>
                              </tr> „; 
                              echo “ </table> „;
                    
                    
                } ; 
                 ?>
                 <br>
                    
                     
                    <?php if($msg != “): ?>  <!– This part show error or warning message if one of the operand does not meet calculations requirements – dividing by zero –>
                        <br><br>    
                    <div class=“alert <?php echo $msgClass; ?>“><?php echo $msg; ?></div>
                    <?php endif; ?>
                    
      </form>

PHP code for result calculation follow

<?php
    // two variables for message and styling of the mesage with bootstrap
    $msg = “;
    $msgClass = “;
    // default values of auxiliary variables
    $operator = “; // at the beggining is no operator selected
    $is_result = „false“; //before hitting submit button no result is available
    $result = 0; // result and boath number are by default at zero values initialized
    // Control if data was submitted
    if(filter_has_var(INPUT_POST, ‚submit‘)){
        // Data obtained from $_POST are assigned to local variables
        $nr1 = htmlspecialchars($_POST[‚nr1‘]);
        $nr2 = htmlspecialchars($_POST[‚nr2‘]);
        $operator = htmlspecialchars($_POST[‚operation‘]); 
        
        $is_result = „true“;
        // calculation of appropriate results
        /* if ($operator == „+“) {          
            $result = $nr1 + $nr2;     
        };
        if ($operator == „-„) {          
            $result = $nr1 – $nr2;     
        };
        if ($operator == „*“) {          
            $result = $nr1 * $nr2;     
        };
        if ($operator == „/“) {          
            $result = $nr1 / $nr2;     
        };
        */
        //this part can be reworked for switch command for educational purposes like this
        switch ($operator) {
          case „+“: {          
                       $result = $nr1 + $nr2;     
                    }; break;
          case „-„: {          
                        $result = $nr1 – $nr2;     
                     }; break;
          case „*“: {          
                        $result = $nr1 * $nr2;     
                     }; break;
          case „/„: {   
                        if ($nr2 != 0)  { //dividing by zero mittigation, if nr2 is zero then
                                                      error message is outputed
                            $result = $nr1 / $nr2;
                            $msg = “;} 
                            else { 
                                $msg = ‚Dividing by zero NaN‘; // text of the message
                                $msgClass = ‚alert-danger‘; // bootstrap type alert-
                                                                                       danger is outputed
                             } ;  
                             
                     }; break;  
          case „Power“: {          
                        $result = Pow($nr1, $nr2);     
                     }; break;  
          case „Log10“: {          
                        $result = Log10($nr1);     
                     }; break;  
          case „sin“: {          
                        $result = sin($nr1);     
                     }; break;  
          case „cos“: {          
                        $result = cos($nr1);     
                     }; break;  
          case „tg“: {          
                        $result = tan($nr1);     
                     }; break;                       
        };
        
    }
?>
 

For main formating was used bootstrap code obtained from https://bootswatch.com/.

Small altering is created by own style.css that follow

.navbar  {
    background-color: #325d88;
    margin-bottom: 25px ;
    
}
.navbar-brand {
   
    color: white;
}
/* set midle container to width 580px */
.container {
   
    width: 580px;
    margin-left: 240px;
  
}
/* add margin to both sides in calculator input fields */
.inputSelector {
   
    
    margin-left: 20px;
    margin-right: 15px;
  
}
/* colorizing backround and change font-size of input number fields n1 and n2 partialy alter bootstrap css */
.form-control {
   
    background-color: rgb(250, 250, 131);
    font-size:25px
}
/* aboolute positioning of image on calc frontend – on left side */
#calcimage {
   
    position: absolute;
  top: 80px;
  left: 20px;
  right: 0;
  
  
}
/* change wight of label text before input field of form */
label {
   
    font-weight: bold;
}
.footer {
    background-color: #325d88;
    margin-top: 25px;
    padding-left: 15px;
    height: auto;
    
}

Full code for further study can be obtained from github here.




Submit form – example php code

This article contains example of simple submit form with control of fulfilment of all fields and valdation. For proper testing of our code is used mercury e-mail server build in in XAMPP environment.

Next picture show visual look of submit form frontend that use bootstrap stylesheet downloaded from https://bootswatch.com/.

Example of our final submit form in php

HTML code part with submiting form consist from

<!– **************************************** –>
<!– HTML code containing Form for submitting –>
<!– **************************************** –>
<!DOCTYPE html>
<html>
<head>
    <title>Contact Form</title>
    <link rel=“stylesheet“ href=“./css/bootstrap.min.css“> 
                                                           <!– bootstrap mini.css file –>
    <link rel=“stylesheet“ href=“./css/style.css“> <!– my local.css file –>
</head>
<body>
    <nav class=“navbar navbar-default“>
      <div class=“container“>
        <div class=“navbar-header“>    
          <a class=“navbar-brand“ href=“index.php“>Submit form example</a>
        </div>
      </div>
    </nav>
    <div class=“container“> 
        <?php if($msg != “): ?>
            <div class=“alert <?php echo $msgClass; ?>“><?php echo $msg; ?></div>
        <?php endif; ?>
    <form method=“post“ action=“<?php echo $_SERVER[‚PHP_SELF‘]; ?>“>
          <div class=“form-group“>
              <label>Your Name:</label>
              <input type=“text“ name=“name“ class=“form-control“ value=“<?
                php echo isset($_POST[‚name‘]) ? $name : “; ?>“>
          </div>
          <div class=“form-group“>
            <label>Your e-mail:</label>
            <input type=“text“ name=“email“ class=“form-control“ value=“<?
              php echo isset($_POST[‚email‘]) ? $email : “; ?>“>
          </div>
          <div class=“form-group“>
            <label>Please writte your mesage:</label>
            <textarea name=“message“ class=“form-control“><?
              php echo isset($_POST[‚message‘]) ? $message : “; ?></textarea>
          </div>
          <br>
          <button type=“submit“ name=“submit“ class=“btn 
            btn-primary“> Send message … </button>
      </form>
    </div>
    
       <div class=“footer“> 
          <a class=“navbar-brand“ href=“https://cdesigner.eu“> Visit us on CDesigner.eu </a>
        </div>
      
</body>
</html>

PHP code grab $_POST[] submited variables, assign them into php code variables and test its content against filtering rules. First test detect content of all needed values as name, e-mail and mesage text. Next verifies e-mail against rules expected from valid e-mails.

If something is missing or e-mail is incorrect red (bootstrap alerted style) highlight in outputed text is used.

Also our code test sucessfull e-mail sending, if sendig finished correct green message display with text

$msg = ‚Your e-mail has been sent‘;       
$msgClass = ‚alert-success‘;             

if sending was unsuccessful red message is displayed

$msg = ‚Your e-mail was not sent‘;                   
 $msgClass = ‚alert-danger‘;

PHP code looks like

<!– ************************************************* –>
<!– PHP „self“ code handling e-mailing submit request   –>
<!– ************************************************* –>
<!–         Code remastered by cdesigner.eu along               –>
<?php
    // two variables for message and styling of the mesage with bootstrap
    $msg = “;
    $msgClass = “;
    // Control if data was submitted
    if(filter_has_var(INPUT_POST, ‚submit‘)){
        // Data obtained from $_POST are assigned to local variables
        $name = htmlspecialchars($_POST[‚name‘]);
        $email = htmlspecialchars($_POST[‚email‘]);
        $message = htmlspecialchars($_POST[‚message‘]);
        // Controll if all required fields was written
        if(!empty($email) && !empty($name) && !empty($message)){
            // If check passed – all needed fields are written
            // Check if E-mail is valid
            if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
                // E-mail is not walid
                $msg = ‚Please use a valid email‘;
                $msgClass = ‚alert-danger‘;
            } else {
                // E-mail is ok
                $toEmail = ‚ciljak@localhost.org‘; //!!! e- mail address to send to – change for your needs!!!
                $subject = ‚Contact Request From ‚.$name;
                $body = ‚<h2>Contact Request</h2>
                    <h4>Name</h4><p>‘.$name.'</p>
                    <h4>Email</h4><p>‘.$email.'</p>
                    <h4>Message</h4><p>‘.$message.'</p>
                ‚;
                // Email Headers
                $headers = „MIME-Version: 1.0″ .“\r\n“;
                $headers .=“Content-Type:text/html;charset=UTF-8″ . „\r\n“;
                // Additional Headers
                $headers .= „From: “ .$name. „<„.$email.“>“. „\r\n“;
                if(mail($toEmail, $subject, $body, $headers)){
                    // Email Sent
                    $msg = ‚Your e-mail has been sent‘;
                    $msgClass = ‚alert-success‘;
                } else {
                    // Failed
                    $msg = ‚Your e-mail was not sent‘;
                    $msgClass = ‚alert-danger‘;
                }
            }
        } else {
            // Failed – if not all fields are fullfiled
            $msg = ‚Please fill in all contactform fields‘;
            $msgClass = ‚alert-danger‘; // bootstrap format for allert message with red color
        }
    }
?>

Full example code can be obtained from from github location https://github.com/ciljak/phpsubmit .

For proper work of this code you must use appropriate webhosting or use XAMPP with runing mercury e-mail server. After enabling mercury through xamp control-panel go to administration and add new user. In our case we used account with name ciljak. local domain aliases that are posible to use are localhost (can not be validate with this code), localhost.net or localhost.org. Next picture show example of mercury enabled features in XAMPP server

Mercury e-mail server in XAMPP



For versioning of our code can be used git with github service. Mouch simpler graphical tool for commiting changes and share your code with team is gitkraken https://www.gitkraken.com/. For further reading please wisit next tutorial.



Our project setup screen in gitkraken looks like next picture

Setup of new project with gitkraken



Introduction to web developement technology

From the early years of www new technology will arisen. As fundamental building bocks of all web can be recongnized HTML and CSS.

HTML or Hypertext Markup Language is content descripting markup language for description of appropriate building blocks of all webpages. Today longterm supported version is 5.0. This version is meant to be open standard – new improvements are continualy added to its syntax.

For styling or visual theming is used CSS standard (standard for Cascade Style sheets). Actual verion is 3.0. HTML+CSS introduced separation of content and look of a pages. Content is more rigid bud external styles enable quick change of look of your page from one location on your webserver.

We can say that only HTML and CSS are main building blocks of all webpages but today webs are mor dynamic and adaptive. You can make administration from web backends, or you can make subscription and then gain access to elevated content of pages.

These improvements enable scripting technologies. These technologies can be divided on two main parts:

a) scripting technologies on server side – for a long time and beacause wide support in hosting houses wide spreaded technology is PHP. For PHP is common that generate pure HTML as interpreted output. Today standardized version is 7.4 but version 8.0 is in development. More reading about PHP can be found on https://www.php.net/docs.php or in more descriptive way on wiki https://en.wikipedia.org/wiki/PHP .

PHP is not only server side technology – for bigger projects but with lover support at hosting company are node.js (server side scripting with javascript), java jsp or servlets or microsoft asp.

b) scripting technology on client side – widely used is javascript (not confuse with java because this scripting languahe has nothing with java/ jsp as its name will sugest). Difference between server side and client side scripting is that client script must be downloaded to the browser and interpreted by them. Taht lead to possible problems with code confidentiality and posible blocking features on browser/ client side. Output of server scripting technology can by pure HTML/ CSS pages.

If you are involved in bigger projects or make common web for larger public existing frameworks will accelerate development. When you use framework you can obtain generated parts and use prepared parts of web. Most frameworks insist on design patterns named MVC (model – view – controller). MVC concept separate building parts of code in to:

  • model – driving logic of aplication, how are data handled and stored with database
  • view – visual part of aplication
  • controller – part handling requests from the clients and event generated by states of application

Well known frameworks are:

  • symfony for PHP scripting language – more reading at https://symfony.com/
  • bootstrap – for frontend developement – for furter reading https://getbootstrap.com/
  • angular – used by google, big framewor for creation robust application, based on javascriptsyntax https://angular.io/docs
  • react – frontend development framwork used by facebook, based on javascript syntax (user friendlier as angular) https://reactjs.org/
  • jQuery – small framework for web scripting and DOM manipulation (separtaion of parts of page and manipuating them). Can be used for srooling menu creation, animation of galeries … .For furter reading you can visit https://jquery.com/ .