while ($row = mysql_fetch_row($result))
{
echo "<tr>";
echo ("<p><td>$row[2]</td><td>$row[0]</td><td>$row[1]</td><td><i>$row[3]</i></td><td><center>[x]</center></td></p>");
echo "</tr>";
$x++;
}
echo "</table>";
}
else
{
echo "*No Accounts*";
}
if (isset($_COOKIE['amountx'])) {
if ($_COOKIE['amountx'] < $x) {
$x = $x - $_COOKIE['amountx'];
echo "<title>'New Logs - ($x)'</title>";
}
else if ($_COOKIE['amountx'] == $x) {
echo "<title>'Logs (0)'</title>";
}
else {
setcookie("amountx", $x, time() + 60 * 60 * 24 * 30);
}
}
else {
setcookie("amountx", $x, time() + 60 * 60 * 24 * 30);
}
The title never updates but the cookie is saved. This was in the while loop but I took it out and it still saves the cookie amount. But I can't get it to display the new title even after refreshing every 5 seconds via meta-refresh. How can I update the title?
Looking at the structure of your code, it appears that you're printing HTML in the <body> tag before you're attempting to echo a different <title> tag.
You can't have a <title> tag anywhere but within the <head> element.
Move your <title> code to take effect within the <head> element, and it should work.
I removed the top <title>Page title</title> at the top of my page now it works properly thanks guys.
Related
So i have this code that whenever an IP is ping able or up it'll choose the green line to appear on my screen and in reverse the red line. So what I am trying to do instead if the Round Trip Time of that IP is < 200 then it's green and when it's > 250 it's red . How can i do that?
Anyone help me. Thank you.
<?php
$page = $_SERVER['PHP_SELF'];
$sec = 5;
function pingAddress($TEST) {
$pingresult = exec("ping -c 1 $TEST", $output, $result);
if ($result == 0) {
echo "Ping successful!";
echo "<pre>Your ping: $TEST</pre>";
echo "<hr color = \"green\" width = 40%> GOOD";
} else {
echo "Ping unsuccessful!";
echo "<pre>Your ping: $TEST</pre>";
echo "<hr color = \"red\" width = 40%> BAD";
}
}
pingAddress("66.147.244.228");
?>
<html>
<head>
<meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
</head>
<body>
</body>
</html>
The exec function is ok to use, but you should parse the contents of the output argument, after declaring it first as an array.
Even if you added -c 1 to only issue one ping, this is the recommended way of using exec.
define('RETRIES', 1);
define('PING_PATH', '/usr/bin/ping');
function pingAddress($IP)
{
$output = array();
exec(PING_PATH . " -c " . RETRIES . " $IP", $output);
// generic way, even for one line. You can also do -c 4,
// and preg_match will pick the first meaningful result.
$output_string = implode("; ", $output);
/// adapt the regular expression to the actual format of your implementation of ping
if (preg_match('/ time=\s+(\d+)ms/', $output_string, $bits)) {
$rt_time = (int)$bits[1];
if ($rt_time < 200) {
// green business
}
else if ($rt_time > 250) {
// red business
}
else {
// default handler business (or not...)
}
}
else {
echo "Hum, I didn't manage to parse the output of the ping command.", PHP_EOL;
}
}
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'm making a mini shopping cart for my project. Im storing the number of items chosen by the user, I don't understand that when i add one to my session variable I always get this error on the first go
Undefined index: cart_1 in D:\wamp\www\MiniCart\cart.php on line 100
And when I add again or refresh the same page it works fine. Why could this error be coming up? I removed the +=1 from the statement and it worked fine, apparently there is no syntax error too.
Cart.php
<!DOCTYPE>
<html>
<head></head>
<body>
<?php
session_start();
//The page where to jump to after adding/editing cart.
$page = 'mini_cart_index.php';
$link = mysqli_connect("localhost","root","","cart");
if(mysqli_connect_errno())
{
echo "Error:".mysqli_connect_error();
echo "<br/>";
} else {
echo "Connected to SQL<br/>";
}
//==================================================
if(isset($_GET['add']))
{
$obt=$_GET['add'];
$quantity_limit = 'SELECT id,quantity FROM products WHERE id='.mysqli_real_escape_string($link,(int)$_GET['add']);
$quantity = mysqli_query($link,$quantity_limit);
while($quantity_row=mysqli_fetch_assoc($quantity))
{
if($quantity_row['quantity']!=$_SESSION['cart_'.$_GET['add']])
{
$_SESSION['cart_'.$_GET['add']]+='1';
}
}
/*
echo 'id='.$obt.' '.'next<br/>';
echo 'Now storing info into session variable and adding one<br/>';
echo $_SESSION['cart_'.$_GET['add']];
echo '<br/>';
echo 'info stored<br/>';
*/
}
//***************************************************
function products()
{
GLOBAL $link;
$get ="SELECT id,name,description,price FROM products
WHERE quantity > 0 ORDER by id ASC";
if($result=mysqli_query($link,$get))
{
echo "Data Selected to be displayed<br/>";
} else {
echo "Error:".mysqli_error($link);
}
if(mysqli_num_rows($result)==0)
{
echo "There are no products to display!<br/>";
} else {
while($get_row=mysqli_fetch_assoc($result))
{
echo '<hr/><br/>';
echo 'displaying data from database<br/>';
echo '==================================';
echo '<p>'.$get_row['name'].'<br/>'.
$get_row['description'].'<br/>'.
number_format($get_row['price'],2).
' Add'.'</p>';
echo '<hr/><br/>';
}
}
}
echo 'outside'.$_SESSION['cart_1'];
?>
</body>
</html>
Mini_cart_index.php
<?php require 'cart.php';?>
<!DOCTYPE>
<html>
<head>
</head>
<body>
<?php products() ?>
</body>
</html>
That code is filled with SQL injection vulnerabilities, you should use PDO and prepare your statements.
PHP is warning you because it has to read the current value and add to it, but the first time you try to access it doesn't exist.
You could suppress the warning with:
#$_SESSION['cart_'.$_GET['add']]+='1';
A better way to do it though would be checking if it exists first
$name = 'cart_'.$_GET['add'];
if(isset($_SESSION[$name]) {
$_SESSION[$name] = 1;
} else {
$_SESSION[$name] += 1;
}
The problem is caused by the fact that...
$var['abc'] += 1
...is the same as
$var['abc'] = $var['abc'] + 1
So if you've got a clean session and $var['abc'] doesn't exist, you're going to get a warning because you're trying to read a non-existant value in order to add 1 to it.
While it's true that 0 + 1 = 1
...what's actually happening here is undefined + 1 = 1 with a warning.
As other answers have mentioned - to fix the issue, you can explicitly check that the array index exists before trying to increment it.
I'd do that with the ternary operator like this:
$key = 'card_' . $_GET['add'];
$_SESSION[$key] = (isset($_SESSION[$key]) ? $_SESSION[$key] : 0) + 1;
This is effectively saying
$val = ($val if it exists, otherwise 0) + 1;
Change your if statement to check if it's empty too:
if (!isset($_SESSION['cart_'.$_GET['add']])) {
$_SESSION['cart_'.$_GET['add']] = 1;
} elseif ($quantity_row['quantity'] != $_SESSION['cart_'.$_GET['add']]) {
$_SESSION['cart_'.$_GET['add']] += 1;
}
I have php code for list all ".swf" files in a folder. (The name of the files is always:
"99-dd-mm-YY_HH-mm-ss.swf", example: "01-19-06-2011_18-40-00.swf".
When I have more than 500 files in the folder is complicated to see and to refresh the page.
I need paginate the list of files.
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title></title>
<script type="text/javascript">
function submitform()
{
document.myform.submit();
}
</script>
</head>
<body>
<form name="myform" action="some.php" method="post">
<?php
echo "\n<br>\n";
echo "<a href='javascript:this.location.reload();' style='color: #000000; font-weight: normal'>Refresh</a></br>";
echo "<tr>\n<td>\n<a href='javascript:javascript:history.go(-1)'>\n";
echo "<img src='../../inc/img/back.png' alt='Back'";
echo " border=0>\n";
echo "<b> Back</b></a></td>\n";
echo "\n</tr>\n";
echo "\n<br>\n\n<br>\n";
$folder='.';
function order($a,$b){
global $folder;
$directory='.';
return strcmp(strtolower($a), strtolower($b));
}
$folder=opendir($folder);
while($files=readdir($folder)){
$ext = pathinfo($files, PATHINFO_EXTENSION);
if ($ext == 'swf') { //con esta línea saco el nombre index.php del listado
$file[]=$files;
usort($file, "order");
}
}
$n = 0;
foreach($file as $archiv){
$n = $n + 1;
$day = substr($archiv, 3,10);
$day = str_replace("-","/", $day);
$hour = substr($archiv, 14,8);
$hour = str_replace("-",":", $hour);
echo "<img alt='Ver $archiv' src='../../inc/img/video.png'> Video $n, Día: $day, hour: $hour\n ";
echo "<input type='submit' name='xxx' value='$archiv'></td>\n";
echo "\n</tr>\n";
echo "<br>";
}
closedir($folder);
echo "\n<br>\n";
echo "<tr>\n<td>\n<a href='javascript:javascript:history.go(-1)'>\n";
echo "<img src='../../inc/img/back.png' alt='Back'";
echo " border=0>\n";
echo "<b> Back</b></a></td>\n";
echo "\n</tr>\n";
?>
</form>
</body>
</html>
When required to go through lots of folders and files, try the Iterator object. A nice example:
function get_files($dir)
{
$dir = new DirectoryIterator($dir);
$list = iterator_to_array($dir, false);
return array_slice($list, 2);
}
This will get all the file names (if you have php 5.3 or higher) very fast and will do the if dir_exists / file_exists for you! The array_slice so it removes the . and .. directory.
I used this code for simple pagination
<?php
// Include the pagination class
include 'pagination.class.php';
// Create the pagination object
$pagination = new pagination;
// some example data
foreach (range(1, 100) as $value) {
$products[] = array(
'Product' => 'Product '.$value,
'Price' => rand(100, 1000),
);
}
// If we have an array with items
if (count($products)) {
// Parse through the pagination class
$productPages = $pagination->generate($products, 20);
// If we have items
if (count($productPages) != 0) {
// Create the page numbers
echo $pageNumbers = '<div>'.$pagination->links().'</div>';
// Loop through all the items in the array
foreach ($productPages as $productID => $productArray) {
// Show the information about the item
echo '<p><b>'.$productArray['Product'].'</b> 243'.$productArray['Price'].'</p>';
}
// print out the page numbers beneath the results
echo $pageNumbers;
}
}
?>
Here there is pagination class and the example for download:
http://lotsofcode.com/php/php-array-pagination.htm
Thanks for all!
Like #Tessmore said, Spl Iterators are teh awesomesauce. According to the docs, you only need PHP > 5.1 for the basic iterators.
Cross-posting an example --
DirectoryIterator and LimitIterator are my new best friends, although glob seems to prefilter more easily. You could also write a custom FilterIterator. Needs PHP > 5.1, I think.
No prefilter:
$dir_iterator = new DirectoryIterator($dir);
$paginated = new LimitIterator($dir_iterator, $page * $perpage, $perpage);
Glob prefilter:
$dir_glob = $dir . '/*.{jpg,gif,png}';
$dir_iterator = new ArrayObject(glob($dir_glob, GLOB_BRACE));
$dir_iterator = $dir_iterator->getIterator();
$paginated = new LimitIterator($dir_iterator, $page * $perpage, $perpage);
Then, do your thing:
foreach ($paginated as $file) { ... }
Note that in the case of the DirectoryIterator example, $file will be an instance of SplFileInfo, whereas glob example is just the disk path.
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;