PHP is a client server language, lots of web developers use this, it is very popular because of its security such as when you write a code in any other langue your code is seen by any one by just clicking ctr+u, but as far as php is concerned you can not seen any part of content because its code runs completely in web server that provides only results back to your browser. Same like in this post we are going to write a code of php calculator.
Simlpy when you use this code in your website in proper way you provide a calculator to your visitors. But remember it does not work as you do in html as I have already told you that php was client server language and your all code executes in web server.
First of all we write a php script for calculator after we discuss how to use in running website and in your personal computer as well.
PHP Calculator Script:
<h1><center> My Calculator </center></h1><br> <table border="2" align="center"> <tr bgcolor="yellow"> <th> <?php $result = ""; class calculator { var $a; var $b; function checkopration($oprator) { switch($oprator) { case '+': return $this->a + $this->b; break; case '-': return $this->a - $this->b; break; case '*': return $this->a * $this->b; break; case '/': return $this->a / $this->b; break; default: return "Sorry No command found"; } } function getresult($a, $b, $c) { $this->a = $a; $this->b = $b; return $this->checkopration($c); } } $cal = new calculator(); if(isset($_POST['submit'])) { $result = $cal->getresult($_POST['n1'],$_POST['n2'],$_POST['op']); } ?> <form method="post"> <table align="center"> <tr> <td><strong><?php echo $result; ?><strong></td> </tr> <tr> <td>Enter 1st Number</td> <td><input type="text" name="n1"></td> </tr> <tr> <td>Enter 2nd Number</td> <td><input type="text" name="n2"></td> </tr> <tr> <td>Select Oprator</td> <td><select name="op"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </select></td> </tr> <tr> <td></td> <td><input type="submit" name="submit" value=" = "></td> </tr> </table> </form> </tr> </th> </table>
How to Use in web-server (In Running Website):
Copy and paste above file in your notepade by giving name extension as filename.php
It is very simple to use in webserver, you just put your domain in browser such as
http://yourdomainname/cpanel
secondly, after giving password you go to file manager section and upload above code file there.
Thirdly in your browser you type this one
http://yourdomainname/filename.php
In this way you calculator will be open.
On the other hand if you do not have a website you should use in your personal computer. Just download wamp server from their website and paste this code in opening your C: drive as:
C << wamp <<<www
and paste your file there.
Then open your local host as
http://localhost/filename.php
I hope you will like this code, if you have question put in comment section.