I'm a newbie here and probably my question has already been answered, but Andy Harris wrote a book (see post topic for name of book). I've enjoyed going through it, however I've got a question that I'd like to post here (I've reached out to him, but have not got a response). The code in question is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="EN" dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>petals.php</title>
<link rel = "stylesheet"
type = "text/css"
href = "petals.css" />
</head>
<body>
<h1>Petals Around the Rose</h1>
<?php
printGreeting();
printDice();
printForm();
//$numPetals = filter_input(INPUT_POST, "numPetals");
function printGreeting(){
global $numPetals;
$guess = filter_input(INPUT_POST, "guess");
$numPetals = filter_input(INPUT_POST, "numPetals");
if (!filter_has_var(INPUT_POST, "guess")){
print "<h3>Welcome to Petals Around the Rose</h3>";
} else if ($guess == $numPetals){
print "<h3>You Got It!</h3>";
} else {
print <<<HERE
<h3>from last try: </h3>
<p>
you guessed: $guess
</p>
<p>
-and the correct answer was: $numPetals petals around the rose
</p>
HERE;
} // end if
} // end printGreeting
function showDie($value){
print <<<HERE
<img src = "die$value.jpg"
height = "100"
width = "100"
alt = "die: $value" />
HERE;
} // end showDie
function printDice(){
global $numPetals;
print "<h3>New Roll:</h3> \n";
$numPetals = 0;
$die1 = rand(1,6);
$die2 = rand(1,6);
$die3 = rand(1,6);
$die4 = rand(1,6);
$die5 = rand(1,6);
print "<p> \n";
showDie($die1);
showDie($die2);
showDie($die3);
showDie($die4);
showDie($die5);
print "</p> \n";
calcNumPetals($die1);
calcNumPetals($die2);
calcNumPetals($die3);
calcNumPetals($die4);
calcNumPetals($die5);
} // end printDice
function calcNumPetals($value){
global $numPetals;
switch ($value) {
case 3:
$numPetals += 2;
break;
case 5:
$numPetals += 4;
break;
} // end switch
} // end calcNumPetals
function printForm(){
global $numPetals;
print <<<HERE
<h3>How many petals around the rose?</h3>
<form action = ""
method = "post">
<fieldset>
<input type = "text"
name = "guess"
value = "0" />
<input type = "hidden"
name = "numPetals"
value = "$numPetals" />
<br />
<input type = "submit" />
</fieldset>
</form>
<p>
<a href = "petalHelp.html">
give me a hint</a>
</p>
HERE;
} // end printForm
?>
</body>
</html>
He says in his book (p. 95 for those who have the text):
This function [printGreeting()] refers to both the $guess and
$numPetals variables. Since both may be needed by other functions,
they are defined in a global statement. Note that you can assign
global status to more than one variable in a single global command.
I don't see where they are defined in a global statement. Probably overthinking it, but any insight would be much appreciated.
the 'statement' global defines the variable as having a global scope even though it is in the function so anything referencing $numPetals will access the same value.
it's possible that you will add code later in the tutorial that uses the $numPetals variable outside of a function but this may be the first introduction of the concept of 'global' in the book which is why it was explained.
in PHP a variable doesn't necessarily have to be defined before it's used which may be the cause of the confusion.
Related
I have to apologize if this answer has already been answered before, I've looked for it and found something partially useful but nothing that answered my needs.
I'm new to PHP and I want to make a simple website with multilingual support. Translations are provided by specific arrays according to the page they are in. I will use a foreach loop to get the translation. User is allowed to change the default language with a select html tag. I am partially able to achieve this goal in this way:
Firstly, with a simple function I look for the browser language and set it as language fall-back:
function browser_lang() {
$rawLang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if($rawLang == 'it') {
$browserLang = 'it';
} else {
$browserLang = 'en';
}
return $browserLang;
}
In the index.php file I set the fall-back language in this way:
<?php
// Include the browser_lang() and other functions
if(isset($_POST['set_language'])) {
$lang = strip_bad_chars($_GET['lang']);
} else {
$lang = browser_lang();
}
?>
<html lang="<?php echo $lang; ?>">
Later in the html I added a form with some select tag that allows to select languages:
<form action="" method="post">
<select name="set_language" id="custom-lang">
<option value="it">Italiano</option>
<option value="en">English</option>
</select>
<input type="submit" name="input_language" value="Set Language">
</form>
When I load the page for the first time, the script is able to retrieve the browser language, but when I select a custom language, it is not able to change it.
How can I add ?lang=en or ?lang=it at the end of the url in order to use $_GET['lang'] and loop through translations with the $lang variable set with that select form?
The entire index.php, included the external resources, is:
<?php
function browser_lang() {
$rawLang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if($rawLang == 'it') {
$browserLang = 'it';
} else {
$browserLang = 'en';
}
return $browserLang;
}
function strip_bad_chars( $input ) {
$output = preg_replace( "/[^a-zA-Z0-9_-]/", "",$input);
return $output;
}
if(isset($_POST['set_language'])) {
$lang = strip_bad_chars($_GET['lang']);
} else {
$lang = browser_lang();
}
?>
<!DOCTYPE html>
<html lang="<?php echo $lang; ?>">
<head>
<title>HOME</title>
</head>
<body>
<form action="" method="post">
<select name="set_language" id="custom-lang">
<option value="it">Italiano</option>
<option value="en">English</option>
</select>
<input type="submit" name="input_language" value="Set Language">
</form>
</body>
</html>
If you want the lang parameter in the URL (which I think makes sense) you can just change your form a bit:
<form action="" method="get"><!-- use get instead of post-->
<select name="lang" id="custom-lang"><!-- change name to lang-->
... etc.
This way, when the form is submitted, you will have ?lang=en or ?lang=it in the URL, and you can use
if (isset($_GET['lang'])) {
$lang = strip_bad_chars($_GET['lang']);
} else {
$lang = browser_lang();
}
to set your language.
You seem to have several problems:
You're mixing the submission methods (Using both POST and GET)
You check for $_POST['set_language'] but expect $_GET['lang']
The <select> menu is named differently to the variable you wish to use in the <html> tag's lang attribute.
What I'd do is settle on a method; POST or GET then change all ref's to GET/POST respectively, and then use either "set_language" or "lang" as your superglobal ($_GET/$_POST) array key.
Try this
<?php
// Include the browser_lang() and other functions
if(isset($_POST['input_language'])) {
$lang1 = $_POST['set_language'];
if ($lang1 == "Italiano") {
$lang = "it"
} else {
echo "en";
}
}
?>
<html lang="<?php echo $lang; ?>">
I am new to PHP and currently I am using php to create four different conference tables that have some hard-coded data in for now and I am trying to make any of the rows within the four tables selectable and eventually I will save the rows selected into a database, but for now I just can't figure out a way to make the rows selectable using PHP. Below is the current code that displays the four tables on my localhost. If this is not possible with PHP how would I incorporate another language within a php file to make the rows selectable. Thank you all for your help in advance.
Conference Class:
<?php
class Conference
{
protected $teams;
function loadTeams($teams)
{
$this->teams = $teams;
}
function getTeams()
{
return $this->teams;
}
}
?>
Main code:
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>') ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>User selection page</title>
<link rel="stylesheet" href="gameViewStyleSheet.css" type="text/css" />
</head>
<?php
require_once('Conference.php');
for ($j = 0; $j<4; $j++)
{
$loadGameClass = new Conference();
$loadGameClass->loadTeams(array("(1)Gonzaga vs (16)Southern U", "(8)Pittsburgh vs (9)Wichita St", "(5)Wisconsin vs (12)Ole Miss", "(4)Kansas st vs (13)Boise St", "(6)Arizona vs (11)Belmont", "(3)New Mexico vs (14) Harvard", "(7)Notre Dame vs (10)Iowa St", "(2)Ohio St vs (15) Iona"));
$teams = $loadGameClass->getTeams();
echo '<table border="1" align="center">';
switch ($j) {
case 0:
echo "Midwest";
break;
case 1:
echo "West";
break;
case 2:
echo "South";
break;
case 3:
echo "East";
break;
}
for ($i = 0; $i < 8; $i++)
{
$games = $teams[$i];
echo '<tr><td>'.$games.'</td><tr>';
}
echo '</table>';
echo "<br>" . "<br>";
}
?>
<body>
</body>
</html>
If you're talking "selectable" as in front-end interactivity in your browser, that cannot be done with PHP. You need to use JavaScript.
If you just want a link that would tag something as "selected" with a page load and a session value, you could do small form submits for each select/deselect action, and highlight the appropriate rows.
side note: <br> is invalid in XHTML - you need to use <br />
So I downloaded and edited a script off the internet to pull an image and find out the hex values it contains and their percentages:
The script is here:
<?php
$delta = 5;
$reduce_brightness = true;
$reduce_gradients = true;
$num_results = 5;
include_once("colors.inc.php");
$ex=new GetMostCommonColors();
?>
<!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" lang="en" xml:lang="en">
<head>
<title>Colour Verification</title>
</head>
<body>
<div id="wrap">
<img src="http://www.image.come/image.png" alt="test image" />
<?php
$colors=$ex->Get_Color("http://www.image.come/image.png", $num_results, $reduce_brightness, $reduce_gradients, $delta);
$success = true;
foreach ( $colors as $hex => $count ) {
if ($hex !== 'e6af23') {$success = false; }
if ($hex == 'e6af23' && $count > 0.05) {$success = true; break;}
}
if ($success == true) { echo "This is the correct colour. Success!"; } else { echo "This is NOT the correct colour. Failure!"; }
?>
</div>
</body>
</html>
Here is a pastebin link to the file colors.inc.php
http://pastebin.com/phUe5Pad
Now the script works absolutely fine if I use an image that is on the server, eg use /image.png in the Get_Color function. However, if I try and use an image from another website including a http://www.site.com/image.png then the script no longer works and this error appears:
Warning: Invalid argument supplied for foreach() in ... on line 22
Is anyone able to see a way that I would be able to hotlink to images because this was the whole point of using the script!
You must download a file to the server and pass its full filename to the method Get_Color($img) as $img parameter.
So, you need to investigate another SO question: Download File to server from URL
The error indicates that the value returned by Get_Color is not a valid object that can be iterated on, probably not a collection. You need to know how the Get_Color works internally and what is returned when it doesn't get what it wants.
In the mean-time, you can download [with PHP] the image from the external url into your site, and into the required folder and read the image from there.
$image = "http://www.image.come/image.png";
download($image, 'folderName'); //your custom function
dnld_image_name = getNameOfImage();
$colors=$ex->Get_Color("/foldername/dnld_image_name.png");
By the way, did you confirm that the image url was correct?
I am trying to capture the contents of my php page using output buffering:
<?php
function connect() {
$dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
session_start();
if(isset($_SESSION['username'])){
if(isset($_POST['entryId'])){
//do something
$dbh = connect();
$ide = $_POST['entryId'];
$usertab = $_POST['usertable'];
$answertable = $usertab . "Answers";
$entrytable = $usertab . "Entries";
$query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());
if($query){
//set variables
$sectionOne = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$sectionOne[] = $row;
}
}else{
//error - sql failed
}
}
?>
<?php
ob_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#export").click(function(e){
//post to html2pdfconverter.php
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
$("#nm").val("Entry Report.pdf");
$("form#sendanswers").submit();
});
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
<form id = "sendanswers" name = "sendanswers" action="html2pdfconverter.php" method="post">
<input type = "hidden" name = "link" id = "link" value = "">
<input type = "hidden" name = "nm" id = "nm" value = "">
<input type = "button" name = "export" id = "export" value = "Export As PDF"/>
</form>
</div>
<h3>Biological Information</h3>
<?php
echo('<p>');
$i = 0;
foreach($sectionOne as &$value){
if($i == 1 || $i == 3){
$image = "assets/urine".$i.".png";
echo("<br/>");
echo($value['question']." <br/> "."<img src = \"$image\"/>");
echo("<br/>");
}else{
echo($value['question'].' : '.$value['answer']);
}
echo("<br/>");
$i++;
}
echo('</p>');
?>
</body>
</html>
<?php
}
$contents = ob_get_contents(); //THIS WORKS
ob_end();
?>
I assign the contents of ob to $contents using ob_get_contents(); This works, and echoing $contents duplicates the html page.
However, in my jQuery, I am trying to assign this to a hidden text field ('link') using:
$("#link").val("<?php echo($contents); ?>");
This doesn't work however..And I have a feeling its because I am accessing $contents too eraly but not too sure...any ideas?
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
at the point you do that ob_get_contents call, you've only output about 10 lines of javascript and html. PHP will NOT reach back in time and magically fill in the rest of the document where you do this ob_get_contents().
You're basically ripping the page out of the laser printer the moment the page starts emerging, while the printer is still printing the bottom half of the page.
I fail to see why you want to embed the contents of your page into an input field. If you want to somehow cache the page's content in an input field, you can just use JS to grab the .innerHTML of $('body').
Well, you have two problems.
The first is what you suspect. You can't access that stuff until later. The second problem which you may not realize is that you will have quoting issues in JavaScript even if you manage to find a way to reorder this and make it work. It's recursive, in a bad way.
What you should do instead is change your $('#export').click handler to do an Ajax call, render the HTML you need to appear in the link on the server in a separate PHP script (no output buffering necessary) and then have your code inject the result of that call into the page the way you're trying to do in your click handler now.
I know in php you can embed variables inside variables, like:
<? $var1 = "I\'m including {$var2} in this variable.."; ?>
But I was wondering how, and if it was possible to include a function inside a variable.
I know I could just write:
<?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
But what if I have a long variable for output, and I don't want to do this every time, or I want to use multiple functions:
<?php
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
There is <b>alot</b> of text and html here... but I want some <i>functions</i>!
-somefunc() doesn't work
-{somefunc()} doesn't work
-$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string
-more non-working: ${somefunc()}
</body>
</html>
EOF;
?>
Or I want dynamic changes in that load of code:
<?
function somefunc($stuff) {
$output = "my bold text <b>{$stuff}</b>.";
return $output;
}
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
somefunc("is awesome!")
somefunc("is actually not so awesome..")
because somefunc("won\'t work due to my problem.")
</body>
</html>
EOF;
?>
Well?
Function calls within strings are supported since PHP5 by having a variable containing the name of the function to call:
<?
function somefunc($stuff)
{
$output = "<b>{$stuff}</b>";
return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>
will output "foo <b>bar</b> baz".
I find it easier however (and this works in PHP4) to either just call the function outside of the string:
<?
echo "foo " . somefunc("bar") . " baz";
?>
or assign to a temporary variable:
<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>
"bla bla bla".function("blub")." and on it goes"
Expanding a bit on what Jason W said:
I find it easier however (and this works in PHP4) to either just call the
function outside of the string:
<?
echo "foo " . somefunc("bar") . " baz";
?>
You can also just embed this function call directly in your html, like:
<?
function get_date() {
$date = `date`;
return $date;
}
function page_title() {
$title = "Today's date is: ". get_date() ."!";
echo "$title";
}
function page_body() {
$body = "Hello";
$body = ", World!";
$body = "\n\n";
$body = "Today is: " . get_date() . "\n";
}
?>
<html>
<head>
<title><? page_title(); ?></title>
</head>
<body>
<? page_body(); ?>
</body>
</html>