Editing HTML based on $_GET - php

<?php
$g = $_GET['e'];
$t = "Title!";
$h = "";
$p = "";
function errorput($et,$eh,$ep) {
$t = $et;
$h = '<h1>'.$eh.'</h1>';
$p = '<p>'.$ep.'</p>';
}
if ($g == "nodata") {
errorput("Missing Something...", "Blank Field", "You left a box or few empty.");
} elseif ($g == "nopass") {
errorput("Password Incorrect!", "Encrypted Hash Unmatched", "Your password is probably wrong.");
} else {
errorput($t, "I have no idea.", "There was an error, but we don't know why.");
}
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $t ?></title>
<head>
<body>
<?php echo $h; echo $p; ?>
</body>
</html>
So, it outputs html based on what it receives via GET.
Why doesn't it work?

$t and others aren't in global scope. Return them.
<?php
$g = $_GET['e'];
$t = "Title!";
$h = "";
$p = "";
function errorput($et, $eh, $ep)
{
$t = $et;
$h = '<h1>' . $eh . '</h1>';
$p = '<p>' . $ep . '</p>';
return array(
$t,
$h,
$p
);
}
if ($g == "nodata") {
$errors = errorput("Missing Something...", "Blank Field", "You left a box or few empty.");
} elseif ($g == "nopass") {
$errors = errorput("Password Incorrect!", "Encrypted Hash Unmatched", "Your password is probably wrong.");
} else {
$errors = errorput($t, "I have no idea.", "There was an error, but we don't know why.");
}
?>
<!DOCTYPE html>
<html>
<head>
<title><?php
echo $errors[0];
?></title>
<head>
<body>
<?php
echo $errors[1] . $errors[2];
?>
</body>
</html>

You are trying to use variables from outside the function inside the function which won't work like you think it is.
Please read up on variable scope: http://php.net/manual/en/language.variables.scope.php
If you changed your function to have:
At the top this would work how you want it to but it is wrong.

Related

Trying to print an array using an interface and its subclasses (one function)

I have a problem with this PHP code, as I try to get an array into a function under a class implementing the interface, but it ended up showing an error saying that I haven't declared a called function.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<p>Back to selection php
<?php
interface employee
{
public function printout($wid, $arr);
}
class worker implements employee
{
public function printout($wid, $arr)
{
for ($i=0; $i<7; $i++) {
foreach ($arr[$wid][$i] as $val) {
echo "$val <br>";
}
}
}
}
$temp = new worker();
$id = "60800";
$warr = array();
$warr[$id][0] = "60800";
$warr[$id][1] = "Worker";
$warr[$id][2] = "Wang Mingchun";
$warr[$id][3] = "Day";
$warr[$id][4] = "NT$1000";
$warr[$id][5] = "N/A";
$warr[$id][6] = "N/A";
$temp = printout($id, $warr);
?>
</body>
</html>
I have solved, guys.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<p>Back to selection php
<br>
<h1>Employee List</h1>
<h2>KEY LEGEND BELOW</h2>
<h3>ID__,__position__,__name__,__shift(workers)__,__rate(workers)__,__salary(foremen)__,__bonus(foremen)</h3>
<?php
interface employee
{
public function printout($llid, $llarr);
}
class worker implements employee
{
private $i;
private $run = array();
public function printout($llid, $llarr)
{
for ($i=0; $i<7; $i++) {
echo ($llarr[$llid][$i]."__,__\t");
}
echo "<br>";
}
}
class supervisor implements employee
{
private $i;
private $run = array();
public function printout($llid, $llarr)
{
for ($i=0; $i<7; $i++) {
echo ($llarr[$llid][$i]."__,__\t");
}
echo "<br>";
}
}
//worker's part
$wtemp = new worker();
$id = "60800";
$warr = array();
$warr[$id][0] = "60800";
$warr[$id][1] = "Worker";
$warr[$id][2] = "Wang Mingchun";
$warr[$id][3] = "Day";
$warr[$id][4] = "NT$1000";
$warr[$id][5] = "n/a";
$warr[$id][6] = "n/a";
$wtemp->printout($id, $warr);
//supervisor's part
$stemp = new supervisor();
$id = "60800";
$sarr = array();
$sarr[$id][0] = "60800";
$sarr[$id][1] = "Worker";
$sarr[$id][2] = "Liu Tianhong";
$sarr[$id][3] = "n/a";
$sarr[$id][4] = "n/a";
$sarr[$id][5] = "NT$50000";
$sarr[$id][6] = "NT$10000";
$stemp->printout($id, $sarr);
?>
</body>
</html>

