PHP Auto Kill After X minutes - php

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.

Related

php for loop: error message if condition not met

My foreach loop:
$empty = "You cannot decommission this truck. It is in use."
$msg = "";
foreach ($trucks_to_remove as $truck_id) {
$truck_id = trim($truck_id);
if (strlen($truck_id)) {
$msg .= decom_truck(
$db,
$depot_id,
$truck_id
);
}
else
{
echo $empty;
}
}
echo $msg;
If the condition is not met, it means the sql cursor that preceded this foreach loop did not return a result for this truck_id (meaning it is in use), I just want a simple message sent to the page to alert the user.
It does not have to be a pop-up or the like. Where would I put my write or print statement? I assume I'd use an else clause but when I add an else inside the foreach loop (see above), I get nothing printed to the page. I have also tried the following:
else if (strlen($truck_id)) == 0
{
echo $empty;
}
I am very new to php.
$arr1 = array();
if(!$arr1)
{
echo 'arr1 is emty<br/>';
$arr2 = array(1, 2);
if($arr2)
echo 'arr2 has data';
exit();
}

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?

PHP improve my show message function

I'd like some help please, if its possible.
I have created two functions in order to display some messages when is set a $_GET after a redirect.Here's the code:
function display(){
if(isset($_GET['cnf_upd']) && $_GET['cnf_upd'] == '1'){
$value = "The update was successful!";
$type = "confirm";
construct_the_div($value, $type);
}
if(isset($_GET['err_upd']) && $_GET['err_upd'] == '1'){
$value = "The Update failed.";
$type = "error";
construct_the_div($value, $type);
}
if(isset($_GET['cnf_del']) && $_GET['cnf_del'] == '1'){
$value = "Deleted completely.";
$type = "confirm";
construct_the_div($value, $type);
}
if(isset($_GET['err_del']) && $_GET['err_del'] == '1'){
$value = "Unable to delete.";
$type = "error";
construct_the_div($value, $type);
}
}
function construct_the_div($value, $type){
// creating a div to display the message results
$div = "<div class=\"{$type}Msg\">\n";
$div .= "<p>{$value}</p>\n";
$div .= "</div><!-- end of {$type}Msg -->\n";
echo $div;
}
What I'd like to make is to try to improve the display function, as it gets longer and longer, so that there whould be only one (or two at most) if statement(s) if possible. So the value of the GET will be dynamicly inside the if condition and also if it has the preffix 'cnf_' it wil be a 'confirmMsg' and if it has the preffix 'err_' it wil be a 'errorMsg'.
Is it possible to make something like this???
function display() {
$messages = array(
'cnf_upd' => 'The update was successful!',
'cnf_err' => 'The Update failed.!',
// ...
// add all error and confirm there
// ...
);
foreach($_GET as $key => $value) {
if(strpos($key, 'cnf_')===0) {
$type = 'confirm';
$value = isset($messages[$key])
? $messages[$key]
: $key;
construct_the_div($value, $type);
}
if(strpos($key, 'err_')===0) {
$type = 'error';
$value = isset($messages[$key])
? $messages[$key]
: $key;
construct_the_div($value, $type);
}
}
}
The approach is not correct, it seems that only one message should occur at once (there cannot be "deleted completely" and "unable to delete" at once).
Try construct the parameters this way: ?msg=upd&msgType=cnf
function display(){
if (isset($_GET['msg']) && isset($_GET['msgType']))
{
$messages = array('cnf_upd'=>'The update was successful!',
'err_upd'=>'The update failed!',
'cnf_del'=>'The deletion was successful!',
'cnf_upd'=>'The deletion failed!',
);
if (isset($messages[$_GET['msgType'].'_'.$_GET['msg']))
construct_the_div($messages[$_GET['msgType'].'_'.$_GET['msg']], htmlspecialchars($_GET['msgType']));
}
there is still much to improve, but for start this is cleaner and safer.
I'm going to propose a different solution. Instead of setting different parameters in $_GET based on the message to be sent, set one parameter and parse its value.
// Start by setting integer constants:
define(CNF_UPD, 1);
define(ERR_UPD, 2);
define(CNF_DEL, 3);
define(ERR_DEL, 4);
Then when you set the value un $_GET, use the constant:
// Build the URL with a deletion error...
header("Location: http://example.com/script.php?msg=" . ERR_DEL);
Finally, use a switch to parse them
if (isset($_GET['msg'])) {
switch ($_GET['msg']) {
case CNF_UPD:
// Updated...
break;
case ERR_UPD:
// failed...
break;
// etc...
default:
// invalid code.
}
}
If you use a pattern of confirm/error/confirm/error for your integer constants, you can determine which it is by taking $_GET['msg'] % 2. Odd numbers are confirmations, evens are errors. There are of course many other ways you could lay this out, I just happen to have typed them in the alternating order you used. You could also do positive integers for confirmations and negatives for errors, for example.
$type = $_GET['msg'] % 2 == 1 ? $confirm : $error;
This is easily expanded to use multiple messages as well. Since they are integer values, you can safely construct a comma-separated list and explode() them when received.
$messages = implode(array(ERR_DEL,CNF_UPD));
header("Location: http://example.com/script.php?msg=$messages");
Unless you can somehow generate $value and $type based on the $_GET parameter (which I can't see how you would do), you could do something like:
$messages = array();
$messages[] = array('id' => 'cnf_upd', 'value' => 'The update was successful!', 'type' => 'Confirm');
$messages[] = array('id' => 'err_upd', 'value' => 'The Update failed.', 'type' => 'error');
...
foreach ($messages as $message) {
if(isset($_GET[$message['id']]) && $_GET[$message['id']] == '1'){
construct_the_div($message['value'], $message['type']);
}
}

PHP foreach invalid argument supplied

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.

Custom Class not displaying echo

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.

Categories