need to run long taking task in php - php

In a commercial project I need to periodically monitor SMTP and Accounting servers to see if its running and working properly.
if its dead update a table in mysql.
I cant install any 3rd party app on server hosting php script or use exec or modify php settings through php_ini_set
each task takes about 10 to 30 seconds
I tried to run tasks through Jquery ajax calls
and it worked , but the problem is when the jquery request is running you cant navigate to any other page and xhr.abort(); is not working , and stucks on loading until jquery task finishes.
This is what i tried in my js file
var monitor_running = false;
var xhr;
function monitor() {
if (document.readyState === "complete") {
if (monitor_running === false) {
monitor_call();
}
else {
console.log("jobs Already running ===>");
}
}
}
window.onbeforeunload = function () {
console.log(xhr);
xhr.abort();
alert(xhr.status);
};
setInterval(monitor, monitor_interval * 1000);
function monitor_call() {
monitor_running = true;
console.log("jobs running");
xhr = $.ajax({url: './ajax.php',
data: {
cmd: 'monitor'
},
type: 'post',
async: true,
success: function (output) {
monitor_running = false;
console.log(output + " job is finished");
}
});
}
and in php page :
<?php
include_once '../includes/config.php';
$tpl_obj = new template('admin');
$navigation_obj = new navigation();
$auth = $navigation_obj->admin_is_auth();
if (!$auth) {
die('Auth Failed !');
}
function monitor() {
sleep(10);
echo 'done';
// $monReport['acc'] = monitor::domon('acc');
// $monReport['smtp'] = monitor::domon('smtp');
// $monReport['payment'] = monitor::domon('payment');
// $monReport['dns'] = monitor::domon('dns');
// return json_encode($monReport);
}
$cmd_post = filter_input(INPUT_POST, 'cmd');
$cmd_get = filter_input(INPUT_GET, 'cmd');
if ($cmd_post == 'monitor') {
echo monitor();
}

Related

How do I do WebRTC signaling using AJAX and PHP?

I'm new to WebRTC and I don't understand how the signaling works on the server side. I know the request must be two-way. I'm able to send an offer to a PHP page but from there I'm stuck.. How does the other peer pick that offer so that it can generate an answer? I don't want a socket solution because I don't have my own server and I don't want to have a third-party dependency.
I have created an offer and sent that offer to a PHP page. See my code:
var myPeerConnection;
var caller_video=document.getElementById('caller_video');
var receiver_video=document.getElementById('receiver_video');
var mediaConstraints = {
video:true,
audio:false
};
function sendToServer(msg){
var msgJSON = JSON.stringify(msg);
$.ajax({
type:'get',
url:'offer.php',
data:'object='+msgJSON,
beforeSend:function(){
console.log('Sending...');
},
success:function(data){
console.log(data);
}
});
}
function reportError(error){
console.log(error.name);
}
function handleNegotiationNeededEvent(){
myPeerConnection.createOffer().then(function(offer) {
return myPeerConnection.setLocalDescription(offer);
})
.then(function(){ // so here I'm supposed to send an offer
sendToServer({
name: myUsername,
target: targetUsername,
type: "video-offer",
sdp: myPeerConnection.localDescription
});
})
.catch(reportError);
}
function handleICECandidateEvent(event){
if(event.candidate){//send the ICECandidates
sendToServer({
name: myUsername,
target: targetUsername,
type: "new-ice-candidate",
candidate: event.candidate
});
}
}
function handleTrackEvent(event){
console.log(event);
document.getElementById("received_video").srcObject = event.streams[0];
}
function handleRemoveTrackEvent(event){
var stream = document.getElementById("received_video").srcObject;
var trackList = stream.getTracks();
if (trackList.length == 0){
closeVideoCall();
}
}
function handleICEConnectionStateChangeEvent(event){
console.log('ICE connection changed!');
switch(myPeerConnection.iceConnectionState) {
case "closed":
case "failed":
case "disconnected":
closeVideoCall();
break;
}
}
function handleICEGatheringStateChangeEvent(event){
console.log('Is gathering');
console.log(event);
}
function handleSignalingStateChangeEvent(event) {
console.log('Signaling state changed');
switch(myPeerConnection.signalingState) {
case "closed":
closeVideoCall();
break;
}
};
function createPeerConnection() {
var STUN = {
'url': 'stun:stun.l.google.com:19302',
};
var iceServers =
{
iceServers: [STUN]
};
myPeerConnection = new RTCPeerConnection(iceServers);
myPeerConnection.onnegotiationneeded = handleNegotiationNeededEvent;
myPeerConnection.onicecandidate = handleICECandidateEvent;
myPeerConnection.ontrack = handleTrackEvent;
myPeerConnection.onremovetrack = handleRemoveTrackEvent;
myPeerConnection.oniceconnectionstatechange = handleICEConnectionStateChangeEvent;
myPeerConnection.onicegatheringstatechange = handleICEGatheringStateChangeEvent;
myPeerConnection.onsignalingstatechange = handleSignalingStateChangeEvent;
}
function handleGetUserMediaError(e) {
switch(e.name) {
case "NotFoundError":
alert("Unable to open your call because no camera and/or microphone" +
"were found.");
break;
case "SecurityError":
case "PermissionDeniedError":
// Do nothing; this is the same as the user canceling the call.
break;
default:
alert("Error opening your camera and/or microphone: " + e.message);
break;
}
closeVideoCall();
}
function closeVideoCall(){
//do something to exit the video call
}
//invite the other peer...we want to send our SDP
function invite(evt){
if (myPeerConnection){
console.log('Call already started');
}
else{
//myPeerConnection=new MediaStream();
targetUsername ='Nevil';//Unique other peer username
myUsername='Philip';
createPeerConnection();//this function creates a peer connection//uses the STUN/TURNS servers...updates myPeerConnection variable so it's not null
navigator.mediaDevices.getUserMedia(mediaConstraints)//grab our media constraints
.then(function(localStream) {
caller_video.srcObject =localStream;
caller_video.play();
localStream.getTracks().forEach(track => myPeerConnection.addTrack(track, localStream));
})
.catch(handleGetUserMediaError);
}
}
//we click the call button
document.querySelector('#callBt').addEventListener('click',function(){
invite();
});
I know there must be a way to send back the answer but I would like to just send the offer; that way I will understand how both peers exchange the SDP on the backend. Please try using PHP. If anyone can create a signaling XHR request, I will appreciate it.

