I have been trying to write a class to be used for displaying errors and error log.
class CError {
//Error Logging
var $Log;
public function Log($Comment, $Detail = ""){
$Log .= $Comment . "\n";
if ($Detail !== ""){
$Log .= "--" . $Detail . "--\n";
}
}
public function Clear_Log(){
$Log = "";
}
public function Display_Log(){
echo $this->Log;
}
//Error Display
var $ErrorCode = array(
0 => "0: No Error Code found, so either you got here by some rogue code or ...",
1 => "1: General Error, if you are here something went wrong",
2 => "2: Invalid information provided",
3 => "3: Alternate path taken, check message for details",
42 => "42: Here is your answer, but do you know the question?",
50 => "50: You messed with the Creepers without your Diamond Sword, didn't you",
9001 => "9001: Its over 9000... or more likely a value used was to large",
418 => "418: I'm a Teapot, found the error that drove you crazy"
);
public function Error($Error = 0, $ShowLog = false){
if ($Error === ""){
$Error = 0;
}
foreach ($ErrorCode as $key => $value){
if($key == $Error){
echo "<h3 style='color:red'>" . $value . "</h3><br />";
}
}
if($ShowLog == true){
echo $this->Log;
}
}
}
This is how I use the error class
include 'CError.php';
$Error = new CError;
$Error->Log("Email is Required");
$Error->Display_Log();
$Error->Error(2,true);
The problem is, nothing is displayed when used. It is skipped I think but not sure. I do not have access to the error logs for the server so I do not know if an error is being produced or not but the code will run through to the exit points in my main code(irrelevant to the class)
--EDIT--
The answers that tell to change $Log with $this->Log has fixed the issue with the $Log variable. It still has not fixed the issue with the error code array being displayed in the foreach loop.
--EDIT--
I solved the issue by adding $this->ErrorCode to the foreach loop.
You need to access class variable like $this->Log() in Log and Clear_Log() functions.
Try:
public function Log($Comment, $Detail = ""){
$this->Log .= $Comment . "\n";
if ($Detail !== ""){
$this->Log .= "--" . $Detail . "--\n";
}
}
public function Clear_Log(){
$this->Log = "";
}
You should modify $this->Log in methods Log and Clear_Log, like you access it in Display_Log. And you just access a local variable.
you're using the name Log for both function as well as variable. try changing the name for any one.
Related
so I am struggling with this bit of code for a project that I am working on. I do not understand why I am getting an array to string conversion error for my use of the Move_uploaded_file function below, since I implemented a foreach loop to work only with each individual element in the array. Also note that the issue- according to php's error handling- is specifically with the move_uploaded_file function, not with the other methods that get called.
Here's the relevant code. (Thanks all for the help).
public function relocate () {
foreach ($this->getFilename() as $name) {
$validate = $this->validatePhoto($name);
$size = $this->getSize($name);
if ($validate && $size) {
if (move_uploaded_file($name, $this->filepath . $this->getFilename())) {
echo "<p> upload complete </p>";
//rename file, redirect header, etc.
} //end if move_uploaded_file
else {
echo "<p> something's up. </p>";
}//end else
}//end if validate && size
}//end foreach
}//end relocate method
you should replace $this->getFilename() with $name, $this->getFilename() returns an array if I got it right...
public function relocate () {
foreach ($this->getFilename() as $name) {
$validate = $this->validatePhoto($name);
$size = $this->getSize($name);
if ($validate && $size) {
if (move_uploaded_file($name, $this->filepath . $name)) {
echo "<p> upload complete </p>";
//rename file, redirect header, etc.
} //end if move_uploaded_file
else {
echo "<p> something's up. </p>";
}//end else
}//end if validate && size
}//end foreach
}//end relocate method
It should be
public function relocate () {
foreach ($this->getFilename() as $name) {
$validate = $this->validatePhoto($name);
$size = $this->getSize($name);
if ($validate && $size) {
if (move_uploaded_file($name, $this->filepath . $name)) {
echo "<p> upload complete </p>";
//rename file, redirect header, etc.
} //end if move_uploaded_file
else {
echo "<p> something's up. </p>";
}//end else
}//end if validate && size
}//end foreach
}//end relocate method
You're passing in $this->getFileName() to move_uploaded_file(), when you should be passing in $name, as you're already iterating over the array that $this->getFileName() is returning
Hell all, I have a jabber script that automatically load up all msgs for me into a mysql database... however, after it's done, the script still stays/sticks... how can I have it exit after one run? Please help, and any kind of help I can get on this, I would be very very thankful!
<?php
// activate full error reporting
//error_reporting(E_ALL & E_STRICT);
include 'XMPPHP/XMPP.php';
$conn = new XMPPHP_XMPP('talk.google.com', 5222, 'username', 'password', 'xmpphp', 'gmail.com', $printlog=true, $loglevel=XMPPHP_Log::LEVEL_INFO);
// $conn->autoSubscribe();
$vcard_request = array();
try {
$conn->connect();
while(!$conn->isDisconnected()) {
$payloads = $conn->processUntil(array('message', 'presence', 'end_stream', 'session_start'));
foreach($payloads as $event) {
$pl = $event[1];
switch($event[0]) {
case 'message':
print "---------------------------------------------------------------------------------\n";
print "Message from: {$pl['from']}\n";
if($pl['subject']) print "Subject: {$pl['subject']}\n";
print $pl['body'] . "\n";
print "---------------------------------------------------------------------------------\n";
// $conn->message($pl['from'], $body="Thanks for sending me \"{$pl['body']}\".", $type=$pl['type']);
$cmd = explode(' ', $pl['body']);
if($cmd[0] == 'quit') $conn->disconnect();
if($cmd[0] == 'break') $conn->send("</end>");
if($cmd[0] == 'vcard') {
if(!($cmd[1])) $cmd[1] = $conn->user . '#' . $conn->server;
// take a note which user requested which vcard
$vcard_request[$pl['from']] = $cmd[1];
// request the vcard
$conn->getVCard($cmd[1]);
}
break;
case 'presence':
print "Presence: {$pl['from']} [{$pl['show']}] {$pl['status']}\n";
break;
case 'session_start':
print "Session Start\n";
$conn->getRoster();
$conn->presence($status="Cheese!");
break;
case 'vcard':
// check to see who requested this vcard
$deliver = array_keys($vcard_request, $pl['from']);
// work through the array to generate a message
print_r($pl);
$msg = '';
foreach($pl as $key => $item) {
$msg .= "$key: ";
if(is_array($item)) {
$msg .= "\n";
foreach($item as $subkey => $subitem) {
$msg .= " $subkey: $subitem\n";
}
} else {
$msg .= "$item\n";
}
}
// deliver the vcard msg to everyone that requested that vcard
foreach($deliver as $sendjid) {
// remove the note on requests as we send out the message
unset($vcard_request[$sendjid]);
$conn->message($sendjid, $msg, 'chat');
}
break;
}
}
}
} catch(XMPPHP_Exception $e) {
die($e->getMessage());
}
?>
Remove while condition and try.
I think it will work.
Than use any flag variable and add it in while loop.
I suggest you two ways:
1- Using "set_time_limit" function that kills script after specified seconds and throws an error.
2- Define a variable before while loop and save time in that:
$time=time();
At the end of the while loop add this code:
if($time+TimeInSeconds<time()) exit();
These two ways can stop the script after some seconds.
I hope it will help.
For quite a while now we experience a very weird problem with our hosting server. Once a while (seems randomly) variables in PHP become NULLs.
In general everything works perfectly fine, but once a while it happens. All accounts on the server are affected and all PHP apps (including PHPMyAdmin, Wordpress our own scripts). We contacted our hosting company, but they are unable to find any solution.
I had few ideas, the most promising one was an issue with Suhosin. But I do not get any message in the log directly from it.
We made a simplest possible script to reproduce the error:
<?php
class Example
{
protected $stringVar = 'this is a string value';
public function accessParameter()
{
$error = false;
if (isset($this->stringVar) && !is_null($this->stringVar)) {
echo "string var : " . $this->toStringWithType($this->stringVar) . "\n";
} else {
echo "string var is not set\n";
$error = true;
}
if ($error) {
$logfile = dirname(__FILE__)."/random_bug_log.log";
file_put_contents($logfile, date('Y-m-d H:i:s')."\n", FILE_APPEND);
file_put_contents($logfile, $this->toStringWithType($this->stringVar) . "\n", FILE_APPEND);
}
}
public function toStringWithType($var)
{
$type = gettype($var);
return "($type) '$var'";
}
}
$e = new Example();
$e->accessParameter();
Normal output:
string var : (string) 'this is a string value'
Output when the weird thing happens:
string var is not set
I open to any ideas or suggestions how to solve this problem. I guess the ultimate solution is to change the hosting company. I did not manage to create this issue on localhost or any other server.
Test piece that have been made, including your suggestions:
<?php
class Example
{
protected $stringVar = 'this is a string value';
public function accessParameter() {
$error = false;
if(isset($this->stringVar) && !is_null($this->stringVar)) {
echo "string var : "
.$this->toStringWithType($this->stringVar)
."\n";
} else {
echo "string var is not set\n";
$error = true;
}
if($error) {
$logfile = dirname(__FILE__)."/random_bug_log.log";
file_put_contents($logfile, date('Y-m-d H:i:s')." ", FILE_APPEND);
file_put_contents($logfile,
$this->toStringWithType($this->stringVar) . "\n",
FILE_APPEND);
}
}
public function writeParameter() {
$this->stringVar="variable assigned";
if(isset($this->stringVar) && !is_null($this->stringVar)) {
echo "string var : "
.$this->toStringWithType($this->stringVar)
."\n";
} else {
echo "string var is not set\n";
$error = true;
}
}
public function toStringWithType($var)
{
$type = gettype($var);
return "($type) '$var'";
}
}
$e = new Example();
$e->accessParameter();
$e->writeParameter();
The output while the thing happens:
string var is not set
string var is not set
it is very strange problem.
it may not be a solution but worth to try;
protected $stringVar;
function __construct() {
$this->stringVar = 'this is a string value';
}
I would recommend to use !== instead of is_null to see if the variable is actually null.
if (isset($this->stringVar) && ($this->stringVar !== null)) {
or
if (isset($this->stringVar) && (!empty($this->stringVar)) {
should do the work too.
In case of theses type of issues check with the value that you have in if condition and do what you want in else. Like in your situation do like:
if(isset($this->stringVar) && ($this->stringVar == "this is a string value")) {
}else{
// your code here...
}
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?
I'm trying display error messages on a form but only one is displayed (the last one always). I tried using a foreach loop but I keep getting the invalid argument error. The following displays errors one by one. Code is inside a class...
public $errorContainer = '';
// ------------------------------------------------------------
// ERROR MESSAGE PROCESSING
// ------------------------------------------------------------
private function responseMessage($respBool, $respMessage) {
$return['error'] = $respBool;
$return['msg'] = $respMessage;
if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
echo json_encode($return);
} else {
$this->errorContainer = $respMessage;
}
}
The following always gives me the invalid for each argument error.
private function responseMessage($respBool, $respMessage) {
$return['error'] = $respBool;
$return['msg'] = $respMessage;
if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
echo json_encode($return);
} else {
foreach ($respMessage as $value) {
$this->errorContainer = $value;
}
}
}
Thank you!
replace your foreach() with this:
private function responseMessage($respBool, $respMessage) {
// ...code...
foreach ((array) $respMessage as $value) {
$this->errorContainer .= $value;
}
// ...code---
}
Using type casting (array) above will make it works for both array and string type.
Edit:
Use this solution (type casting) only in your last effort. But your real problem is you're not passing an array to the function. See this code:
// incorrect
$msg = 'This is a message';
$this->responseMessage($some_bool, $msg);
// correct
$msg = array('This is a message');
$this->responseMessage($some_bool, $msg);
// correct
$msg = array('This is a message', 'And another message');
$this->responseMessage($some_bool, $msg);
If you pass the argument correctly like above, you don't need to cast $respMessage to array.