Submitting and retrieving cookies in PHP

We are making an voting system for our website. You can post reports to the website which are saved as data files.The current problem is that users can upvote or downvote as many times as they want because there is no barrier to stop the votes. What we want to happen is for users to be able to either upvote or downvote once.We are trying to use cookies to achieve this (not the best system, I know, since people can just clear cookies, but this is a small student project and we just need the system down). We are able to set cookies in the upvote and downvote script. We have a vote cookie which is either set to 0, -1, or 1, depending on whether the user upvoted or not.However, we are unable to retrieve the cookies accurately. When we try to retrieve the cookie vote using $_COOKIE["vote"] it doesn't give us a value.Is there any reason why this cookie is not returning a value? Thank you in advance. All of our code is provided below if you need it.
<?php
$report = $_GET["report"];
if(!isset($_COOKIE["vote"])) {
setcookie("vote", "0", time() + 315360000, $_SERVER['REQUEST_URI']);
$_COOKIE["vote"] = "0";
}
function upvote() {
if(file_exists("DataUploads/".$GLOBALS['report'])) {
if($_COOKIE["vote"] == "1") { // Problem: $_COOKIE is not being compared to "1" properly, always returns false
$filename = "DataUploads/".$GLOBALS['report'];
$line = 3;
$lines = file($filename, FILE_IGNORE_NEW_LINES);
$lines[$line] = (string)((int)$lines[$line] - 1);
file_put_contents($filename, implode("\n", $lines));
setcookie("vote", "0", time() + 315360000, $_SERVER['REQUEST_URI']);
$_COOKIE["vote"] = "0";
} else {
$filename = "DataUploads/".$GLOBALS['report'];
$line = 3;
$lines = file($filename, FILE_IGNORE_NEW_LINES);
if($_COOKIE["vote"] == "-1") {
$lines[$line] = (string)((int)$lines[$line] + 2);
} else {
$lines[$line] = (string)((int)$lines[$line] + 1);
}
file_put_contents($filename, implode("\n", $lines));
setcookie("vote", "1", time() + 315360000, $_SERVER['REQUEST_URI']);
$_COOKIE["vote"] = "1";
}
}
}
function downvote() {
if(file_exists("DataUploads/".$GLOBALS['report'])) {
if($_COOKIE["vote"] == "-1") {
$filename = "DataUploads/".$GLOBALS['report'];
$line = 3;
$lines = file($filename, FILE_IGNORE_NEW_LINES);
$lines[$line] = (string)((int)$lines[$line] + 1);
file_put_contents($filename, implode("\n", $lines));
setcookie("vote", "0", time() + 315360000, $_SERVER['REQUEST_URI']);
$_COOKIE["vote"] = "0";
} else {
$filename = "DataUploads/".$GLOBALS['report'];
$line = 3;
$lines = file($filename, FILE_IGNORE_NEW_LINES);
if($_COOKIE["vote"] == "1") {
$lines[$line] = (string)((int)$lines[$line] - 2);
} else {
$lines[$line] = (string)((int)$lines[$line] - 1);
}
file_put_contents($filename, implode("\n", $lines));
setcookie("vote", "-1", time() + 315360000, $_SERVER['REQUEST_URI']);
$_COOKIE["vote"] = "-1";
}
}
}
if($_POST["upvote_x"]) {
upvote();
}
if($_POST["downvote_x"]) {
downvote();
}
?>
<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<link rel="stylesheet" href="styles.css">
<title>View Report</title>
<link rel="icon" href="Images/favicon.ico" type="image/x-icon">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="header"></div>
<div id="navbar">
<ul>
<li>Home</li>
<li>About</li>
<li>Submit</li>
<li>View</li>
</ul>
</div>
<div id="content">
<ul style="list-style-type: none;">
<?php
if(file_exists("DataUploads/".$GLOBALS['report'])) { // Check if the report exists
echo '<h2>Report Information:</h2>';
$data = file("DataUploads/".$GLOBALS['report']); // Gets array of lines in file
$upvote_button_url = $_COOKIE["vote"] == "1"?"Images/upvote.png":"Images/upvote_noclick.png";
$downvote_button_url = $_COOKIE["vote"] == "-1"?"Images/downvote.png":"Images/downvote_noclick.png";
echo '<h3 style="display:inline">Votes: </h3><p style="display:inline" class="wordwrap">'.$data[3].'</p>';
if($data[4] == "demo") {
echo "<br>";
echo "This is a demonstrational report, and cannot be voted on.";
echo "<br>";
} else {
echo '<form method="post">';
echo '<input type="image" src="'.$upvote_button_url.'" name="upvote" id="upvote" value="Upvote" onclick="changeUpvoteImage()" /><br/>';
echo '<input type="image" src="'.$downvote_button_url.'" name="downvote" id="downvote" value="Downvote" onclick="changeDownvoteImage()" /><br/>';
echo '</form>';
echo '<p>If a report has or has less than -40 votes, it will be deleted.</p>';
}
if(file_exists('ImageUploads/'.pathinfo($GLOBALS['report'], PATHINFO_FILENAME))) {
echo '<li><img src="ImageUploads/'.$GLOBALS['report'].'" style="max-height: 600px; max-width: 700px"></li>';
} else {
echo '<img src="Images/missing.png" width="25%"><br>';
}
echo '<li><h3 style="display:inline">Location: </h3><p style="display:inline" class="wordwrap">'.htmlspecialchars($data[0]).'</p></li>';
echo '<li><h3 style="display:inline">Description: </h3><p style="display:inline" class="wordwrap">'.htmlspecialchars($data[1]).'</p></li>';
echo '<li><b><h3 style="display:inline">Urgency: </h3>';
if($data[2] < 30) {
echo "<span style='color: #1f7725'>Low</span>";
} else if($data[2] < 50) {
echo "<span style='color: #77711e'>Medium</span>";
} else if($data[2] < 80) {
echo "<span style='color: #774e1e'>High</span>";
} else {
echo "<span style='color: #771e1e'>Immediate</span>";
}
echo "</b></li>";
function delete() {
if(file_exists("DataUploads/".$GLOBALS['report'])) {
unlink("DataUploads/".$GLOBALS['report']); //delete file
}
if(file_exists("ImageUploads/".$GLOBALS['report'])) {
unlink("ImageUploads/".$GLOBALS['report']); //delete file
}
}
if($data[3] <= -40 && $data[4] != "demo") {
delete();
}
} else {
echo '<h1>No report found with the name "'.$GLOBALS['report'].'". Check the URL!</h1>';
echo '<img src="Images/missing-report.jpg" width="50%">';
}
?>
</ul>
<br>
<br>
<br>
</div>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function getCookieValue(a) {
var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
return b ? b.pop() : '';
}
function changeUpvoteImage() {
var img = document.getElementById("upvote");
img.src = "Images/upvote.png";
return false;
}
function changeDownvoteImage() {
var img = document.getElementById("downvote");
img.src = "Images/downvote.png";
return false;
}
if(getCookieValue(getUrlVars("report") + "vote") == 1) {
changeUpvoteImage();
} else if(getCookieValue(getUrlVars("report") + "vote") == -1) {
changeDownvoteImage();
}
</script>
<script>
if(window.history.replaceState) {
window.history.replaceState(null, null, window.location.href);
}
</script>
</body>
</html>
Use this to set the cookies:
setcookie("vote", "some_value", time() + (315360000 * 30), "/");
(This worked for me)