Start and stop a request to server when use PHP and JavaScript

I created a function in php which send request to a server at every X seconds. Let's say a watcher. I start that watcher via ajax request from javascript using button. Also a button which stops that watcher.
$continue = true;
if(isset($_POST["start"])) {
global $continue;
$continue = true;
checkCredentials();
while($continue) {
watch();
sleep(60);
}
}
if(isset($_POST["stop"])) {
global $continue;
checkCredentials();
$continue = false;
}
$.ajax({
url: "watch.php",
data: { ztop: true },
type: "post",
success: function (result) {
$result.append("<p>" + result.message + "</p>");
}
});
I want to use a thread to do this in php but I don't know how to do ... I want to stop watch when press on button. But the second isset will be executed after 60 seconds... How to stop the watch executed in first isset ?

JQuery and geolocation not sending any data

Good day,
I am trying to create a script that loads my Browser Geolocation and following sends it to a file that saves it.
The problem is. The data does not get send.
And an even bigger problem is that I have tried many things but I am quite clueless.
I added several alerts but the alerts do not show up.
What should the script do?
Run once every five seconds and requesting your GeoLocation.
When you click accept on your phone and accept for all from this source you will have an active GPS alike tracking.
The code :
<script type="text/javascript">
function success(position) {
///SaveActiveGeoLocation();
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(success, error);
}
else{
error('not supported');
}
function SaveGeoLocation(){
var Lat = position.coords.latitude;
var Lon = position.coords.longitude;
var Accuracy = position.coords.accuracy;
///######## SENDING THE INFORMATION BY AJAX
$.ajax({
type : "POST", /// **** SEND TYPE
url : "savegeo.php", /// **** TARGET FILE TO FETCH THE DATA
data : {
'Lat' : Lat,
'Lon' : Lon,
'GeoAccuracy' : Accuracy
},
///######## IN CASE OF SUCCESS
success:function(response){
if( response == "ok" ){
alert('SEND!');
}
else{
alert( "Response = " + response );
}
}
}
);
}
$(document).ready(function() {
$.ajaxSetup({
cache: false
}); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
///alert('HOI!');
SaveGeoLocation();
}, 5000);
// the "10000" here refers to the time to refresh the div. it is in milliseconds.
/// **** DEFAULT LOADING
///SaveGeoLocation();
});
</script>
The file that saves the send POST data :
<?php
include('function.geolocation.class.php');
$geo = new GeoLocation();
$Lat = $_POST['Lat'];
$Lon = $_POST['Lon'];
$GeoAccuracy = $_POST['GeoAccuracy'];
$IP = $geo->GetIP();
$file = 'location.txt';
$address = $geo->getAddress($Lat, $Lon);
$contents = $Lat.'|'.$Lon.'|'.$IP.'|'.$GeoAccuracy.'|'.date('Y-m-d H:i:s').'|'.$address.PHP_EOL;
$handle = fopen($file, 'a');
fwrite($handle, $contents);
fclose($handle);
echo 'ok';
?>
One problem I can see is the variable position does not exists in the context of the SaveGeoLocation method
function success(position) {
//SaveActiveGeoLocation();
window.position = position;
}
function SaveGeoLocation() {
if (!window.position) {
return;
}
//your stuff
}
There is no need to call SaveGeoLocation using interval, you can call SaveGeoLocation from the success callback like
function success(position) {
SaveActiveGeoLocation(position);
}
function SaveGeoLocation(position) {
//your stuff
}
If you want to save the location continuously
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
function saveLocation() {
navigator.geolocation.getCurrentPosition(success, error);
}
function success(position) {
var Lat = position.coords.latitude;
var Lon = position.coords.longitude;
var Accuracy = position.coords.accuracy;
///######## SENDING THE INFORMATION BY AJAX
$.ajax({
type: "POST", /// **** SEND TYPE
url: "savegeo.php", /// **** TARGET FILE TO FETCH THE DATA
data: {
'Lat': Lat,
'Lon': Lon,
'GeoAccuracy': Accuracy
},
///######## IN CASE OF SUCCESS
success: function (response) {}
}).done(function (response) {
if (response == "ok") {
alert('SEND!');
} else {
alert("Response = " + response);
}
}).always(function () {
setTimeout(saveLocation, 5000)
});
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
}
if (navigator.geolocation) {
saveLocation();
} else {
error('not supported');
}
});

