PHP Echoing strange characters - php

The program gets 5 variables from 2 database tables and compares them to each other. Each correct match increments a correct variable.
I should be getting a number like "100%" but instead get "�%" and "?%" etc. or just random characters.
See below extract from the HTML page
<!DOCTYPE html>
<html xmlns="w3.org/1999/xhtml"; xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<?php
$user = $_SESSION['currentUser'];
$answerCheck1 = mysqli_query($conn,"SELECT * FROM tutorial_exam");
$answerRowCheck1 = mysqli_fetch_array($answerCheck1);
$answerCheck2 = mysqli_query($conn,"SELECT * FROM tutorials_test WHERE user_id='$user'");
$answerRowCheck2 = mysqli_fetch_array($answerCheck2);
$answerCheckT = mysqli_query($conn,"SELECT * FROM tutorials WHERE user_id='$user'");
$answerRowCheckT = mysqli_fetch_array($answerCheckT);
$total = $answerRowCheckT['exam'];
if($total > 0){$total = $total ."%";}else{$total = '';}
$counter1 = 1;
$correct1 = 0;
$userAnswer1 = '';
$databaseAnswer1 = '';
while($counter1 <= 5)
{
$index1 = 'q'.$counter1;
$userAnswer1 = $answerRowCheck2[$index1];
$databaseAnswer1 = $answerRowCheck1[$index1];
if($userAnswer1 == $databaseAnswer1)
{
$correct1 = $correct1 + 1;
//$correct = $answerRow[$counter];
}
$counter1 = $counter1 + 1;
}
$mark1 = $correct1 / 5 * 100;
$mark1 = round($mark1,0);
echo $mark1 . "%";
?>
</body>
</html>

Just a suggestion, try adding this in the <head> section of your page:
<meta charset="utf-8">

We run our system from memory sticks with Server2Go, and what seems to have fixed it is updating the PHP version on the server2Go systems.
We found out how to do that in another Stack Overflow thread: Other answer link

Related

Very strange occurence mysql php blog

Ok so the problem I'm having is very strange. I have a blog website that displays a list of posts, and i made a system to select only 10 posts at a time. and yet on the second generated page 12 results are shown (the last 2 are duplicates)
//removed url because problem solved and i dont want to get sql injected
if you goto my project above and look at the second page of posts 12 entry's are shown with the last 2 being duplicates of the 3rd(and last) page...what is going on?! they should not be able to appear because the sql LIMIT function should restrict the displayed posts to 10.
here is the code for mainpage .php
<?php
session_start();
ob_start();
if ($_SERVER["REQUEST_METHOD"] == "POST"){//this works in my tests.
$low = 0;
$high = 10; //this loop/if method works in conjunction with the code at the bottom of this page
$e = 1;//starts at 1 because 1 itself is defined my default at the bottom of the page
while($_SESSION['i'] != $e){
$e++;
if (isset($_REQUEST["p$e"])){
$u = 1;
while($u != $e){
$u++;
$low = $low + 10;
$high = $high +10;
}
}
}}else{
$low = 0;
$high = 10;
}
?>
<!doctype html>
<!-- AUTHOR:JOSH FAIRBANKS -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home Page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<nav>
<ul>
<li><div id = "new">Create new post</div></li>
<li><div id = "veiw">Veiw posts</div></li>
</ul>
</nav>
<main>
<?php
$link = mysqli_connect( 'localhost', 'username', 'password' );
mysqli_select_db( $link, 'mydatabasename' );
$results = mysqli_query( $link, "SELECT LEFT(post, 575) as post FROM Users where verified = 1 ORDER BY `id` DESC LIMIT $low , $high" ); //this displayes all the posts that have been verified
while( $record = mysqli_fetch_assoc( $results ) ) {
$post = $record['post'];
$count = mysqli_affected_rows( $link );
//ORDER BY YEAR(Date) DESC, MONTH(Date) DESC, DAY(DATE) DESC
$post .= "</td></tr></table>";
print $post;
}
$vresults = mysqli_query( $link, "SELECT post FROM Users where verified = 1" );
while( $vrecord = mysqli_fetch_assoc( $vresults ) ) {
$vpost = $vrecord['post'];
$vcount = mysqli_affected_rows( $link );
$_SESSION['vcount'] = $vcount;
//
//these mirror variables arent seen and just are used to count the total amount of posts
//not just the ones on the page
}
mysqli_free_result( $results );
mysqli_close( $link );
?>
<form method = "post" action = "mainPage.php">
<table>
<tr><td>Page Number: </td><!--<td><input type = "submit" name = "p1" value = "1"></td>-->
<?php
$i = 0;
print "displaying low: $low high: $high";
for($j = 0; $j < $vcount; $j++) //modulus
{
if($j % 10 == 0)
{
$i++;
$_SESSION['i'] = $i;
print "<td><input type = 'submit' name ='"."p".$i. "' value = '$i'></td>";
}
}
?>
</tr>
</table>
</form>
</main>
</body>
</html>
I know this code is a bit of a mess :p but i swear it works except for this frustrating issue. any and all help appreciated.
I guess your problem at $high variable... Records per page always constant. But seems that you are increment in one place.
if ($_SERVER["REQUEST_METHOD"] == "POST"){//this works in my tests.
$low = 0;
$high = 10; //this loop/if method works in conjunction with the code at the bottom of this page
$e = 1;//starts at 1 because 1 itself is defined my default at the bottom of the page
while($_SESSION['i'] != $e){
$e++;
if (isset($_REQUEST["p$e"])){
$u = 1;
while($u != $e){
$u++;
$low = $low + 10;
$high = 10;
}
}
}}else{
$low = 0;
$high = 10;
}
?>

