error returning information using php - php

I am steps away from finishing this project, I seem to have a problem with my logic in my fetchMessage() function, I am passing in the session_id however I am getting nothing returned here is my function code
function fetchMessages($session)
{
$get = ("SELECT * FROM chatRoom WHERE session_id = '$session'");
$hold = mysql_query($get, $con);
if($hold)
{
return mysql_fetch_array($hold);
}
}
the code calling this function is
<?php
include 'core/conection.php';
include 'function.php';
if(isset($_POST['method']) === true && empty($_POST['method']) === false)
{
$method = trim($_POST['method']);
$session = trim($_POST['session']);
if($method === 'fetch')
{
$messages = fetchMessages($session);
if(empty($messages) === true)
{
echo 'A representative will be with you shortly';
echo '<br />';
echo $session;
}else
{
foreach($messages as $message)
{
$ts = $message['timestamp'];
?>
<div class = "message">
<?php echo date('n-j-Y h:i:s a', $ts); ?>
<?php echo $message['username']; ?>
says:<p><?php echo nl2br($message['message']); ?></p>
</div>
<?php
}
}
}
}
?>
I know it is making it at least this far because at this line
if(empty($messages) === true)
{
echo 'A representative will be with you shortly';
echo '<br />';
echo $session;
}
it displays the correct session_id i have a fealing it is either my fetchMessages function that is wrong or the html code to display the results that is wrong.

Related

check external links invalid in a web site

i wrote a script on php in order to check external links invalid in a web site
this is the sript
<?php
// It may take a whils to spider a website ...
set_time_limit(10000);
// Inculde the phpcrawl-mainclass
include_once('../PHPCrawl_083/PHPCrawl_083/libs/PHPCrawler.class.php');
include ('check.php');
// Extend the class and override the handleDocumentInfo()-method
class MyCrawler extends PHPCrawler
{
function handleDocumentInfo(PHPCrawlerDocumentInfo $DocInfo) {
if (PHP_SAPI == "cli") $lb = "\n";
else {
$lb = "<br />";
// Print the URL and the HTTP-status-Code
// Print the refering URL
$file = file_get_contents($DocInfo->url);
preg_match_all('/<a[^>]+href="([^"]+)/i', $file, $urls);
echo '<br/>';
$home_url = parse_url( $_SERVER['HTTP_HOST'] );
foreach($urls as $url){
for($i=0;$i<sizeof($url);$i++){
$link_url = parse_url( $url[$i] );
if( $link_url['host'] != $home_url['host'] ) {
if (check_url($url[$i])=== false){
echo " Page requested: ".$DocInfo->url." (".$DocInfo->http_status_code.")".$lb;
echo '<br/>';
echo "<font color=green >"."lien externe invalide :".$url[$i].$lb." </font>";
echo '<br/>';
}
}
}
}
}
}
}
$crawler = new MyCrawler();
$crawler->setURL("http://www.tunisie-web.org ");
$crawler->addURLFilterRule("#\.(jpg|gif|png|pdf|jpeg|css|js)$# i");
$crawler->setWorkingDirectory("C:/Users/mayss/Documents/travailcrawl/");
$crawler->go();
?>
but more than external links(not invalid :/) it gives "http://www.tunisie-web.org" as an axternal link and i don't know where is the problem !!
please help
and this is check.php :
<?php
function check_url($url) {
if ( !filter_var($url, FILTER_VALIDATE_URL,FILTER_FLAG_QUERY_REQUIRED) === false) {
return true ;
}
else {
return false;
}
}
?>

php function to get page title