AJAX long polling - waiting for php to finish while trying to get to another page

I want to create notification system in my company's erp similar to Facebook one. To maintain good performance, I use long polling - looped ajax querying php script for number of seconds.
Everything works fine, until I try to go to another page inside ERP. When I click any link on the page, everything freezes waiting until background php script is completed, even if I manually killed ajax connection.
JS script is included on every page and starts itself on page load.
function notificationsObject(){
var nl = new Object();
nl.startAjax = function(data){
if(nl.ajaxObject != null) try{ nl.ajaxObject.abort() } catch(e){} finally{nl.ajaxObject = null}
nl.ajaxObject = $.ajax({
url: nl.ajaxUrl, //declared before function declaration
type: 'POST',
data: {data: data}
}).done(function(responseText){nl.ajaxSuccess(responseText)
}).fail(function(responseText){nl.ajaxFail(responseText)});
}
nl.ajaxSuccess = function(response){
console.debug(response);
nl.startAjax();
}
nl.ajaxFail = function(response){
//#todo some code here
}
nl.killConnection = function(){
if(nl.ajaxObject != null) try{ nl.ajaxObject.abort() } catch(e){} finally{nl.ajaxObject = null}
console.debug('killing');
}
(more code here)
return nl;
}
init code looks like this
$(document).ready(function(){
var notifications = notificationsObject();
notifications.startAjax({name: 'startup'});
setTimeout(function(){window.onbeforeunload = function(){notifications.killConnection()};}, 1000);
});
and there's also some PHP code:
public function executeUsersNotificationListener(){
ignore_user_abort(false);
ob_end_flush();
$this->getResponse()->setHttpHeader("Cache-Control", "no-cache");
$this->getResponse()->setHttpHeader("Pragma", "no-cache");
$this->getResponse()->setHttpHeader("Expires", 0);
$timeLimit = 30;
set_time_limit($timeLimit+1);
echo 'test';
$i = 0;
while($i++ < $timeLimit){
echo " ";
sleep(1);
}
return sfView::NONE;
}
as you can see above, I did some research and used ignore_user_abort and so on, but it won't work.

NGiNX Http Push Module - broadcast behaves random

The symptoms: I have the "push_listener_concurrency" set to "broadcast" but only several (random amount) of subscribers get the message. Was anybody dealing with this type of problem? The test cases are pretty straight-forward I 'POST' to a '/publisher?cid=test' channel and 'GET' from a '/listener?cid=test' everything seems to be working when there's only one client per channel...
Just in case somebody will face the same problem.
There were a problem with headers. To listen the nginx http push module correctly with jQuery you should use a listener that processes the headers correctly here is my code:
function Listener(url, successCallback, failureCallback) {
var scope = this;
var etag = 0, lastModified = 0;
var launched = false;
var failure = false;
this.successTimeout = 0;
this.failureTimeout = 5000;
var getTimeout = function () {
return failure ? this.failureTimeout : this.successTimeout;
};
var listen = function () {
$.ajax(scope.ajaxOptions);
}
var beforeSend = function (jqXHR) {
jqXHR.setRequestHeader("If-None-Match", etag);
jqXHR.setRequestHeader("If-Modified-Since", lastModified);
};
var complete = function (jqXHR) {
var timeout = getTimeout();
etag = jqXHR.getResponseHeader('Etag');
lastModified = jqXHR.getResponseHeader('Last-Modified');
var timeout = jqXHR.statusText == 'success' ? scope.successTimeout : scope.failureTimeout;
if (timeout > 0) {
setTimeout(listen, timeout);
} else {
listen();
}
};
this.ajaxOptions = {
url : url,
type : 'GET',
async : true,
error : failureCallback,
success : successCallback,
dataType : 'json',
complete : complete,
beforeSend : beforeSend,
timeout: 1000 * 60 * 60 * 24
};
this.start = function (timeout) {
if (!launched) {
if (typeof(timeout) == 'undefined' || timeout == 0) {
listen();
} else {
setTimeout(listen, timeout);
}
launched = true;
}
};
}

Categories