PHP PDO Pagination not refreshed

im quite new to PHP and im trying to make a pagination, the code works! but i need to click on the button twice to make the page refreshed/change. how do i fix this?
view/main/user/userlist.php
<?php
$_SESSION['pagelim'] = 10;
$_SESSION['page'] = $_GET['halaman'];
if ($_SESSION['page'] == '') {
$_SESSION['pos'] = 0;
$_SESSION['page'] = 1;
} else {
$_SESSION['pos'] = ($_SESSION['page']- 1) * $_SESSION['pagelim'];
}
$itemcount = listpetugas::getlisted();
$pagecount = ceil(listpetugas::getlisted()/$_SESSION['pagelim']);
for ($i=1;$i<=$pagecount;$i++)
{ ?>
<?php
if ($i!=$pagecount){
echo " <ul class='pagination'><li><a href='?controller=main&action=userlist&halaman=$i' onclick='myFunction()'>$i</a></li></ul>";?>
<?php }
else{
echo "$i";
} ?>
<?php } ?>
model/userdb.php
public static function listemup()
{
if ($_SESSION['pos'] =='' && $_SESSION['pagelim'])
{
$pos = 0;
$lim = 10;
}
else {
$pos = $_SESSION['pos'];
$lim = $_SESSION['pagelim'];
}
$list = [];
$db = FirstFire::StartConnection();
$req = $db->query("SELECT * FROM randomity LIMIT $pos,$lim");
$rowcount = $req->rowCount();
foreach ($req->fetchAll() as $post) {
$list[] = new listpetugas($post['name'],$post['email'],$post['adress'],$post['wow']);
}
return $list;
}
JS
<script>
function myFunction() {
location.reload();
}
</script>
sorry for the messy code.