I want to get my website page title through a function
First I get the Page Name from a function...
function pagetitle() {
global $th, $ta, $tp, $ts, $tc; // <---- Getting the variable value from outside function
global $bl, $qt;
$tit = ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
if($tit == "Index") {
echo $th;
}
elseif($tit == "About-us"){
echo $ta;
}
elseif($tit == "Projects"){
echo $tp;
}
elseif($tit == "Services"){
echo $ts;
}
elseif($tit == "Contact-us"){
echo $tc;
}
elseif($tit == "Blog"){
echo $bl;
}
elseif($tit == "Quotation"){
echo $qt;
}
}
Then I tried to get the page title in the format of PageName | PageTitle or PageTitle | PageName...
function getOrg_title(){
$tit = "";
$block = " | ";
global $sl;
$org = $sl['app_org'];
if($sl['title_before'] === 'yes'){
$tit = $org.$block.\pagetitle(); //<----- This should be like "Raj | This is my website"
} else {
$tit = \pagetitle().$block.$org; //<----- This should be like "This is my website | Raj"
}
echo $tit;
}
But not happening...
$tit = $org.$block.\pagetitle(); //<----- Output is "This is my websiteRaj |"
And
$tit = \pagetitle().$block.$org; //<----- Output is "This is my website | Raj"
What should I do ?
You expect pagetitle() to return the page's title, but instead in your code you use echo.
echo will print out the title to the client rather than return it to the caller.
So change you echo $...; to return $...; and do echo pagetitle(); whereever you use it directly.
If this can not be done, you could extend your function to
pagetitle($echo = true)
{
// ...
if(/* ... */) {
$ret = $th;
} elseif(/* ... */) {
$ret = ...;
} elseif(/* ... */) {
$ret = ...;
}
// And so on ...
if($echo)
echo $ret;
return $ret;
}
Now in your wrapper function call pagetitle(false) to prevent the echo and still get the title from it.
About the backslash: \pagetitle()
The backslash is the namespace separator. Since you are not using namespacing here, all functions will be on the root namespace.
In this case - if you are using PHP 5.3 or above - you can use it or leave it out.

Adding new PHP session variable is destroying the session

