Is there a better way to perform these operations?

I debated trying to do these as functions, or as items that can be called by a ajax script, but decided to go this route (not sure why). My question is, is there a better way I could have written it.

Additionally, how complex is it to have these be able to be performed by an ajax function. I’ve not used ajax as it seems to be somewhat complex as opposed to say jQuery.

Essentially, what I want to do in the grand scheme is when a user clicks an icon, we’ll use RESTART for example, I want the action to be loaded into a div that is hidden, and when completed, show a jquery based notification that the action has been completed. I have the styles and everything, I just need the basic idea of what to do.

Full disclosure, I’m rewriting an older script to use PDO, since when it was abandoned, it was using the mysql extension.

Any Ideas? Feedback would be greatly appreciated.

[php]
if (isset($_GET[‘command’]) && ($_GET[‘command’] == “restart”)) {
$db = new Db();
$gettype = $db->query("SELECT * FROM servers WHERE portnum = ".$_GET[‘port’]);

foreach ($gettype as $svr) {
$type = $svr[‘type’];
break;
}

if ($type == “shoutcast”) {
// kill and restart server

$pidfile = fopen($getDataDirectory."shoutcast/".$_GET['port']."/server.pid", "r") or die("Unable to open file!");
$pid = fread($pidfile,filesize($getDataDirectory."shoutcast/".$_GET['port']."/server.pid"));
fclose($pidfile);

//$pid = shell_exec("nohup ".$config['sc_serv']." ".$config['smi_path']."/servers/shoutcast/".$portbase."/".$srvname.".conf > /dev/null & echo $!");
$cleanpid = trim($pid);
exec("echo $cleanpid > ".$getDataDirectory."shoutcast/".$_GET['port']."/server.pid");

// set alert to show
echo "<script>showNotification('success','restarted');</script>";

} else {
echo “”;
}
}

if (isset($_GET[‘command’]) && ($_GET[‘command’] == “start”)) {
$db = new Db();
$gettype = $db->query("SELECT * FROM servers WHERE portnum = ".$_GET[‘port’]);

foreach ($gettype as $svr) {
$type = $svr[‘type’];
$port = $svr[‘portnum’];
$srvname = $svr[‘servername’];
break;
}

if ($type == “shoutcast”) {
// kill and restart server

  $sc_conf = $getDataDirectory."shoutcast/".$port."/server.conf";
  // Check that config file exists before trying to launch
    
    $cmdstr = shell_exec($getShoutcastBinary." ".$getDataDirectory."shoutcast/".$port."/server.conf > /dev/null & echo $!");
    $pid = shell_exec($cmdstr);

	$cleanpid = trim($pid);

	// Write PID to file
	$fd = fopen($getDataDirectory."shoutcast/".$port."/".$srvname.".pid", "w+");
	fputs($fd, $cleanpid);
	fclose($fd);
  } else {
echo "Icecast";

}
}

if (isset($_GET[‘command’]) && ($_GET[‘command’] == “stop”)) {
$db = new Db();
$gettype = $db->query("SELECT * FROM servers WHERE portnum = ".$_GET[‘port’]);

foreach ($gettype as $svr) {
$type = $svr[‘type’];
$port = $svr[‘portnum’];
$srvname = $svr[‘servername’];
break;
}

if ($type == “shoutcast”) {
// kill and restart server
$pidfile = fopen($getDataDirectory.“shoutcast/”.$_GET[‘port’]."/server.pid", “r”) or die(“Unable to open file!”);
$pid = fread($pidfile,filesize($getDataDirectory.“shoutcast/”.$_GET[‘port’]."/server.pid"));
fclose($pidfile);

$killserver = shell_exec("kill -9 ".$pid);

if ($killserver) {
	shell_exec("rm ".$getDataDirectory."shoutcast/".$port."/".$srvname.".pid");	
} else {
	die("Failed to kill server");
}

} else {
echo “Icecast”;
}
}
[/php]

[member=71845]JimL[/member] I’d love to get your feedback.

Happy New Year BTW! Thanks for reading my post! (to everyone, not just Jim!! HAHA That would be rude!)

This should never be done. Inserting untrusted data into the query string will allow any malicious user to at best read, or at worst tamper with / destroy your data or server.

Ajax

Ajax (also AJAX; /ˈeɪdʒæks/; short for asynchronous JavaScript and XML)[1][2][3] is a set of web development techniques using many web technologies on the client-side to create asynchronous Web applications. With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows for web pages, and by extension web applications, to change content dynamically without the need to reload the entire page.[4] In practice, modern implementations commonly substitute JSON for XML due to the advantages of being native to JavaScript.

Jquery

jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML

Ajax is simply to make a HTTP request in javascript. Depending on which browsers you want to support, jQuery may not be necessary to use at all these days.

What you need to understand when making a request (GET, POST or whichever) in javascript it’s that the request is fully handled in javascript. This means that your javascript code will receive the response returned from the request. Normally this is a JSON response (JavaScript Object Notation) as it’s a light weight (suitable for small requests/responses) data set that javascript can read by default.

To make your PHP script suitable you should change all output to use json_encode, so you get a json string your javascript code can make use of.

To make the request from javascript is very simple, especially with jQuery.

[php]$.get( “control.php”, { command: “restart”, port: 8000 } )
.done(function( data) {
alert( "Command executed: " + data);
})
.fail(function() {
alert( “Command failed” );
});[/php]

vs vanilla javascript (no jquery)
[php]var request = new XMLHttpRequest();
request.open(‘GET’, ‘control.php?command=restart&port=8000’, true);

request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var data = JSON.parse(this.response);
alert( "Command executed: " + data );
} else {
alert( “Command failed” );
}
};

request.onerror = function() {
alert( “Command failed” );
};

request.send();[/php]

[member=71845]JimL[/member] I’ve tried to use json_encode in the past and it never seems to work out for me.

Can you take the code I’ve written and include an example of the way you would write it?

Additionally I can’t seem to call the external JS function for the ajax snippet you sent (i made a function to import command data)

function restartserver(serverid, portnum) {
	// make icon spin while performing actions
	$("spin_" + serverid).addClass("fa-spin");
	
	// execute command to restart server
	$.post( "control.php", { command: "restart", serverid: serverid, port: portnum } )
	.done(function( data) {
		$("#spin-" + serverid).removeClass("fa-spin");
		alert( "Command executed: " + data);
	})
	.fail(function() {
		$("#spin-" + serverid).removeClass("fa-spin");
		alert( "Command failed" );
	});	
}

The PHP code that calls the function is below.
[php]
echo ‘

<a href=“javascript:void(0);” onclick=javascript:restartserver(’.$server[‘id’].’, ‘.$server[‘portnum’].’);" data-toggle=“tooltip” title="" data-original-title=“Restart Server”>  ';
[/php]

In this instance, $server[‘id’] = 1, and portnum equals 8000. For reference of course.

Just curious why don’t you simply do a php or html header redirect?

How do you know it isn’t working? if you are referring to the spinning class change, the id is wrong in the function.

My apologies. I’ve actually fixed the issue. Forgot to post that. What with the holiday and all.

Sponsor our Newsletter | Privacy Policy | Terms of Service