PHP Game won't recognize input from form, doesn't run switch-case statement

I have a text-based exploring game based off of HackingWithPHP that I'm working on, and my code just won't take input from the form I have for commands. It probably does take input, it's just that the PHP I have doesn't recognize it. Another problem is that the switch ($command) { statement that I have doesn't seem to run. It just skips over the entire thing. I can't figure out what's going on. Any help would be greatly appreciated.
Code:
index.php (I have this as a .php file so the $input variable can be passed from this file to game.php)
<html>
<head>
<title>Urban Adventure</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<div class="main">
<?php
include_once 'game.php';
?>
<FORM NAME ="form1" METHOD ="POST" ACTION = "">
<INPUT TYPE = "TEXT" VALUE ="" name="input" style="width: 600; position: absolute; bottom: 0; z-index: 2;">
</FORM>
</div>
<?php
$input = $_POST["input"];
?>
</div>
</body>
</html>
game.php:
<?php
include_once 'index.php';
print($input);
$World = simplexml_load_file("gameworld.xml");
$CurrentPos = 0;
$Done = 0;
print "<br>";
printplace();
function printplace() {
GLOBAL $World, $CurrentPos;
$Room = $World->ROOM[$CurrentPos];
$Name = $Room->NAME;
$Desc = wordwrap((string)$Room->DESC);
print "$Name<br>";
print str_repeat('-', strlen($Name));
print "<br>$Desc<br>";
if ((string)$Room->NORTH != '-') {
$index = (int)$Room->NORTH;
print "North: {$World->ROOM[$index]->NAME}<br>";
}
if ((string)$Room->SOUTH != '-') {
$index = (int)$Room->SOUTH;
print "South: {$World->ROOM[$index]->NAME}<br>";
}
if ((string)$World->ROOM[$CurrentPos]->WEST != '-') {
$index = (int)$Room->WEST;
print "West: {$World->ROOM[$index]->NAME}<br>";
}
if ((string)$World->ROOM[$CurrentPos]->EAST != '-') {
$index = (int)$Room->EAST;
print "East: {$World->ROOM[$index]->NAME}<br>";
}
print "<br>";
}
$input = explode(' ', $input);
print "<br>";
foreach ($input as $command) {
switch ($command) {
case 'north':
if ((string)$World->ROOM[$CurrentPos]->NORTH != '-') {
$CurrentPos = (int)$World->ROOM[$CurrentPos]->NORTH;
printplace() ;
} else {
print "You cannot go north!<br>";
}
break;
case 'south':
if ((string)$World->ROOM[$CurrentPos]->SOUTH != '-') {
$CurrentPos = (int)$World->ROOM[$CurrentPos]->SOUTH;
printplace() ;
} else {
print "You cannot go south!<br>";
}
break;
case 'west':
if ((string)$World->ROOM[$CurrentPos]->WEST != '-') {
$CurrentPos = (int)$World->ROOM[$CurrentPos]->WEST;
printplace() ;
} else {
print "You cannot go west!<br>";
}
break;
case 'east':
if ((string)$World->ROOM[$CurrentPos]->EAST != '-') {
$CurrentPos = (int)$World->ROOM[$CurrentPos]->EAST;
printplace() ;
} else {
print "You cannot go east!<br>";
}
break;
case 'look':
printplace() ;
break;
default:
print "not a valid command... <br>";
break;
}
}
print "<br>Thanks for playing!<br>";
?>
What happens is that the input doesn't work, the switch-case statement doesn't work, and the print "<br>Thanks for playing!<br>"; runs before the switch-case statement. Sorry if I can't describe this correctly. You might want to check out the real thing here: urbanadventure.dumpong.tk . You'll be able to see the real bugs going on there.
move
<?php $input = $_POST["input"]; ?>
above the include - although there are other issues here

How to write poll data to a text file? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Im trying to make a poll in php. Im trying to gather data by writing the info to a txt file. How do I get the code to write the data to a txt file?
This all the code I have in my handler, how do I make it write to my txt file. Most of the stuff at the bottom doesn't matter yet. Try to look at the code that say if ($submit == 'submit') and what follows that.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Poll</title>
</head>
<body>
<?php
//no need for sport validation is unimportant and doesnt work
if (isset($_REQUEST['Soda'])) {
$Soda = $_REQUEST['Soda'];
} else {
$Soda = NULL;
echo '<p class="error">You forgot to select your favorite soda!</p>';
}
//This is end of soda validation
if (!empty($_REQUEST['Book'])) {
$Book = $_REQUEST['Book'];
} else {
$Book = NULL;
echo '<p class="error">You forgot to write in your favorite book!</p>';
}
//End of book validation
if (isset($_REQUEST['SOTU'])) {
$SOTU = $_REQUEST['SOTU'];
} else {
$SOTU = NULL;
echo '<p class="error">You forgot to select the two biggest issues of the state of the union address!</p>';
}
//End of SOTU validation
if (isset($_REQUEST['Soda']) && !empty($_REQUEST['Book']) && isset($_REQUEST['SOTU'])) {
echo' Thank You for filling out the survey!<br> You can see the results of the pole' . " here!<br><br> Your response has been recorded.";
} else {
echo '<p class="error">Please go ' . "back" . ' and fill out the poll!<p>';
}
//End of link responses
//Define variables and make sure file works
$submit = $_REQUEST['submit'];
$filename = 'poll_data.txt';
$handle = fopen($filename, 'a');
//next is the stuff that is to be appended
if ($submit == 'Submit') {
fopen($filename, 'w');
$newdata = $Soda . PHP_EOL;
fwrite($handle, $newdata);
} else { echo 'You didn\'t click submit';}
//Now to sort the data and present it
/*explode('PHP.EOL', $filename);
$CC = 0;
$P = 0;
$MD = 0;
$SS = 0;
$BR = 0;
$DLS = 0;
$O = 0;
foreach($filename as $value) {
if ($value = 'Coca-Cola') {
$CC = $CC + 1;
}
elseif ($value = 'Pepsi') {
$P = $P + 1;
}
elseif ($value = 'MtnDew') {
$MD = $MD + 1;
}
elseif ($value ='Sprite/Sierra-Mist') {
$SS = $SS + 1;
}
elseif ('BigRed') {
$BR = $BR + 1;
}
elseif ('DontLikeSoda') {
$DLS = $DLS + 1;
}
elseif ('Other') {
$O = $O + 1;
}
}*/
?>
this should work:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Poll</title>
</head>
<body>
<?php
//no need for sport validation is unimportant and doesnt work
if (isset($_REQUEST['Soda'])) {
$Soda = $_REQUEST['Soda'];
} else {
$Soda = NULL;
echo '<p class="error">You forgot to select your favorite soda!</p>';
}
//This is end of soda validation
if (!empty($_REQUEST['Book'])) {
$Book = $_REQUEST['Book'];
} else {
$Book = NULL;
echo '<p class="error">You forgot to write in your favorite book!</p>';
}
//End of book validation
if (isset($_REQUEST['SOTU'])) {
$SOTU = $_REQUEST['SOTU'];
} else {
$SOTU = NULL;
echo '<p class="error">You forgot to select the two biggest issues of the state of the union address!</p>';
}
//End of SOTU validation
if (isset($_REQUEST['Soda']) && !empty($_REQUEST['Book']) && isset($_REQUEST['SOTU'])) {
echo' Thank You for filling out the survey!<br> You can see the results of the pole' . " here!<br><br> Your response has been recorded.";
} else {
echo '<p class="error">Please go ' . "back" . ' and fill out the poll!<p>';
}
//End of link responses
//Define variables and make sure file works
$submit = $_REQUEST['submit'];
$filename = 'poll_data.txt';
//next is the stuff that is to be appended
if ($submit == 'Submit') {
$handle = fopen($filename, 'a');
fputs($handle, $Soda.PHP_EOL);
fclose($handle);
} else { echo 'You didn\'t click submit';}
//Now to sort the data and present it
/*explode('PHP.EOL', $filename);
$CC = 0;
$P = 0;
$MD = 0;
$SS = 0;
$BR = 0;
$DLS = 0;
$O = 0;
foreach($filename as $value) {
if ($value = 'Coca-Cola') {
$CC = $CC + 1;
}
elseif ($value = 'Pepsi') {
$P = $P + 1;
}
elseif ($value = 'MtnDew') {
$MD = $MD + 1;
}
elseif ($value ='Sprite/Sierra-Mist') {
$SS = $SS + 1;
}
elseif ('BigRed') {
$BR = $BR + 1;
}
elseif ('DontLikeSoda') {
$DLS = $DLS + 1;
}
elseif ('Other') {
$O = $O + 1;
}
}*/
?>
I think if you use
fopen($filename, 'r');
that should work.
http://www.php.net/manual/en/function.fopen.php

Categories