I have a vb.net application where i am sending error string to a php page to process it.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim errorString As String = "test string"
Dim request As WebRequest = WebRequest.Create("http://10.0.0.1/test.php")
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(errorString)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
MsgBox(responseFromServer)
End Sub
The responseFromServer is empty. Doesn't show the errorString.
My php page for testing looks like this:
<?php
if (isset($_POST['errorString']))
{
$a = $_POST['errorString'];
echo $a;
}
else
{
echo "ERROR: No data!";
}
?>
Does anyone know what I am missing? Any help would be greatly appreciated.
Thanks in advance!
In your request string you have to add key value parameters like this,
Dim errorString As String = "errorString=test string"
This is because in php code you are using errorString as POST parameter to receive data for that key value, so always send data with respect to the POST/GET key you are using in PHP code.
I am having trouble sending the post variable to received in the PHP document in my server. I tried it with the GET and it works fine. But what I notice is the POST VARIABLE doesn't receive the content I am sending. This is my code:
VB.NET WINFORM CODE
enter code here
Dim Username = TxtUser.Text
Dim PostData = "user_name=" & Username
Dim request As WebRequest = WebRequest.Create("http://website.com/test.php")
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(PostData)
request.ContentType = "application/x-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
MsgBox(responseFromServer)
PHP CODE
<?php
//I tried this $user_name= 'SOMETHING'; and works fine.
$user_name= $_POST['user_name'];
?>
Changing the ContentType should do the trick.
request.ContentType = "application/x-www-form-urlencoded"
I am trying to send a document file from Lotus Script to a web server and save it there. Unfortunately the file transfer does not work. I have a Lotusscript agent to get the document and this part is working ( str_filecontent contains the correct xml file ), but the file transfer or saving is not working. Here is my Lotusscript agent:
Option Public
Option Declare
Sub Initialize
'Declare long
Dim lng_resolveTimeout, lng_connectTimeout, lng_sendTimeout, lng_receiveTimeout As Long
'Declare integer
Dim int_serverCredentials As Integer
'Declare variants
Dim var_submitObject As Variant
'Set values
int_serverCredentials = 0
lng_resolveTimeout = 120000 'miliseconds = 2 minutes
lng_connectTimeout = 1200000
lng_sendTimeout = 1200000
lng_receiveTimeout = 1200000
'Create HTTP object
Set var_submitObject = CreateObject("WinHTTP.WinHTTPRequest.5.1")
Call var_submitObject.SetTimeouts(lng_resolveTimeout, lng_connectTimeout, lng_sendTimeout, lng_receiveTimeout)
'Standards for this post
%REM
Content-Type: multipart/form-data; boundary={boundary}
{boundary}
Content-Disposition: form-data; name="data"; filename="{filename}"
Content-Type: text/plain
{contents}
{boundary}--
%END REM
Dim str_url As String
str_url = "http://.../upload.php"
Dim str_AUTH As String
Dim str_boundary As String
Dim str_filecontent As String
str_filecontent = get_data()
Dim submitHTTP
'Set post parameters
Call var_submitObject.open("POST", str_url, False)
Call var_submitObject.setRequestHeader("Accept", "application/xml")
Call var_submitObject.setRequestHeader("Authorization", "Basic " & str_auth)
Call var_submitObject.setRequestHeader("Content-Type", "multipart/form-data; boundary=b1")
str_boundary = |--b1| & Chr(13) & Chr(10) &_
|Content-Disposition: form-data; name="data"; filename="name.txt"| & Chr(13) & Chr(10) &_
|Content-Type: text/plain| & Chr(13) & Chr(10) &_
str_fileContent & |b1--|
'Send the HTTP request
Call var_submitObject.Send(str_boundary)
'Wait for the answer and set object as returned value for further validation
Call var_submitObject.WaitForResponse
Set submitHTTP = var_submitObject
'Clear memory
Set var_submitObject = Nothing
End Sub
%REM
Function get_data
Description: Comments for Function
%END REM
Function get_data() As String
Dim session As New NotesSession
Dim doc As NotesDocument
' Dim db As NotesDatabase
Dim exporter As NotesDXLExporter
' Set db = session.CurrentDatabase
Dim workspace As New NotesUIWorkspace
Dim uidoc As NotesUIDocument
Set uidoc = workspace.CurrentDocument
Set doc = uidoc.Document
' Set doc = SESSION.CU
Set exporter = session.CreateDXLExporter
get_data = exporter.Export(doc)
Print get_data
End Function
Here is my web server PHP to receive and save the file:
<?php
define("UPLOAD_DIR", "/temp/");
if (!empty($_FILES["data"])) {
$myFile = $_FILES["data"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
?>
Thanks for your time!
I am trying get string result from PHP webservice in my android application, I used ksaop2 library and this is my code :
env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
request = new SoapObject("customWebService","addProductToCart");
request.addProperty("sessionID", sessionId);
request.addProperty("cartID", cartID);
request.addProperty("productID", productID);
request.addProperty("qty", qty);
request.addProperty("sku", productSKU);
env.setOutputSoapObject(request);
androidHttpTransport = new HttpTransportSE(
"http://mysiteeee.com/WebServiceSOAP/server.php?wsdl/",
60000);
androidHttpTransport.debug = true;
androidHttpTransport.call("", env);
result = env.getResponse();
It`s returned this:
???·???§?? ?¯?²?????? (???§??) ?§???²?§???? ????µ???? ?±?§ ???´?®?µ ?©?????¯.
I tested it on Chrome and Firefox with UTF-8 encoding and shows result correctly on browser.
How can I get result from web service with correct encoding and show it on android?
Try getting response this way :
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
String Test1 = result.getProperty(0).toString();
Edit : Try setting Xml header Tag for request :
androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
I'm trying to upload an image file to a PHP file on a web server.
On VB.NET ->
My.Computer.Network.UploadFile(tempImageLocation, "website.com/upload.php")
tempImageLocation is a location on the harddrive where the image is located. The image is located on the harddrive where I specify it.
On PHP ->
$image = $_FILES['uploads']['name'];
I don't understand, because it is loading the page - but PHP can't find the file under 'uploads'
Google brought me here while I was searching for the same question. Thanks people it gave me the idea, and with a little knowledge of PHP, I've achieved it. I know its an old question but still I'm going to share my code so it could help people in future..
VB:
My.Computer.Network.UploadFile("e:\file1.jpg", "http://www.mysite.com/upl/upl.php")
PHP:
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
and don't forget to give the upload folder the appropriate permissions.
I know, is old.. but here is solution work to me:
Private Sub HttpUploadFile(
ByVal uri As String,
ByVal filePath As String,
ByVal fileParameterName As String,
ByVal contentType As String)
Dim myFile As New FileInfo(filePath)
Dim sizeInBytes As Long = myFile.Length
Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
Dim newLine As String = System.Environment.NewLine
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
Dim request As Net.HttpWebRequest = Net.WebRequest.Create(uri)
request.ContentType = "multipart/form-data; boundary=" & boundary
request.Method = "POST"
request.KeepAlive = True
'request.Credentials = Net.CredentialCache.DefaultCredentials
Using requestStream As IO.Stream = request.GetRequestStream()
Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}"
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3};"
Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType)
header = header & vbNewLine & "Content-Length: " & sizeInBytes.ToString & vbNewLine
header = header & "Expect: 100-continue" & vbNewLine & vbNewLine
'MsgBox(header)
Debug.Print(header)
Dim headerBytes As Byte() = Encoding.UTF8.GetBytes(header)
requestStream.Write(headerBytes, 0, header.Length)
Using fileStream As New IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read)
Dim buffer(4096) As Byte
Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)
Do While (bytesRead > 0)
requestStream.Write(buffer, 0, bytesRead)
bytesRead = fileStream.Read(buffer, 0, buffer.Length)
Loop
End Using
Dim trailer As Byte() = Encoding.ASCII.GetBytes(newLine & "--" + boundary + "--" & newLine)
requestStream.Write(trailer, 0, trailer.Length)
requestStream.Close()
End Using
Dim response As Net.WebResponse = Nothing
Try
response = request.GetResponse()
Using responseStream As IO.Stream = response.GetResponseStream()
Using responseReader As New IO.StreamReader(responseStream)
Dim responseText = responseReader.ReadToEnd()
Debug.Print(responseText)
End Using
End Using
Catch exception As Net.WebException
response = exception.Response
If (response IsNot Nothing) Then
Using reader As New IO.StreamReader(response.GetResponseStream())
Dim responseText = reader.ReadToEnd()
Diagnostics.Debug.Write(responseText)
End Using
response.Close()
End If
Finally
request = Nothing
End Try
End Sub
Using:
HttpUploadFile("https://www.yousite.com/ws/upload.php?option1=sss&options2=12121", FULL_FILE_NAME_PATH_IN_YOUR_PC, "files", "multipart/form-data")
I copy somen code in a website i dont remember.
I only put this 2 lines of code to work:
header = header & vbNewLine & "Content-Length: " & sizeInBytes.ToString & vbNewLine
header = header & vbNewLine & "Expect: 100-continue" & vbNewLine
hope help.
Here is the complete example for uploading file using Visual Basic and on Server Side PHP (Rest API) GitHub Link
Here is quick and dirty tutorial for you: PHP File Upload
'uploads' is just name attribute value of element of a form:
<input type="file" name="uploads" />
or in other words, this is POST variable name that is accessed over $_FILES global.
If you don't set the field name, you can save the uploaded file with this
$file = array_shift($_FILES);
move_uploaded_file($file['tmp_name'], '/path/to/new/location/'.$file['name']);
Take a look at some of these other answers. PHP requires files uploaded with the POST method to use certain headers which are normally set by the browser when uploading from a web form but which can be set in VB with the HttpWebRequest Class.
As for the PHP side, you aren't going to be able to locate the file immediately after uploading with $image = $_FILES['uploads']['name'];. PHP stores uploads with a temporary filename accessible with the $_FILES['uploads']['tmp_name'] variable, and using move_uploaded_file() is the standard way of shifting uploads from temporary storage into a permanent uploads directory. The PHP manual provides a good overview of that.
Here's my sample server php file:
<?php
// write to a log file so you know it's working
$msg = $_POST['w'];
$logfile= 'data.txt';
$fp = fopen($logfile, "a");
fwrite($fp, $msg);
fclose($fp);
$file = array_shift($_FILES);
move_uploaded_file($file['tmp_name'], '/MAMP/htdocs/test/'.$file['name']);
?>
Here's the code to call #Rodrigo's code:
HttpUploadFile("http://localhost/test/test.php?w=hello&options2=12121", "C:\temp\bahamas.mp3", "files", "multipart/form-data")