I was wondering if it is possible to access windows performance counters using php?
Basically, I already have a PHP application, and I have a basic vb script that accesses the performance counters and creates variables from them. What I need is to be able to access these same performance counters using PHP and therefore set them as variables within my PHP application.
If that isn't possible, is there a way I can use the vb script within the PHP application to use the variables? I would rather not do it this way as I have limited knowledge in that sense, but if that is the only way I will have to learn.
I can post the code if and when required, however for now I just need to know if what I'm asking is possible.
Thanks
EDIT:
My vb code is as follows:
Imports Microsoft.VisualBasic
Imports Microsoft.VisualBasic.CompilerServices
Imports Microsoft.Win32
Imports System
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports System.Data.SqlClient
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim perfActiveUsers As New PerformanceCounter("ASP.NET Apps v2.0.50727", "Sessions Active", "__Total__")
Dim perfAlcInstances As New PerformanceCounter("Alchemy Web Pool Manager", "Alchemy Instances Active")
Dim perfAlcAvgResponse As New PerformanceCounter("Alchemy Web Pool Manager", "Request Average Response Time")
Dim perfAlcQueue As New PerformanceCounter("Alchemy Web Pool Manager", "Requests Queued")
Dim perfAlcTimeout As New PerformanceCounter("Alchemy Web Pool Manager", "Requests Timed Out")
Dim perfAlcTotal As New PerformanceCounter("Alchemy Web Pool Manager", "Requests Total")
Dim totalDBs As String = "0"
Dim SQLStr As String
Dim ConnString As String = "Server=ALCHEMYSVR\SQLEXPRESS;Database=AuServer;Integrated Security=SSPI;User Id=STORETECSERVICE\administrator;Password=westend"
Dim SQLConn As New SqlConnection() 'The SQL Connection
Dim SQLCmd As New SqlCommand() 'The SQL Command
Dim SQLdr As SqlDataReader 'The Local Data Store
SQLStr = "SELECT COUNT (*) FROM AusDatabase"
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open() 'Open the connection
SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
SQLCmd.CommandText = SQLStr 'Sets the SQL String
SQLdr = SQLCmd.ExecuteReader 'Gets Data
Do
While (SQLdr.Read()) 'While Data is Present
totalDBs = SQLdr(0)
MsgBox(SQLdr(0)) 'Show data in a Message Box
End While
Loop While SQLdr.NextResult() 'Move to the Next Record
SQLdr.Close() 'Close the SQLDataReader
SQLConn.Close() 'Close the connection
'Display The Values
lblAlcInstances.Text = perfAlcInstances.NextValue()
lblActiveUsers.Text = perfActiveUsers.NextValue()
Label1.Text = perfAlcAvgResponse.NextValue()
Label2.Text = perfAlcQueue.NextValue()
Label3.Text = perfAlcTimeout.NextValue()
Label4.Text = perfAlcTotal.NextValue()
Label5.Text = totalDBs
End Sub
End Class
It is the performance counter values that are assigned to the labels at the bottom that I require passing to php as a variable. I have tried the PHP exec but cant grasp how I pass the variables in the vb script to variables in PHP.
It can get a little nasty if you try to fetch windows system data via PHP.
If you already have a VB script, you have two common options:
use exec and parse the data from your script. i would NOT recommend that.
add a little more code to your VB script: it should run periodically and write the current data into a database/key-value-storage/textfile from where you can retrieve the data via php
Related
I am working on a project where I have a simple conveyor program done in Visual Basic. I have a button on a website which when pressed writes a "1" into a text file via a simple PHP server program. The VB conveyor system monitors the text file and if it has the value of "1" the conveyor stops. I then have a reset button on the VB program that when pressed should write a "0" into the text file and allow the conveyor to restart. I was able to get the VB program to monitor the text file, and it works accordingly, but I can't get the reset button to write the "0" into the text file.
The code that reads the file is:
Dim remoteStatus As New WebClient()
Dim data = remoteStatus.DownloadString("http://www.users.wfleitz.com/fleitzwc/example.txt")
Console.WriteLine(data)
Console.Read()
Dim remoteEnable As Boolean
If data.Trim = "0" Then
remoteEnable = True
ElseIf data.Trim = "1" Then
remoteEnable = False
Else
remoteEnable = False
End If
The code I have been trying to use to write to the text file is:
Private Sub PushButton1_Load(sender As Object, e As EventArgs) Handles PushButton1.Click
Dim resetEvent As New WebClient()
Dim textAddress As String = "http://www.users.miamioh.edu/fleitzwc/example.txt"
Dim resetCommand As String = "0"
Dim resetArray As Byte() = Encoding.ASCII.GetBytes(resetCommand)
Dim resetStream As Stream = resetEvent.OpenWrite(textAddress, resetCommand)
resetStream.Write(resetArray, 0, resetArray.Length)
resetStream.Close()
End Sub
One other thing that i was thinking about, was rather than have the VB program write to the text file, have it talk to the PHP file that contains the code for the website, and have it send the "0" value. I didn't know if that would be cleaner or not.
If anyone could point me in the right direction it would be greatly appreciated.
Thank you in advance,
Wfleitz
What I would do in your case is use PHP as you said.
<?php
/*
Upload this to http://www.users.miamioh.edu/fleitzwc/script.php or something like that.
Do either
http://www.users.miamioh.edu/fleitzwc/script.php?bar=get or
http://www.users.miamioh.edu/fleitzwc/script.php?bar=reset
*/
$foo = $_GET['bar'];
if ($foo=="get"){
echo file_get_contents("example.txt");
}
if ($foo=="reset"){
file_put_contents("example.txt","0");
}
This should work finely for what you are doing. It is somewhat incomplete though because I didn't fully pay attention to the details of the question but I think you are able to modify it to work with your needs. If not, I can update it.
I've got a Minecraft Software written in C# that I want to send a heartbeat to my site. I've got the way to send the beat already written.
if (Server.Uri == null) return;
string uri = "http://GemsCraft.comli.com/Heartbeat.php";
// create a request
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
// turn request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(string.Format("ServerName={0}&Url={1}&Players={2}&MaxPlayers={3}&Uptime={4}",
Uri.EscapeDataString(ConfigKey.ServerName.GetString()),
Server.Uri,
Server.Players.Length,
ConfigKey.MaxPlayers.GetInt(),
DateTime.UtcNow.Subtract(Server.StartTime).TotalMinutes));
request.ContentType = "application/x-www-form-urlencoded";
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
request.ContentLength = postBytes.Length;
request.Timeout = 5000;
Stream requestStream = request.GetRequestStream();
// send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Flush();
requestStream.Close();
/* try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Logger.LogToConsole(new StreamReader(response.GetResponseStream()).ReadToEnd());
Logger.LogToConsole(response.StatusCode + "\n");
}
catch (Exception ex)
{
Logger.LogToConsole("" + ex);
}*/
}
Now, I want to be able to retrieve the heartbeat in PHP, upload it to the SQL database, and then display each user's server in a table that will be displayed on the webpage
How do I do this?
portforwardpodcast's answer isn't very well-suited for your purposes, here's a process for you to ponder
Server accesses the following page: heartbeat.php?port=25565&maxplayers=25&players=2&name=Cheese_Pizza_Palace
Your PHP script will then do the following...
Go through each value, making sure they're all the types you want them to be (integers/strings)
Connect to the database
Update the server in the database if it already exists, create it if it doesn't
Return some value so the server knows that it completed successfully.
And to display the servers
Fetch all 'active' servers
Loop through them and display each one.
Things you'll need to figure out:
How to determine uptime
How to determine "active" servers
How to update/create MySQL entries
How to (properly) connect to a database. I would suggest using PDO since you're using PHP. It's a bit difficult to learn, but it's much more secure than writing the queries directly.
How to loop through all the GET variables.
Good hunting!
I would create a simple php page accept a get variable. something like www.site.com/beat.php?lasttime=123456&serverid=1 where the number us the unix timestamp. Then you need to re-work your c# to do a simple get request on a website. Finally your php should insert into a mysql table with a column for id, timestamp, server_id etc.
First you need to pull the data from the request. The $_REQUEST variable in php is nice because it works for both GET and POST:
http://php.net/manual/en/reserved.variables.request.php
Start out by var_dump or echo the fields you want. Once you can get the needed data into variables you are done with the first part. For the next part you need to create a database and table in MySQL. The best tool for this is phpmyadmin. If you have a host like godaddy (or some others) you can get at this from the control panel. If not you may need to install upload the phpmyadmin files yourself. It's a pretty simple tool to use:
http://www.youtube.com/watch?v=xxQSFHADUIY
Once your database has the correct columns, you need to insert the data from your php file. This page should help:
http://www.w3schools.com/php/php_mysql_insert.asp
I'm looking for an efficient and secure way to store small amount of user data like a line of text, for an indefinite period of time.
The scenario: One client 'A' sends some data to another client 'B' , asynchronously via a server 'S'. For simplicity, consider the data to be a single line of text. Now, this data would be delivered to client 'B' by server 'S' , only when B asks for it. So until that time Server 'S' has to store this data.
For a simple demo, I implemented it very crudely as follows: Client 'A' does a POST request with XMLHttpRequest, sending the text to 'S' as follows
xhr.open("POST",url+"?sentText=text"); //url points to a php file on S
xhr.send();
The PHP code then saves the received text to a file as follows:
<?php
$selected = $_GET["sentText"];
$writefile = "text.txt";
$fh = fopen($writefile,'w');
fwrite($fh,$selected);
fclose($fh);
?>
Later, after any amount of time, B asks for the text in this file,using BufferedInputStream as follows:
URL fileurl = new URL("url/text.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(fileurl.openStream()));
while((tmpReceived = in.readLine())!=null){
received = tmpReceived;
}
This demo works properly, but this is just a demo. However, if this were to be a full scale real world application with millions of users, how would I implement the following:The part where server S stores the text. Obviously, I can't save the text as plain text in a file, as it would breach my users' privacy. And it would also be ineffecient when there are millions of users. How do commercial services like Dropbox achieve this?
To keep things simple, I just need to know how to do this for text, then I can extrapolate to other types possibly.
Thanks a lot!
I'm trying to create a proxy for cross-domain AJAX POST queries and, in order to do that, I need to be adding the cookies from my client (browser)'s request into the POST request I send to the PHP backend, which is using HttpWebRequest. In order to do this, I'm adding each of the Request.Cookie into the HttpWebRequest.CookieContainer object. For some reason, none of the cookies I add to it ever get to my PHP backend.
I understand from some searches that the CookieContainer object is URI-dependent (I'm not sure how to even explain it!), so perhaps that's the cause of my issues. However, I've tried setting the domain on my cookie to different things and it doesn't seem to affect it. So maybe URI means something different than the Cookie's Domain parameter. If that's the case, I'm stuck.
I'm all for an alternate solution if it exists (if there's a way to do an automatic cross-domain proxy in asp.net without the need for a plugin, that'll save my life!).
Here's the code I'm using.
<%# Page Language="VB" validateRequest="false" Debug="true" %>
<%# Import Namespace="System.IO" %>
<%# Import Namespace="System.Net" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim displayValues As New StringBuilder()
Dim CookieJar as New CookieContainer
Dim objCookieColl as HttpCookieCollection
Dim objThisCookie As HttpCookie
Dim myCookie As HttpCookie
Dim arr1() As String
Dim myCount as Integer
objCookieColl = Request.Cookies
arr1 = objCookieColl.AllKeys
Dim postedValues As NameValueCollection = Request.Form
Dim nextKey As String
For i As Integer = 0 To postedValues.AllKeys.Length - 1
nextKey = postedValues.AllKeys(i)
If nextKey.Substring(0, 2) <> "__" Then
displayValues.Append("&" & nextKey)
displayValues.Append("=")
displayValues.Append(Server.UrlEncode(postedValues(i)))
End If
Next
Dim uri As New Uri("http://www.otherdomain.com/subfolder/backend.php")
Dim data As String = displayValues.ToString
If (uri.Scheme = uri.UriSchemeHttp) Then
Dim postRequest As HttpWebRequest = HttpWebRequest.Create(uri)
For index As Integer = 1 to UBound(arr1)
objThisCookie = objCookieColl(arr1(index))
Dim tempCookie As New Cookie(objThisCookie.Name, objThisCookie.Value, objThisCookie.Path, Request.ServerVariables("HTTP_HOST"))
myCount = myCount + 1
CookieJar.Add(tempCookie)
Next
postRequest.CookieContainer = CookieJar
postRequest.Method = Request.HttpMethod
postRequest.ContentLength = data.Length
postRequest.ContentType = "application/x-www-form-urlencoded"
Dim writer As New StreamWriter(postRequest.GetRequestStream())
writer.Write(data)
writer.Close()
Dim myResponse As HttpWebResponse = postRequest.GetResponse()
Dim x As Integer
While x < myResponse.Headers.Count
Response.AppendHeader(myResponse.Headers.Keys(x), myResponse.Headers(x))
x = x + 1
End While
Dim reader As New StreamReader(myResponse.GetResponseStream())
Dim responseString As String = reader.ReadToEnd()
myResponse.Close()
Response.Write(responseString)
End If
End If
End Sub
</script>
I'm not familiar with how ASP sets, stores, and handles cookies. But on your PHP backend try
<?php
echo "<pre>";
print_r($_COOKIE);
echo "</pre>";
?>
this way you can see if the PHP is even finding any cookies that remotely look like the cookie your trying to read. I do have to say though, mixing languages like this is not something I would advise, though I am sure there is decent logic behind this need. May I suggest a possible alternative. Bridge the gap with maybe some JavaScript. Set your variables up like you want them stored in the cookie, then use JavaScript to Set a cookie.
http://www.w3schools.com/JS/js_cookies.asp for reference of how to set up a cookie via JavaScript I know with PHP I can retieve a cookie I set with JavaScript so hopefully this helps out some, and what I know of ASP you should be able to use JavaScript there as well.
Grant it this isn't an end all be all solution, may not be the best either. I wouldn't use this concept on a lot of things you may be trying to connect the front and the back with but I can't see to much harm with one to another.
You mean that you have a site that is run using .Net (asp in your situation) and then you want to pass the cookie on to another application running PHP? I think the cookies are prevented from being shared with another "site" since this is not supposed to be done. It is often used as an attack vector of hackers and thus I would be that you server is trying to prevent it.
A project of mine involves a flash movie (.swf) in a webpage, where the user has to pick from a number of items, and has the option to thumbs up or thumbs down (vote on) each item.
So far I have gotten this to work during each run of the application, as it is currently loading the data from an XML file - and the data is still static at the moment.
I need to persist these votes on the server using a database (mySQL), such that when the page is reloaded, the votes aren't forgotten.
Has anyone done this sort of thing before?
The two mains methods that I have found on the 'net are
either direct communication between AS3 and the SQL using some sort of framework, or
passing the SQL query to a PHP file, which then executes the SQL query and returns the SQL to AS3.
Which of these methods is the better option?
For the latter method (involving PHP), I have been able to find resources on how to acheive this when attempting to retrieve information from the database (i.e. a read operation), but not when attempting to send information to the database (i.e. a write operation, which is needed when the users vote). How is this done?
Thank you!
Edit: Implemented solution
Somewhere in the PHP file:
if ($action == "vote")
{
$id = $_POST['id'];
$upvotes = $_POST['upvotes'];
$query = "UPDATE `thetable` SET `upvotes` = '$upvotes' WHERE `thetable`.`id` = '$id' LIMIT 1 ;";
$result = mysql_query($query);
}
Somewhere in the ActionsScript:
public function writeToDb(action:String)
{
var loader:URLLoader = new URLLoader();
var postVars:URLVariables = new URLVariables();
var postReq:URLRequest = new URLRequest();
postVars.action = action;
postVars.id = id;
postVars.upvotes = upvotes;
postReq.url = <NAME_OF_PHP_FILE>;
postReq.method = URLRequestMethod.POST;
postReq.data = postVars;
loader.load(postReq);
loader.addEventListener(Event.COMPLETE, onWriteToDbComplete);
}
I am not aware of any framework that supports method-1.
I would use method-2 - but instead of making the query within Flash and passing it to PHP, I would rather pass the related data and construct the query in PHP itself. This is safer because it is less susceptible to SQL injection attacks.
This answer has an example of sending data from flash to the server - it talks about ASP, but the method is same for PHP (or any technology) - just change the URL.
Within the php code, you can read the sent data from the post $_POST (or $_GET) variable.
$something = $_POST["something"]
Many different options:
AMFPHP - binary messaging format between PHP and Actionscript/Flash.
LoadVars - for POSTing and GETing values to a PHP script.
JSON - Using the AS3Corelib you can post JSON formatted data to your web site (just like an AJAX script does).