My countdown doesnt start on my betting site

I have a csgo betting site, when atleast 2 players deposit their skins into the site it the game starts and it takes 2 minutes until the the bot picks a winner.
Everything works fine, the game starts, a winner is picked 2 minutes after the game started, but the countdown text that are supposed to display the seconds left is not working.
this is my code Time left: <h4 id="countdown-timer"><span id="timeleft">0</span></h4>
Accepted trade offer #1211760373 by XXXXXXX (XXXXXXXXXXXXXX)
Current Players: 1
Accepted trade offer #1211760308 by XXXXXXXXX (XXXXXXXXXXXXXXX)
Current Players: 2
Found 2 Players
and that is what the bot says
and this is the timeleft.php http://prnt.sc/b03ute
PHP Code
<?php
#include_once ("set.php");
$game = fetchinfo("value", "info", "name", "current_game");
$r = fetchinfo("starttime", "games", "id", $game);
$somebodywon = fetchinfo("winner", "games", "id", $game);
if ($r == 2147483647)
die("120");
$r += 120 - time();
if ($r < 0) {
$r = 0; /* if(empty($somebodywon)) include_once('getwinner34634f.php'); */
} echo $r;
?>
Found this one aswell, called ssetimeleft.php
<
?php
#include_once ("set.php");
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
/**
* Constructs the SSE data format and flushes that data to the client.
*
* #param string $id Timestamp/id of this connection.
* #param string $msg Line of text that should be transmitted.
*/
function sendMsg($id, $msg) {
echo "id: $id" . PHP_EOL;
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
while (1) {
$game = fetchinfo("value","info","name","current_game");
$r = fetchinfo("starttime","games","id",$game);
if($r == 2147483647){
$var=120;
}else{
$var = $r += 120-time();
if($r < 0)
{
$var = 0;
/*if(empty($somebodywon))
include_once('getwinner34634f.php');*/
}
}
sendMsg(time(),$var);
usleep(500000); //1000000 = 1 seconds
}
?>
It's difficult to see what you are trying to do here without more information but the time() function in your PHP file runs only when the server-side PHP processor processes this file. The countdown display, however, is something that should be handled client side.
I recommend adding a javascript or jQuery file to handle the countdown display for you.
Try this its a very basic example :
$(function() {
var time_out = 10;
var timeout = setInterval(calculate, 1000);
function calculate() {
$('#timeleft').text(time_out--);
if (time_out < 0) {
clearInterval(timeout);
}
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h4 id="countdown-timer"><span id="timeleft">0</span></h4>
</body>
</html>

I don't get all the data from mysql - PHP

I've been searching for this for while but didn't find anything related.
So my problem is that I do get all the data from mysql with while(). However, all the articles I am trying to get displays as only 1 article even though the content is different. Sorry, it's not easy to explain that but see pictures below:
My database:
How it is displayed:
my articlesFunction.php code:
// check if user is logged in to view the content:
if(!isset($_SESSION['loggedin']) && !isset($_SESSION['loggedinAdmin'])){
header("Location: login.php");
}else{
}
//
$sql = "SELECT * FROM `articles` ORDER BY id DESC";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle = 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
//
my articles.php:
<?php
///////////////////////////////////////////////////////////////////////////////////////
// UNFINISHED //
///////////////////////////////////////////////////////////////////////////////////////
session_start();
require_once 'connect.php';
include 'articlesFunction.php';
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blog posts</title>
<link rel="stylesheet" href="css/articles.css">
</head>
<body>
<div id="bannerDiv" style="background-image: url(images/banner.jpg); background-size: 100% 100%; height:150px;">
<h2 id="bannerTitle"><u><i>Articles about travel that everyone loves...</i></u></h2>
<p>Homepage</p>
<span id="BannerMenu"><?php echo 'logged in as: '.$_SESSION['username'].' ';?></span><button>Logout</button>
</div>
<div id="container">
<div id="articles">
<div id="Display Articles">
<h1><u>Our set of articles:</u>
</h1>
<div id="display">
<?php
echo $fullArticle;
?>
</div>
</div>
</div>
</div>
</body>
</html>
So, I hope you understand my issue now. First, in this example, when I put it alone in the div, I only get the oldest article and I get only 1. If I add a while to the div, It gives me the results in the picture above:
So, how can I display the articles (all of them) and each one to be different as they are in the database.
You are overwriting your variable on every iteration of the while loop.
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle = 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}
so as a simple example
$a = 0;
$b = 3;
while($a < $b){
$output = $a;
$a++;
}
echo $output;
This gives back 2 because $output is being over written every-time. There are two approaches to keeping all the values.
Option one, concatenate the variable
$a = 0;
$b = 3;
$output = '';
while($a < $b){
$output .= $a;
$a++;
}
echo $output;
Which will output 012. We have to define the variable before using it with the .=. With the .= it is trying to concatenate the value first so it must already exist.
Option two, store the values in an array
$a = 0;
$b = 3;
while($a < $b){
$output[] = $a;
$a++;
}
print_r($output);
This will output:
Array
(
[0] => 0
[1] => 1
[2] => 2
)
This way is a bit more work because when you want to access it later you have to re-iterate through it. However it can be better if you want to be able to access each data point separately.
foreach($output as $value) {
echo $value;
}
Also note if users are providing their usernames, article name, or description and you aren't filtering that this will open you to XSS injections.
https://en.wikipedia.org/wiki/Cross-site_scripting
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#A_Positive_XSS_Prevention_Model
Usage in your actual code would be:
$sql = "SELECT * FROM `articles` ORDER BY id DESC";
$result = mysql_query($sql);
$fullArticle = '';
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle .= 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
This should be your code, in order to avoid the errors you mentioned in the comments;
//init fullname variable
$fullArticle = '';
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle .= 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
//

check login and sessions

I'm making API to simple forum ,, Now trying to check Login with php
on the control page : showForums.php
<?php require_once('session.php');?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TheForums</title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('fourmsAPI.php');
/*
function tinyf_forums_get($extra ='')
{
global $tf_handle;
$query = sprintf("SELECT * FROM `forums` %s",$extra );
$qresult = mysqli_query($tf_handle, $query);
if (!$qresult)
return NULL;
$recount = mysqli_num_rows($qresult);
if ($recount == 0)
return NULL ;
$forums = array();
for($i = 0 ; $i < $recount ; $i++)
$users[count($forums)] = mysqli_fetch_object($qresult);
//mysql_free_result($qresult);
return $forums;
}
*/
$forums = tinyf_forums_get();
if($forums == NULL)
{
die('problem');
}
$fcount = count($forums);
if($fcount == 0)
{
die('No Forums ');
}
if($_SESSION['user_info'] == false){
echo 'Login!';
}
else{
$uname = $_SESSION['user_info']->name ;
echo ''.$uname.' -- Logout!'.'' ;
}
?>
<br/>
<ul type = "square">
<?php
for($i = 0 ; $i < $fcount ; $i++)
{
$forum = $forums[$i];
echo "<li><a href = \"forum.php?id=$forum->id\"> $forum->title <a/> <br/> $forum->desc --";
if($_SESSION['user_info']->isadmin ==1){
echo " <a href = \"deleteForum.php?id=$forum->id\"> Delete <a/> | <a href = \"modifyForum.php?id=$forum->id\"> edit <a/> " ;
}
echo "<br/> </li>"; //$array ->
}
?>
</ul>
</body>
</html>
Error: Trying to get property of non-object in /var/www/html/tinyforum/showForums.php on line 62
session.php
<?php
session_start();
if(!isset($_SESSION['user_info'])){
$_SESSION['user_info'] = false ;
}
?>
i expected the if statement won't be executed
The if statement check has to execute if the loop executes. The inside part does not execute as you expected. The error you're getting is from the condition check. If the user is not logged in, your code is equivalent to
if(null->isadmin ==1){
echo " <a href = \"deleteForum.php?id=$forum->id\"> Delete <a/> | <a href = \"modifyForum.php?id=$forum->id\"> edit <a/> " ;
}
Which obviously yields an error. You can check that the session is set first or use the # operator.

PHP controlling the output of rand

Is it possible to control the output of rand, for example if I just want rand to give me the output of the variable $roll1 with the value or number of 1 half the time out of the six possibilities when rand is ran or when the browser is refreshed, how does one accomplish that?
My code sucks but I am fighting to learn, I only get one every now and then, but it's not consistent, I want a 1 every time I refresh the page.
So If I refresh the page 6 times I should get a 1 out of the variable $roll1 three times, and the rest of the values for $roll1 should be random.
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>loaded dice</title>
</head>
<body>
<h1>loaded dice</h1>
<h3>loaded dice</h3>
<?php
// loaded dice, should roll the number 1 half the time out of a total of 6.
// So if I refreshed my browser six times I should at least see three 1's for roll1.
$roll1 = rand(1, 6);
// Okay is it possible to divide rand by two or somehow set it up
// so that I get the the value 1 half the time?
// I am trying division here on the if clause in the hopes that I can just have
// 1 half the time, but it's not working,maybe some type of switch might work? :-(.
if ($roll1 == 3) {
$roll1 / 3;
}
if ($roll1 == 6) {
$roll1 / 6;
}
if ($roll1 == 1) {
$roll1 / 1;
}
// This parts works fine :-).
// Normal random roll, is okay.
$roll2 = rand(1, 6);
print <<<HERE
<p>Rolls normal roll:</p>
You rolled a $roll2.
<p>Rolls the number 1 half the time:</p>
<p>You rolled a $roll1.</p>
HERE;
// Notice how we used $roll1 and 2, alongside the HERE doc to echo out a given value.
?>
<p>
Please refresh this page in the browser to roll another die.
</p>
</body>
</html>
You could do something like this
if (rand(0,1))
{
$roll = rand(2,6);
}
else
{
$roll = 1;
}
You can't directly make rand() do that, but you can do something like this:
<?PHP
function roll(){
if(rand(0,1)) //this should evaluate true half the time.
return 1;
return rand(2,6); //the other half of the time we want this.
}
So if you want to guarantee that in the last 6 rolls their would always have been at least 3 ones, I think you would have to track the history of the rolls. Here is a way to do that:
<?php
if (array_key_exists('roll_history', $_GET)) {
$rollHistory = unserialize($_GET['roll_history']);
} else {
$rollHistory = array();
}
$oneCount = 0;
foreach($rollHistory as $roll) {
if ($roll == 1) {
$oneCount++;
}
}
if (6 - count($rollHistory) + $oneCount <= 3) {
$roll = 1;
} else {
if (rand(0,1)) {
$roll = rand(2,6);
} else {
$roll = 1;
}
}
$rollHistory[] = $roll;
if (count($rollHistory) > 5) {
array_shift($rollHistory);
}
echo '<p>Weighted Dice Role: ' . $roll . '</p>';
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="get" >';
echo '<input type="hidden" name="roll_history" value="' . htmlspecialchars(serialize($rollHistory)) . '" />';
echo '<input type="submit" value="Roll Again" name="roll_again" />';
echo '</form>';
Rather than call rand() twice, you can simply do a little extra math.
$roll = $x = rand(1,12)-6 ? $x : 1;
A slightly different solution. It isn't as elegant, but perhaps more conducive to loading the die more finely?
$i = rand(1, 9);
if($i<=3)
{
$num = 1;
}
else $num = $i-2;

Categories