I am new to php so can anyone tell me why when I open the HTML, it is not showing “5! is 120” as it should be and am instead getting:
Applications
", $num, "! is ", factorial ($num), ".
"; } else { echo "
Please enter a positive integer.
"; } echo "
Return to the Entry Page
"; ?>
PHP functions
<?php
function isPositiveInteger ($n) {
$result = false;
if (is_numeric($n))
if ($n == floor($n))
if ($n>0 )
$result = true;
return $result;
}
function factorial ($n) { // declare the factorial function
$result = 1; // declare and initialise the result variable
$factor = $n; // declare and initialise the factor variable
while ($factor > 1) { // loop to multiple all factors until 1
$result = $result * $factor;
$factor--; // next factor
} // Note that the factor 1 is not multiplied
return $result;
}
?>
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="product" />
<meta name="keywords" content="HTML5, tags" />
<meta name="author" content="Ib" />
<title>Product</title>
</head>
<body>
<?php
include ("mathfunctions.php");
?>
<h1> Applications </h1>
<?php
$num=5;
if (isPositiveInteger($num)) {
echo "<p>", $num, "! is ", factorial ($num), ".</p>";
} else {
echo "<p> Please enter a positive integer. </p>";
}
echo "<p> <a href='factorial.html'> Return to the Entry Page </a></p>";
?>
</body>
</html>
Related
Im trying to understand php a little better so Im making an application that converts different units. In my code I ask the user to enter a value for units of length, volume, and weight, then check a multiple checkboxes to convert what unit they want. I have everything working except for when I enter no input in a input box I get a warning A non-numeric value encountered in " ". So my question is how do I stop this warning from showing and just have it say you forgot to enter an input.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="convert_units2.php" method="POST">
<?php
//use from other php code
// require("form_functions.php");
//
// include("form_functions.php");
function generate_options_pulldown($options){
echo '<select name = "' . $options["title"] . '_unit">';
foreach($options["list"] as $opt){
echo '<option value="' . $opt . '">' . $opt . '</option>';
}
echo '</select>';
}
function generate_options_checkbox($options){
foreach($options["list"] as $opt){
echo '<lable><input type ="checkbox" name="'. $opt . '">' .$opt .'</label>';
}
}
function generate_conversion_form($units){
echo '<input type="text" size="10" name="' . $units["title"] . '_val"> ';
generate_options_pulldown($units);
echo "-->";
generate_options_checkbox($units);
}
//
$length_units = array("title"=>"length","list"=>array("meter","mm","cm","km"));
$volume_units = array("title"=>"volume","list"=>array("liter","oz","gallon"));
$weight_units = array("title"=>"weight","list"=>array("gram","mg","kg"));
if ($_SERVER["REQUEST_METHOD"] == "GET"){
generate_conversion_form($length_units);
echo "<p>";
generate_conversion_form($volume_units);
echo "<p>";
generate_conversion_form($weight_units);
echo '<p><input type="submit" value="Convert"></p>';
}
else{//Post
// var_dump($_POST);
$length_units_conversion_table = array("meter"=>1,"mm"=>1000,"cm"=>100,"km"=>0.001);
$from_unit = $_POST["length_unit"];
$val = $_POST["length_val"];
$meter = $val / $length_units_conversion_table[$from_unit];
foreach($length_units_conversion_table as $unit => $rate){
if(isset($_POST[$unit]) and $_POST[$unit] == 'on' )
printf("%s %s is %s %s<br>",$val, $from_unit,$meter * $rate, $unit);
}
echo '<br>';
$volumn_units_conversion_table = array("liter"=>1,"oz"=>33.8,"gallon"=>0.264);
$from_unit = $_POST["volume_unit"];
$val = $_POST["volume_val"];
$liter = $val / $volumn_units_conversion_table[$from_unit];
foreach($volumn_units_conversion_table as $unit => $rate){
if(isset($_POST[$unit]) and $_POST[$unit] == 'on' )
printf("%s %s is %s %s<br>",$val, $from_unit,$liter * $rate, $unit);
}
echo '<br>';
$weight_units_conversion_table = array("gram"=>1,"mg"=>1000,"kg"=>0.001);
$from_unit = $_POST["weight_unit"];
$val = $_POST["weight_val"];
$gram = $val / $weight_units_conversion_table[$from_unit];
foreach($weight_units_conversion_table as $unit => $rate){
if(isset($_POST[$unit]) and $_POST[$unit] == 'on' )
printf("%s %s is %s %s<br>",$val, $from_unit,$gram * $rate, $unit);
}
}
?>
</form>
</body>
</html>
you can check if the value is numeric using the function is_numeric() (https://www.php.net/manual/en/function.is-numeric.php)
if(!is_numeric($_POST["volume_val"])) { ...} )
For the specific case where no value has been set, you can either check that the value is not an empty string,
if( $_POST["volume_val"] == '') {...}
or convert an empty string to zero
$volume_val = empty($_POST["volume_val"]) ? 0 : $_POST["volume_val"];
For the empty field alert, you can use the required attribute in the input, so when you submit the form you'll get the "Field required" warning and the form won't submit.
Then, in the POST part of your code, you can test $_POST["length_unit"] for empty:
if (empty(trim($_POST["length_unit"])))
if this is true then ... you can either treat this as 0 or just send a warning.
You can also test for numeric value before processing:
if (is_numeric($_POST["length_unit"]))
I'm making something similar a captha, the not working part is the IF, under if(isset($_POST['submit'])), that always returns false. I think.
Tried a lot ways with no luck...
Anyway, I have followed this solution https://stackoverflow.com/a/21504949/4167976 without success.
Here is my test php and html:
<?php
session_start();
$char = "abcdefghijklmnopqrstuvwxyz1234567890";
$code = $char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)];
$_SESSION["testcode"] = $code;
echo $_SESSION["testcode"]."<br>"; // echo here only for testing
if(isset($_POST['submit'])) {
$code1 = mb_substr($_POST['fullcode'], 0, 5);
$code2 = mb_substr($_POST['fullcode'], -6);
if ($code2 == $_SESSION["testcode"])
{echo "The code is correct!";}
else
{echo "Wrong code!";}
// unset($_SESSION['testcode']); // ???
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="fullcode">
<input type="Submit" name="submit" value="Submit!">
</form>
</body>
</html>
Please, tell me what and where I'm wrong... Thanks! :)
EDIT:
<?php
session_start();
if (!isset($_SESSION["testcode"])) {
$char = "abcdefghijklmnopqrstuvwxyz1234567890";
$code = $char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)];
$_SESSION["testcode"] = $code;
}
if(isset($_POST['submit'])) {
$code1 = mb_substr($_POST['fullcode'], 0, 5);
$code2 = mb_substr($_POST['fullcode'], -6);
if ($code2 === $_SESSION["testcode"])
{echo "The code is correct!<br>";}
else
{echo "Wrong code!<br>";}
unset($_SESSION['testcode']);
$char = "abcdefghijklmnopqrstuvwxyz1234567890";
$code = $char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)];
$_SESSION["testcode"] = $code;
}
?>
Finally, get a new code IF the condition is false!
<?php
session_start();
// first request.
// if not set session 'testcode' and set it, else do nothing.
// prevent session be covered.
if (!isset($_SESSION["testcode"])) {
reFreshCode();
}
if(isset($_POST['submit'])) {
$code1 = mb_substr($_POST['fullcode'], 0, 5);
$code2 = mb_substr($_POST['fullcode'], -6);
if ($code2 == $_SESSION["testcode"])
echo "The code is correct!";
else {
// get a new code IF the condition is false!
echo "Wrong code!";
echo “new code:”.reFreshCode();
}
}
function reFreshCode() {
$char = "abcdefghijklmnopqrstuvwxyz1234567890";
$code = $char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)].$char[rand(0,35)];
return $_SESSION["testcode"] = $code;
}
I have an anonymous function that works when called directly. However, when I try to call it from another anonymous function, I get the error
Fatal error: Function name must be a string in ...(fileName)
Here is the complete code. Appreciate any thoughts on why this is failing.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<?php
$ringW = 16; $ringCx = 8;
$ringH = 16; $ringCy = 8; $ringR = 7;
$penWidth = 2;
$svgCircle = function ($fillColor, $ringColor)
use ($ringW, $ringH, $ringR, $ringCx, $ringCy, $penWidth) {
echo "<svg width=\"$ringW\" height=\"$ringH\">";
echo "<circle cx=\"$ringCx\" cy=\"$ringCy\" r=\"$ringR\" " .
"stroke=\"$ringColor\" stroke-width=\"$penWidth\" fill=\"$fillColor\" />\n";
echo "</svg>\n";
};
$pac = function ($condition) {
if ($condition)
// echo "Hello world\n"; // pass
$svgCircle("yellow", "green"); // fails
};
?>
<head>
<title>LVCC Algorithm</title>
</head>
<body>
<?php
$pac(1);
$svgCircle("yellow", "green"); // pass
$svgCircle("yellow", "green");
?>
</body>
</html>
You forgot to make $svgCircle available to your second function
$pac = function ($condition) use ($svgCircle) {...};
^^^^^^^^^^^^^^^^
Hi i am devloping sample site in php i need to translate whole website in to persian. how can it possible in php?? I have tried using the following code.. This code will working fine for deutsch conversion.
1. class.translation.php
<?php
class Translator {
private $language = 'en';
private $lang = array();
public function __construct($language){
$this->language = $language;
}
private function findString($str) {
if (array_key_exists($str, $this->lang[$this->language])) {
echo $this->lang[$this->language][$str];
return;
}
echo $str;
}
private function splitStrings($str) {
return explode('=',trim($str));
}
public function __($str) {
if (!array_key_exists($this->language, $this->lang)) {
if (file_exists($this->language.'.txt')) {
$strings = array_map(array($this,'splitStrings'),file($this->language.'.txt'));
foreach ($strings as $k => $v) {
$this->lang[$this->language][$v[0]] = $v[1];
}
return $this->findString($str);
}
else {
echo $str;
}
}
else {
return $this->findString($str);
}
}
}
?>
2.Register.php
<?php
require_once('class.translation.php');
if(isset($_GET['lang']))
$translate = new Translator($_GET['lang']);
else
$translate = new Translator('en');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title><?php $translate->__('CSS Registration Form'); ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15"/>
<link rel="stylesheet" type="text/css" href="css/default.css"/>
</head>
<body>
<form action="" class="register">
<h1><?php $translate->__('Registration'); ?><a class="flag_deutsch" title="deutsch" href="register1.php?lang=de"></a><a class="flag_english" title="english" href="register1.php"></a></h1>
<fieldset class="row1">
<legend><?php $translate->__('Account Details'); ?></legend>
<p>
<label><?php $translate->__('Email'); ?> *</label>
<input type="text"/>
<label><?php $translate->__('Repeat email'); ?> *</label>
<input type="text"/>
</p>
</fieldset>
<div><button class="button"><?php $translate->__('Register'); ?> »</button></div>
</form>
</body>
</html>
Is it possible to transilate to other laguages using this code?? I changed register1.php?lang=de to register1.php?lang=fa(persian).. But nothing hapens..anybody plese help
AS per me you can try this method.This method is already implemented in our system and it is working properly.
Make php file of each language and define all the variables and use those variables in pages.
for e.g
For english
english.php
$hello="Hello";
persian.php
$hello=html_entity_decode(htmlentities("سلام"));
Now use this variable to page like this.
your_page.php
<label><?php echo $hello; ?></label>
You have load specific language file as per get language variable from URL.
It is better that you have define this language variable into config file.
config.php
if(isset($_GET['lang']) && $_GET['lang']=='persian')
{
require_once('persian.php');
}
else
{
require_once('english.php');
}
If I were you, I'd do it like this:
/inc/lang/en.lang.php
define('_HELLO', 'Hello');
/inc/lang/fa.lang.php
define('_HELLO', 'سلام');
index.php
// $_SESSION['lang'] could be 'en', 'fa', etc.
require_once '/inc/lang/' . $_SESSION['lang'] . 'lang.php';
echo _HELLO;
Benchmark: Constants vs. Variables
Here you see why I offered using Constants not Variables:
const.php
echo memory_get_usage() . '<br>'; // output: 674,576
for ($i = 0; $i <= 10000; $i++) {
define($i, 'abc');
}
echo memory_get_usage() . '<br>'; // output: 994,784
var.php
echo memory_get_usage() . '<br>'; // output: 674,184
for ($i = 0; $i <= 10000; $i++) {
$$i = 'abc';
}
echo memory_get_usage() . '<br>'; // output: 2,485,176
original from #rbenmass :
try this:
function translate($q, $sl, $tl){
$res= file_get_contents("https://translate.googleapis.com/translate_a/single?client=gtx&ie=UTF-8&oe=UTF-8&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&sl=".$sl."&tl=".$tl."&hl=hl&q=".urlencode($q), $_SERVER['DOCUMENT_ROOT']."/transes.html");
$res=json_decode($res);
return $res[0][0][0];
}
//example--
echo translate("اسمي منتصر الصاوي", "ar", "en");
From an Perl trans script I extracted the following for 100% free php google translation this function:
See working demo on http://ogena.net
function translate($q, $sl, $tl){
if($s==$e || $s=='' || $e==''){
return $q;
}
else{
$res="";
$qqq=explode(".", $q);
if(count($qqq)<2){
#unlink($_SERVER['DOCUMENT_ROOT']."/transes.html");
copy("http://translate.googleapis.com/translate_a/single?client=gtx&ie=UTF-8&oe=UTF-8&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&sl=".$sl."&tl=".$tl."&hl=hl&q=".urlencode($q), $_SERVER['DOCUMENT_ROOT']."/transes.html");
if(file_exists($_SERVER['DOCUMENT_ROOT']."/transes.html")){
$dara=file_get_contents($_SERVER['DOCUMENT_ROOT']."/transes.html");
$f=explode("\"", $dara);
$res.= $f[1];
}
}
else{
for($i=0;$i<(count($qqq)-1);$i++){
if($qqq[$i]==' ' || $qqq[$i]==''){
}
else{
copy("http://translate.googleapis.com/translate_a/single?client=gtx&ie=UTF-8&oe=UTF-8&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&sl=".$s."&tl=".$e."&hl=hl&q=".urlencode($qqq[$i]), $_SERVER['DOCUMENT_ROOT']."/transes.html");
$dara=file_get_contents($_SERVER['DOCUMENT_ROOT']."/transes.html");
#unlink($_SERVER['DOCUMENT_ROOT']."/transes.html");
$f=explode("\"", $dara);
$res.= $f[1].". ";
}
}
}
return $res;
}
}
//sample usage
echo translate("Goede dag dames en heren", "nl", "en");
As i can read from the code, the translator class loads the translation data from en.txt file, if you want have 'fa' translation, just create fa.txt as copy of en.txt with all translations and edit and translate fa.txt to persian...
Hope it helps
#rbenmass
Thank You :-)
I think it have to be , because it runs good for me :
/*
original from #rbenmass :
function translate($q, $sl, $tl){
if($s==$e || $s=='' || $e==''){
return $q;
}
**/
function translate($q, $sl, $tl){
if($sl==$tl || $sl=='' || $tl==''){
return $q;
}
// ... //
I have the following code where I declare a PHP array variable and inside a function, I put some data into the array. I also display buttons mapped to each index of the array that will show the data in the PHP array for that index number.
When testing on a browser, I don't get the right answer. I checked the page source, it had code like data_array = ["<?php echo implode ('',Array); ?>"]; instead of the text from the Array.
What am I doing wrong and what should I do to get the correct output? (BTW, I tried to execute the same without declaring the function and it seemed to work, but I need a function for my work and can't take that approach).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
<html lang="en">
<head>
<title>Example</title>
<?php
$giant_says = array();
function display() {
global $giant_says;
$giant_says[] = "<a href='http://www.google.com'>Google</a>";
$giant_says[] = "Yahoo!";
$giant_says[] = "Bing";
echo "<div id='content'>";
echo $giant_says[0];
echo "</div><br><br>";
$i = 0;
while($i < count($giant_says)) {
echo "<input type='button' value='".$i."' onClick=\"addtext(".$i.");return false;\"";
$i += 1;
}
}
?>
<script type="text/javascript">
function addtext(index) {
giantSays = ["<?php echo implode ('","', $giant_says); ?>"];
document.getElementById('content').innerHTML = giantSays[index];
}
</script>
</head>
<body>
<?php
display();
?>
</body>
</html>
You have the order wrong, which is causing the implode() to compress an empty array. I also suggest using json_encode() instead of implode(). It exists for this type of thing - updated example below:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
<html lang="en">
<head>
<title>Example</title>
<?php
$giant_says = array();
function display(&$giant_says) {
// Calculate the array (referenced)
$giant_says[] = "<a href='http://www.google.com'>Google</a>";
$giant_says[] = "Yahoo!";
$giant_says[] = "Bing";
// Return the HTML, to display later
ob_start();
echo "<div id='content'>";
echo $giant_says[0];
echo "</div><br><br>";
$i = 0;
while($i < count($giant_says)) {
echo "<input type='button' value='".$i."' onClick=\"addtext(".$i.");return false;\">";
$i += 1;
}
$Return = ob_get_contents();
ob_end_clean();
return $Return;
}
$Display = display($giant_says);
?>
<script type="text/javascript">
function addtext(index) {
giantSays = <?php echo json_encode($giant_says); ?>;
document.getElementById('content').innerHTML = giantSays[index];
}
</script>
</head>
<body>
<?php
echo $Display;
?>
</body>
</html>
You're trying to implode the $giant_says array before you've filled it (you're calling display() after the implode when the call needs to happen before).
The problem is that you call the display method, that fills the content after the html part with the javascript is sended.
the html code is "like" making an "echo 'html'" from your php. Your html is already processed but the display method is not called. call the method before the html code.
Example:
<?php
$giant_says = array();
$giant_says[] = "<a href='http://www.google.com'>Google</a>";
$giant_says[] = "Yahoo!";
$giant_says[] = "Bing";
function display() {
global $giant_says;
echo '<div id="content">'.$giant_says[0]."</div><br><br>";
$i = 0;
while($i < count($giant_says)) {
echo "<input type='button' value='".$i."' onClick=\"addtext(".$i.");\" />";
$i += 1;
}
}
?>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
function addtext(index) {
giantSays = ["<?php echo implode ('","', $giant_says); ?>"];
document.getElementById('content').innerHTML = giantSays[index];
return false;
}
</script>
</head>
<body>
<?php display(); ?>
</body>
</html>