I have encountered an odd issue that I was hoping someone could shed some light on.
I have a website that uses a PHP session to store login details. On this site is a game that also uses PHP session variables. Whenever I have not logged in to the site for a while, then try to play the game it logs me out. If I log back in straight away the session variables are remembered, I stay logged in and I can play the game as many times as I like. I can access any other page on the site with no issues.
I have session_start at the top of all pages. Any thoughts? Thank you.
This is my init.php file:
<?php
ob_start();
session_start();
//error_reporting(0); // don't display errors
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
require 'functions/items.php';
require 'functions/creatures.php';
$current_file = explode('/', $_SERVER['SCRIPT_NAME']);
$current_file = end($current_file);
if (logged_in() === true){
$session_user_id = $_SESSION['user_id'];
$user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name', 'email', 'password_recover', 'type', 'allow_email', 'profile', 'coins');
$creature_data = creature_data($session_user_id, 'base_creature_id', 'level', 'strength', 'speed', 'intelligence', 'happiness', 'status', 'battle_level');
if(user_active($user_data['username']) === false) {
session_destroy();
header('Location: logout.php');
exit();
}
if($current_file !== 'changepassword.php' && $user_data['password_recover'] == 1){
header('Location: changepassword.php?force');
exit();
}
}
$errors = array();
?>
And here is the game file:
<?php
require_once('core.php');
Hangman::StartPage();
?>
<head>
<link rel="stylesheet" type="text/css" href="games/plank/styles.css" />
</head>
<?php Hangman::PrintGameState(); ?>
<div id="content">
<!--<div id="banner"><img src="games/plank/images/interface/banner.png" /></div>-->
<div id="innerContent">
<div id="wordArea">
<span class="alphabet">
<?php Hangman::PrintCurrentWord(); ?>
</span>
</div>
<span id="controls">
<?php if(isset($_GET['finished']) === true && empty($_GET['finished']) === true){ ?>
<img id="result" src="games/plank/images/interface/<?php echo Hangman::GameResult() ? 'win' : 'lose'; ?>.png" />
<a id="replay" href="http://www.mobbipets.com/site/walkthepalm.php?m=r"></a>
<?php }
else if (Hangman::IsGameFinished()) {
header('Location: walkthepalm.php?finished');
if (Hangman::GameResult() == 'win'){
update_coins($session_user_id, 50);
}
}
else { ?>
<span class="alphabet">
<?php Hangman::PrintKeyboard(); ?>
</span>
<?php } ?>
</span>
<span id="hangman"><img src="games/plank/images/hangman/<?php echo $_SESSION['gameState']; ?>.png" /></span>
</div>
</div>
<?php Hangman::EndPage(); ?>
And here is the core.php file the game uses.
<?php
require_once('db.php');
/*=================================================
this class handles game logic and php sessions.
==================================================*/
abstract class Hangman
{
private static $pageUrl = 'http://www.mobbipets.com/site/walkthepalm.php';
private static $gameStates = 8; //includes the game over state
private static $keyboardButtons = "abcdefghijklmnopqrstuvwxyz&'-";
private static $underscores = array(
'us_1',
'us_2',
'us_3',
);
private static $alphabetAliases = array(
'&' => 'amp',
'\'' => 'apos',
'-' => 'hyphen',
',' => 'comma',
'!' => 'exclaim',
'+' => 'plus',
'?' => 'question',
);
//just checks if we have a valid session
public static function IsLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
private static function RegenerateSession()
{
//session_regenerate_id();
$_SESSION['valid'] = 1;
$_SESSION['lastActivity'] = time();
$_SESSION['word'] = Database::GetRandomWord();
$_SESSION['lettersLeft'] = strlen($_SESSION['word']);
$_SESSION['guessedLetters'] = '';
$_SESSION['gameState'] = 1;
// $session_user_id = $_SESSION['user_id'];
}
//session handling
public static function StartPage()
{
//session_start();
//terminate the session if we've been inactive for more than 10 minutes
if (self::IsLoggedIn())
{
if (isset($_SESSION['lastActivity']) && ((time() - $_SESSION['lastActivity']) > 600 ))
self::EndSession();
else
$_SESSION['lastActivity'] = time();
}
//if logged in after timeout check
if (self::IsLoggedIn())
{
$mode = trim(#$_GET['m']);
if ($mode != '')
$mode = strtolower($mode);
if ($mode != '') //we've passed a special input 'mode'
{
switch ($mode)
{
case 'g': //player making a guess
$guess = trim(#$_GET['g']);
if ($guess != '')
{
$guess = self::FromAlias(strtolower($guess));
if (strlen($guess) == 1 && stripos($_SESSION['guessedLetters'],$guess) === false) //valid
{
$_SESSION['guessedLetters'] .= $guess;
if (stripos($_SESSION['word'],$guess) === false) //wrong guess
$_SESSION['gameState']++;
else
$_SESSION['lettersLeft'] -= substr_count($_SESSION['word'] ,$guess);
}
}
break;
case 'r': //forced reset of session
self::EndSession();
break;
}
}
}
//we forced a reset
if (!self::IsLoggedIn())
{
self::RegenerateSession();
header ('Location: '.self::$pageUrl);
}
}
//is the game finished
public static function IsGameFinished()
{
return $_SESSION['gameState'] >= self::$gameStates || (isset($_SESSION['lettersLeft']) && $_SESSION['lettersLeft'] <= 0);
}
//check if we won (true == win)
public static function GameResult()
{
return $_SESSION['gameState'] < self::$gameStates && $_SESSION['lettersLeft'] == 0;
}
//add any page-close stuff here
public static function EndPage()
{
}
//terminates the session
private static function EndSession()
{
//$_SESSION = array(); //destroy all of the session variables
//session_destroy();
//session_unset();
self::RegenerateSession();
return true;
}
//convert a character to it's alias
private static function ToAlias($letter)
{
return array_key_exists($letter, self::$alphabetAliases) ? self::$alphabetAliases[$letter] : $letter;
}
//reduce an alias to it's corresponding character
private static function FromAlias($alias)
{
$key = array_search($alias, self::$alphabetAliases);
return $key === false ? $alias : $key;
}
//spit out the current word images based on game state
public static function PrintCurrentWord()
{
if (!self::IsLoggedIn())
return;
$finished = self::IsGameFinished();
for ($i = 0; $i < strlen($_SESSION['word']); $i++)
{
$letter = substr($_SESSION['word'],$i,1);
echo '<span class="';
if (!$finished && stripos($_SESSION['guessedLetters'], $letter) === false) //haven't guessed this yet
echo self::$underscores[rand(0,count(self::$underscores)-1)];
else //is a valid character that we've guessed already
echo self::ToAlias($letter);
echo '"></span>'."\n";
}
}
public static function PrintGameState() //debugging
{
echo "\n<!--\n";
echo "Word: ".$_SESSION['word']."\n";
echo "Letters guessed: ".$_SESSION['guessedLetters']."\n";
echo "Letters left: ".$_SESSION['lettersLeft']."\n";
echo "Game State: ".$_SESSION['gameState']."\n";
echo "-->\n";
}
//print out the keyboard buttons
public static function PrintKeyboard()
{
if (!self::IsLoggedIn())
return;
for ($i = 0; $i < strlen(self::$keyboardButtons); $i++)
{
$key = substr(self::$keyboardButtons,$i,1);
$keyAlias = self::ToAlias($key);
if (stripos($_SESSION['guessedLetters'], $key) === false) //haven't guessed this yet
echo '<a class="'.$keyAlias.'" href="?m=g&g='.$keyAlias.'"></a>';
else //we've guessed already
echo '<span class="'.$keyAlias.'"><img src="games/plank/images/alphabet/'.(stripos($_SESSION['word'], $key) === false?'wrong':'right').'.png" /></span>';
echo "\n";
}
}
}
?>
A common mistake is an assignment like this:
$_SESSION = $data;
this will overwrite any previously stored information.
Better practice is to make $_SESSION an array with named indexes:
$_SESSION['somedata'] = $data;
Now you will only overwrite data stored in the 'somedata' field.

Javascript confirm() function cannot pass parameters properly

I'm using PHP and JavaScript, and I got a problem when deal with the confirm() function in JavaScript.
Say I have a page add.php, firstly I receive some parameters passed from another page, and I check to see if they are valid or not. If yes, I just insert the data into db and return to another page, if they are not valid, there'll be a confirm() window popped up and let the user to choose whether to continue or not. If the user still choose to continue, I want the page to be reloaded with all the parameters sent again. But the problems is that I cannot get the parameter the second time add.php is loaded.
Previously I didn't use a window.onload function and confirm() pop up, but an < a href> link instead, everything worked fine (Please see the attached code at the end). But when I tried to use the following code, the same url stopped working
echo "<script type=\"text/javascript\">";
echo "window.onload = function() {
var v = confirm(\"$name is not alive, do you want to add it into system?\");
if (v) {
window.location.href= \"add.php?type=room&name=$name&area\"
+ \"=$area&description=$description&\"
+ \"capacity=$capacity&confirm=Y\";
} else {
window.location.href= \"admin.php?area=$area\";
}
}";
echo "</script>";
Following is the previous version, instead of using window.onload(), I used < a href="..." /> link, everything worked fine at that time. get_form_var is a function in functions.inc, which is to get the parameter using $_GET arrays.
<?php
require_once "functions.inc";
// Get non-standard form variables
$name = get_form_var('name', 'string');
$description = get_form_var('description', 'string');
$capacity = get_form_var('capacity', 'string');
$type = get_form_var('type', 'string');
$confirm = get_form_var('confirm','string');
$error = '';
// First of all check that we've got an area or room name
if (!isset($name) || ($name === ''))
{
$error = "empty_name";
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location: $returl");
}
// we need to do different things depending on if its a room
// or an area
elseif ($type == "area")
{
$area = mrbsAddArea($name, $error);
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location: $returl");
}
elseif ($type == "room")
{
if (isset($confirm)){
$dca_osi = getOsiVersion($name);
$room = mrbsAddRoom(
$name,
$area,
$error,
$description,
$capacity,
$dca_osi,
1
);
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location:$returl");
}
else {
$dca_status= pingAddress($name);
$dca_osi = getOsiVersion($name);
if( $dca_status == 0){
$room = mrbsAddRoom(
$name,
$area,
$error,
$description,
$capacity,
$dca_osi,
0
);
$returl = "admin.php?area=$area"
. (!empty($error) ? "&error=$error" : "");
header("Location:$returl");
}
else {
print_header(
$day,
$month,
$year,
$area,
isset($room) ? $room : ""
);
echo "<div id=\"del_room_confirm\">\n";
echo "<p>\n";
echo "$name is not alive, are you sure to add it into system?";
echo "\n</p>\n";
echo "<div id=\"del_room_confirm_links\">\n";
echo "<a href=\"add.php?type=room&name"
. "=$name&area=$area&description"
. "=$description&capacity=$capacity&confirm"
. "=Y\"><span id=\"del_yes\">"
. get_vocab("YES") . "!</span></a>\n";
echo "<a href=\"admin.php?area=$area\"><span id=\"del_no\">"
. get_vocab("NO") . "!</span></a>\n";
echo "</div>\n";
echo "</div>\n";
}
}
}
function pingAddress($host)
{
$pingresult = exec("/bin/ping -c 1 $host", $outcome, $status);
if ($status==0) {
return $status;
}
else {
return 1;
}
}
function getOsiVersion($host)
{
$community = 'public';
$oid = '.1.3.6.1.4.1.1139.23.1.1.2.4';
$sysdesc = exec("snmpwalk -v 2c -c $community $host $oid");
$start = strpos($sysdesc, '"');
if ($start!==false) {
$sysdesc = substr($sysdesc, $start+1,$sysdesc.length-1);
return $sysdesc;
}
else {
return "not available";
}
}
I've solved the problem, just simply by using "&" instead of " & amp;" in the url link... it works fine now...
You try location.reload() javascript call?

Concrete5 error with no result

I am using concrete to render my site, it uses the following error system;
if (isset($error) && $error != '') {
if ($error instanceof Exception) {
$_error[] = $error->getMessage();
} else if ($error instanceof ValidationErrorHelper) {
$_error = $error->getList();
} else if (is_array($error)) {
$_error = $error;
} else if (is_string($error)) {
$_error[] = $error;
}
?>
<?php if ($format == 'block') { ?>
<div class="alert-message error">
<?php foreach($_error as $e): ?>
<?php echo $e?><br/>
<?php endforeach; ?>
</div>
<?php } else { ?>
<ul class="ccm-error">
<?php foreach($_error as $e): ?>
<li><?php echo $e?></li>
<?php endforeach; ?>
</ul>
<?php } ?>
<?php } ?>
This is used to detect errors in the system, or validation errors.
My problem is that the error div is being displayed but there is no errors, e.g.:
I have tried dumping the variables and this is the result (in this case):
Array object(ValidationErrorHelper)#89 (1) { ["error:protected"]=> array(0) { } }
This is the ValidationErrorHelper system:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
class ValidationErrorHelper {
protected $error = array();
public function reset() {
$this->error = array();
}
public function add($e) {
if ($e instanceof ValidationErrorHelper) {
$this->error = array_merge($e->getList(), $this->error);
} else if (is_object($e) && ($e instanceof Exception)) {
$this->error[] = $e->getMessage();
} else {
$this->error[] = $e;
}
}
public function getList() {
return $this->error;
}
public function has() {
return (count($this->error) > 0);
}
public function output() {
if ($this->has()) {
print '<ul class="ccm-error">';
foreach($this->getList() as $error) {
print '<li>' . $error . '</li>';
}
print '</ul>';
}
}
}
?>
Is there any way to remove this? or diagnose it?
Sometimes the error object is set, but doesn't have any errors in it. If you look at the very top "if" statement, you'll see this:
if (isset($error) && $error != '') {
So what's happening is the $error variable is an object or an array and has been set by the system, but it doesn't have any errors in it. But your code is always outputting the container <div> as long as the $error variable is set (or not an empty string). What you need to do is add an additional check on the $_error variable (the one that is created in the first dozen or so lines of the code) to see if it's empty or not.
Try this:
if (isset($error) && $error != '') {
if ($error instanceof Exception) {
$_error[] = $error->getMessage();
} else if ($error instanceof ValidationErrorHelper) {
$_error = $error->getList();
} else if (is_array($error)) {
$_error = $error;
} else if (is_string($error)) {
$_error[] = $error;
}
if (!empty($_error)) {
if ($format == 'block') { ?>
<div class="alert-message error">
<?php foreach($_error as $e): ?>
<?php echo $e?><br/>
<?php endforeach; ?>
</div>
<?php } else { ?>
<ul class="ccm-error">
<?php foreach($_error as $e): ?>
<li><?php echo $e?></li>
<?php endforeach; ?>
</ul>
<?php }
}
}

Categories