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.
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 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'm currently researching this as we speak. Putting this question here hoping to see some awesome insights. Here's my question:
I am developing an android application that downloads files from my web server to be displayed in the app, and available for offline use.
If my app goes to https://www.mydomain.com/abc/xyz.png to download the file, how can I make that same url not publicly available? i.e. if you type https://www.mydomain.com/abc/xyz.png into your browser address bar, you will be taken somewhere other than the png file.
I think I need some kind of wrapper here, but I'm new to all of this and trying to learn fast.
Any help is appreciated.
For what it's worth, I will be using a mySql database with either workbench 6.0 or phpMyAdmin.
EDIT
In response to the first two responses:
So my code here in my android app where I download the file and save it to internal storage that looks like this (where base path gets me to the web directory of the file):
url = new URL(basePath + fileName);
URLConnection connection = url.openConnection();
int lenghtOfFile = connection.getContentLength();
inputStream = new BufferedInputStream(url.openStream());
outFile = new File(context.getFilesDir() + "/" + fileName);
fileStream = new FileOutputStream(outFile);
outputStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
would change to say:
url = new URL(basePath + "download_file.php" + "?key=hardcodedkey&file=" + fileName);
URLConnection connection = url.openConnection();
int lenghtOfFile = connection.getContentLength();
inputStream = new BufferedInputStream(url.openStream());
outFile = new File(context.getFilesDir() + "/" + fileName);
fileStream = new FileOutputStream(outFile);
outputStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
You have a few options here.
1.) Not great-> .htaccess to restrict certain referrers, all but Android for example.
2.) Greater -> Use a PHP file to output the image if GET var is the same as the pass. e.g.
if (isset($_GET["pass"]) && $_GET["pass"]=="8h932mgks984jsolm9sjt4ms") {
header('Content-type:image/png');
include('/path/to/thePngFile.png');
} else die("nothing to see here..");
A simple way might be calling a php script with a certain key as secret parameter and the image or file you want to download.
www.myweb.com/myfunction.php?pass=secretPassword&file=image.png
This key will be harcoded in the call from your application.
Then you could just check if the password is the one you expect with something like:
//hardcoded hashed pass with sha1, for example.
$myHashedPass = '40bd001563085fc35165329ea1ff5c5ecbdbbeef';
if(sha1($_GET['pass']) != $myHashedPass){
die();
}
//download of file...
Inside the PHP application you can start the download or not depending on the password.
I'm developing an app in android which connects to a web service in php. The users can send pictures, or better said, will be able to send pictures cause I'm stuck on it, to other users.
Right now the image is sent to the web service via SOAP with type xsd:base64binary. The user take a picture and the byte array with data is converted to base64 before sending it in this way:
String img;
....
#Override
public void onPictureTaken(byte[] data, Camera camera) {
img = Base64.encodeToString(data, Base64.NO_WRAP);
}
In the server side, php stores img string in a mysql BLOB column.
When another user ask for the picture, the server retrieves the data from mysql in a stdClass, not only the image, also id, owner, etc... and encapsulate all this data into a JSON string with the php function json_encode. The return type for this in the WSDL file is xsd:string. Back in Android what I do is:
JSONArray array = new JSONArray(response);
JSONObject row;
String imgStr;
byte[] img;
for (int i = 0; i < array.length(); i++) {
row = array.getJSONObject(i);
...
imgStr = row.getString("image");
...
}
if (!TextUtils.isEmpty(imgStr)) {
img = Base64.decode(imgStr, Base64.NO_WRAP);
}
//Insert byte[] in android SQLite
dao.insert(id, owner, img);
The table column type in SQLite is BLOB as well. The problem comes up when I get the image from SQLite and try to convert it to Bitmap object. The code for this:
...
byte[] img = cursor.getBlob(cursor.getColumnIndex(DB.M_IMG));
Bitmap bmp = BitmapFactory.decodeByteArray(img, 0, img.length);
...
The img byte array seems to be alright but bmp is always null...
Some tests I've done are getting the base64 string on the image owner device before sending it and passing it to bitmap with good results, that's why I think my problem has something to do with encoding or addition of characters by json or php, I don't know...
UPDATE: If I hardcoded the base64 string from the mysql database, no bitmap is created, if I do the same with the base64 string generated in the moment I take the picture then it works.
What am I doing wrong?
After a couple of days with this problem, I have the answer, it was a MySQL issue.
Apparently MySQL BLOB type can just store up to 64Kb (a clue to find the bug is that all images take up the same space of 64 Kb...The aswer was there all along but I couldn't see it...). So the SOLUTION, in my case, has been changing BLOB type in MySQL by LONGBLOB...
Thank you all for your time.
Though I'm still thinking over this, something struck me: why use so much, when you can simply use HttpClient, cookie and retrieve image(s) instead of converting to & fro.
Also if possible, storing Blob is not highly recommended unless your picture size is small. To me, some design changes would make whole code (server & phone) lot more manageable.
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.