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.
Related
I want to send data to my web server from my windows application.
Firstly i was sending data with URL parameters but due to URL lenght limit it was failing with large data. Then i tried to send data like file uploads but my data is not a file. It is very long string(about 4k chars).
So file upload tutorials on internet i replaced FileStream with my byte array but on server side $_FILES variable is an empty array.
Here is my code.
Sub sendData(ByVal data As String)
Dim enc_data As String = EncryptRJ256(data)
Dim byteData() As Byte = Encoding.UTF8.GetBytes(enc_data)
Dim postReq As HttpWebRequest = WebRequest.Create("http://example.com")
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.AllowWriteStreamBuffering = True
postReq.ContentLength = byteData.Length
Dim postreqstream As Stream = postReq.GetRequestStream()
postreqstream.Write(byteData, 0, byteData.Length)
postreqstream.Close()
Dim postresponse As HttpWebResponse
postresponse = postReq.GetResponse()
Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
Dim thepage As String = postreqreader.ReadToEnd
File.WriteAllText("C:\Users\kenar\Desktop\response.txt", thepage)
End Sub
There is nothing to show on server side. I'm using apache web server and checking $_FILES variable on PHP script.
It doesn't appear that you're uploading a file, I suggest trying to check your $_POST instead for data, as i'm guessing before you was checking $_GET. If you want to submit as a file you would have to set the appropriate content type as well.
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 am trying to understand how this web site is working. There is an input form where you can provide a url. This form returns information retrieved from another site (Youtube). So:
My first and more interesting question is if anybody has any idea how this site retrieve the entire corpus of statements?
Alternatively, since now I am using the following code:
from BeautifulSoup import BeautifulSoup
import json
urlstr = 'http://www.sandracires.com/en/client/youtube/comments.php?v=' + videoId + '&page=' + str(npage)
url = urllib2.urlopen(urlstr)
content = url.read()
soup = BeautifulSoup(content)
#parse json
newDictionary=json.loads(str(soup))
#print example
print newDictionary['list'][1]['username']
However, I can not iterate in all pages (which is not happening when I to that manually). I have placed timer.sleep(30) below json but without success. Why is that happening?
Thanks!
Python 2.7.8
Probably using the Google Youtube data API. Note that (presently) comments can only be retrieved using version 2 of the API - which has been deprecated. Apparently no support yet in V3. Python clients libraries are available, see https://developers.google.com/youtube/code#Python.
Response is already JSON, no need for BS. The web server seems to require cookies, so I recommend using requests module, in particular its session management:
import requests
videoId = 'ZSzeFFsKEt4'
results = []
npage = 1
session = requests.session()
while True:
urlstr = 'http://www.sandracires.com/en/client/youtube/comments.php'
print "Getting page ", npage
response = session.get(urlstr, params={'v': videoId, 'page': npage})
content = response.json()
if len(content['list']) > 1:
results.append(content)
else:
break
npage += 1
print results
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
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