Showing posts with label POC. Show all posts
Showing posts with label POC. Show all posts

Saturday, March 21, 2020

C# and NLUA for plugins

C# and NLUA, For my note ONLY



di class C#



--// Ini di class c#
-- SomeClass obj = new SomeClass ("Param");
-- state ["obj"] = obj; // Create a global value 'obj' of .NET type SomeClass


Di NLUA nya


--// Disini starting NLUA scriptnya


local res1 = obj:Text()
obj:MessageBoxing(res1)

local res3 = obj:DownloadStringText('http://nlua.org')
-- obj:MessageBoxing(res3)

Paint the form via LUA ( di gambar dulu biar popout lebih native c# daripada sekedar MessageBox.


NLUA

-- //////////////////////////=====================

-- kevinh - the following lines are part of our standard init
-- require("compat-5.1")

import("System.Windows.Forms")
import("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
import("System.Drawing")


local EnumToObject, WinFormsAnchorStylesType =
                luanet.get_method_bysig(luanet.System.Enum, "ToObject",
                                             "System.Type", "System.Int32"),
                luanet.System.Windows.Forms.AnchorStyles.Top:GetType()

AnchorTop, AnchorLeft, AnchorRight, AnchorBottom = 1, 4, 8, 2

function Anchor(flags)
  return EnumToObject(WinFormsAnchorStylesType, flags)
end



form1=Form()
button1=Button()
richtext1=RichTextBox()
button2=Button()

function handleClick(sender,data)
  if sender.Text=="OK" then
    sender.Text="Clicked"
  else
    sender.Text="OK"
  end
  button1.MouseUp:Remove(handler)
  MessageBox.Show (sender:ToString())
end


button1.Text = "OK"
button1.Location=Point(10,10)
button2.Text = "Cancel"
button2.Location=Point(button1.Left, button1.Height + button1.Top + 10)
richtext1.Location = Point(button2.Left,button2.Height + button2.Top + 10)
richtext1.Size = Size(form1.Width-30, form1.Height - 120)
richtext1.Text = res3
richtext1.Anchor = Anchor(AnchorLeft + AnchorTop + AnchorRight + AnchorBottom)


handler=button1.MouseUp:Add(handleClick)
form1.Text = "My Dialog Box"
form1.HelpButton = true
form1.MaximizeBox=false
form1.MinimizeBox=false
form1.AcceptButton = button1
form1.CancelButton = button2
form1.Controls:Add(button1)
form1.Controls:Add(button2)
form1.Controls:Add(richtext1)
form1:ShowDialog()


FULL Scriptnya



--// Ini di class c#
-- SomeClass obj = new SomeClass ("Param");
-- state ["obj"] = obj; // Create a global value 'obj' of .NET type SomeClass 

--// Disini starting NLUA scriptnya


local res1 = obj:Text()
obj:MessageBoxing(res1) 

local res3 = obj:DownloadStringText('http://nlua.org')
-- obj:MessageBoxing(res3) 

-- //////////////////////////=====================

-- kevinh - the following lines are part of our standard init
-- require("compat-5.1")

import("System.Windows.Forms")
import("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
import("System.Drawing")


local EnumToObject, WinFormsAnchorStylesType = 
                luanet.get_method_bysig(luanet.System.Enum, "ToObject",
                                             "System.Type", "System.Int32"),
                luanet.System.Windows.Forms.AnchorStyles.Top:GetType()

AnchorTop, AnchorLeft, AnchorRight, AnchorBottom = 1, 4, 8, 2

function Anchor(flags)
  return EnumToObject(WinFormsAnchorStylesType, flags)
end



form1=Form()
button1=Button()
richtext1=RichTextBox()
button2=Button()

function handleClick(sender,data)
  if sender.Text=="OK" then
    sender.Text="Clicked"
  else
    sender.Text="OK"
  end
  button1.MouseUp:Remove(handler)
  MessageBox.Show (sender:ToString())
end


button1.Text = "OK"
button1.Location=Point(10,10)
button2.Text = "Cancel"
button2.Location=Point(button1.Left, button1.Height + button1.Top + 10)
richtext1.Location = Point(button2.Left,button2.Height + button2.Top + 10)
richtext1.Size = Size(form1.Width-30, form1.Height - 120)
richtext1.Text = res3
richtext1.Anchor = Anchor(AnchorLeft + AnchorTop + AnchorRight + AnchorBottom)


handler=button1.MouseUp:Add(handleClick)
form1.Text = "My Dialog Box"
form1.HelpButton = true
form1.MaximizeBox=false
form1.MinimizeBox=false
form1.AcceptButton = button1
form1.CancelButton = button2
form1.Controls:Add(button1)
form1.Controls:Add(button2)
form1.Controls:Add(richtext1)
form1:ShowDialog()

Monday, August 22, 2016

Kill Child Process When Parent Exit C#


 

 

Taken from
http://stackoverflow.com/questions/3342941/kill-child-process-when-parent-process-is-killed

for My NOTE



/// <summary>
/// Allows processes to be automatically killed if this parent process unexpectedly quits.
/// This feature requires Windows 8 or greater. On Windows 7, nothing is done.</summary>
/// <remarks>References:
///  http://stackoverflow.com/a/4657392/386091
///  http://stackoverflow.com/a/9164742/386091 </remarks>
public static class ChildProcessTracker
{
    /// <summary>
    /// Add the process to be tracked. If our current process is killed, the child processes
    /// that we are tracking will be automatically killed, too. If the child process terminates
    /// first, that's fine, too.</summary>
    /// <param name="process"></param>
    public static void AddProcess(Process process)
    {
        if (s_jobHandle != IntPtr.Zero)
        {
            bool success = AssignProcessToJobObject(s_jobHandle, process.Handle);
            if (!success)
                throw new Win32Exception();
        }
    }

    static ChildProcessTracker()
    {
        // This feature requires Windows 8 or later. To support Windows 7 requires
        //  registry settings to be added if you are using Visual Studio plus an
        //  app.manifest change.
        //  http://stackoverflow.com/a/4232259/386091
        //  http://stackoverflow.com/a/9507862/386091
        if (Environment.OSVersion.Version < new Version(6, 2))
            return;

        // The job name is optional (and can be null) but it helps with diagnostics.
        //  If it's not null, it has to be unique. Use SysInternals' Handle command-line
        //  utility: handle -a ChildProcessTracker
        string jobName = "ChildProcessTracker" + Process.GetCurrentProcess().Id;
        s_jobHandle = CreateJobObject(IntPtr.Zero, jobName);

        var info = new JOBOBJECT_BASIC_LIMIT_INFORMATION();

        // This is the key flag. When our process is killed, Windows will automatically
        //  close the job handle, and when that happens, we want the child processes to
        //  be killed, too.
        info.LimitFlags = JOBOBJECTLIMIT.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;

        var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
        extendedInfo.BasicLimitInformation = info;

        int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
        IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);
        try
        {
            Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);

            if (!SetInformationJobObject(s_jobHandle, JobObjectInfoType.ExtendedLimitInformation,
                extendedInfoPtr, (uint)length))
            {
                throw new Win32Exception();
            }
        }
        finally
        {
            Marshal.FreeHGlobal(extendedInfoPtr);
        }
    }

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string name);

    [DllImport("kernel32.dll")]
    static extern bool SetInformationJobObject(IntPtr job, JobObjectInfoType infoType,
        IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);

    // Windows will automatically close any open job handles when our process terminates.
    //  This can be verified by using SysInternals' Handle utility. When the job handle
    //  is closed, the child processes will be killed.
    private static readonly IntPtr s_jobHandle;
}

public enum JobObjectInfoType
{
    AssociateCompletionPortInformation = 7,
    BasicLimitInformation = 2,
    BasicUIRestrictions = 4,
    EndOfJobTimeInformation = 6,
    ExtendedLimitInformation = 9,
    SecurityLimitInformation = 5,
    GroupInformation = 11
}

[StructLayout(LayoutKind.Sequential)]
public struct JOBOBJECT_BASIC_LIMIT_INFORMATION
{
    public Int64 PerProcessUserTimeLimit;
    public Int64 PerJobUserTimeLimit;
    public JOBOBJECTLIMIT LimitFlags;
    public UIntPtr MinimumWorkingSetSize;
    public UIntPtr MaximumWorkingSetSize;
    public UInt32 ActiveProcessLimit;
    public Int64 Affinity;
    public UInt32 PriorityClass;
    public UInt32 SchedulingClass;
}

[Flags]
public enum JOBOBJECTLIMIT : uint
{
    JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
}

[StructLayout(LayoutKind.Sequential)]
public struct IO_COUNTERS
{
    public UInt64 ReadOperationCount;
    public UInt64 WriteOperationCount;
    public UInt64 OtherOperationCount;
    public UInt64 ReadTransferCount;
    public UInt64 WriteTransferCount;
    public UInt64 OtherTransferCount;
}

[StructLayout(LayoutKind.Sequential)]
public struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
    public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
    public IO_COUNTERS IoInfo;
    public UIntPtr ProcessMemoryLimit;
    public UIntPtr JobMemoryLimit;
    public UIntPtr PeakProcessMemoryUsed;
    public UIntPtr PeakJobMemoryUsed;
}


This answer started with @Matt Howells' excellent answer plus others (see links in the code below). Improvements:
  • Supports 32-bit and 64-bit.
  • Fixes some problems in @Matt Howells' answer:
    1. The small memory leak of extendedInfoPtr
    2. The 'Win32' compile error, and
    3. A stack-unbalanced exception I got in the call to CreateJobObject (using Windows 10, Visual Studio 2015, 32-bit).
  • Names the Job, so you if you use SysInternals, for example, you can easily find it.
  • Has a somewhat simpler API and less code.
Here's how to use this code:
// Get a Process object somehow.
Process process = Process.Start(exePath, args);
// Add the Process to ChildProcessTracker.
ChildProcessTracker.AddProcess(process);
To support Windows 7 requires:
In my case, I didn't need to support Windows 7, so I have a simple check at the top of the static constructor below.

Saturday, February 23, 2013

Creating a Multi Page PDF from a TIFF | TIFF to PDF Converter


I've been working on a project recently that had a requirement to do a tiff to pdf conversion on the fly, and serve these pdf's over the web. The added wrinkle was that these tiff files were stored in a database - so I wasn't going to reading or writing from the filesystem. This isn't a huge problem, but it did throw 90% of the examples out of the window!

I opted to use PdfSharp to do the conversion this - it's a really great open source library and did exactly what I needed.

So here we go:

snippet 1:
byte[] bytes = GetMyByteData();

using (MemoryStream memoryStream = new MemoryStream(bytes))
{
 memoryStream.Position = 0;
 memoryStream.Write(bytes, 0, bytes.Length);
 
 System.Drawing.Image image = System.Drawing.Image.FromStream(memoryStream, true, true);
 
 //This is where the next code goes!!
}


To start with I retrieved my data from the database into a byte array, wrote it into a memory stream object and finally created an Image object from the memory stream. Next onto creating the pdf document:

snippet 2:
PdfDocument doc = new PdfDocument();
XGraphics xgr;

PdfPage page = new PdfPage();
doc.Pages.Add(page);
xgr = XGraphics.FromPdfPage(page);

XImage ximg = XImage.FromGdiPlusImage(image);
xgr.DrawImage(ximg, 0, 0);


As you can see from the code, this is where PdfSharp comes into play (I opted for the GDI+ version) - creating a PdfDocument, XGraphics object, PdfPage and loading the image into page. I guess the real magic here when using the XImage.FromGdiPlusImage method to load the in memory image file into a pdf writeable object.

Finally was writing this back to the response stream (in ASP.NET obviously!):

snippet 3:
using (MemoryStream responseStream = new MemoryStream())
{
 doc.Save(responseStream, false);
 responseStream.Position = 0;

 context.Response.ClearContent();
 context.Response.ClearHeaders();
 context.Response.BufferOutput = true;
 context.Response.ContentType = "application/pdf";
 context.Response.AddHeader("content-disposition", "inline;filename=mypdf.pdf");

 responseStream.CopyTo(context.Response.OutputStream);

 context.Response.Flush();
 context.Response.Close();
 context.Response.End();
}

doc.Close();


I wont go into too much detail about this, its pretty straight forward stuff. For me the 2 things really worth mentioning is the doc.Save() method which saves the pdf to a new memory stream, and the responseStream.CopyTo method which copies one stream to another (new to .net 4 I think!).

This all worked fine but there was one further complication - the TIFFs might be multi-page. In those examples the pdf would only ever contain the first page. To overcome this I had to loop over the page frames and add a new pdf page for each one. This replaces snippet 2 with the following:

snippet 2(v2):
PdfDocument doc = new PdfDocument();
XGraphics xgr;

int count = image.GetFrameCount(FrameDimension.Page);
for (int pageNum = 0; pageNum < count; pageNum++) {  image.SelectActiveFrame(FrameDimension.Page, pageNum);   PdfPage page = new PdfPage();  doc.Pages.Add(page);  xgr = XGraphics.FromPdfPage(page);   XImage ximg = XImage.FromGdiPlusImage(image);  xgr.DrawImage(ximg, 0, 0); } 


I was pleasantly surprised with how straight forward this was to achieve, and in particular how quickly it all worked.

Matt

source : http://www.codenutz.com/2011/10/creating-multi-page-pdf-from-tiff-tiff.html

Wednesday, February 20, 2013

Using cURL in PHP to access HTTPS (SSL/TLS) protected sites

From PHP, you can access the useful cURL Library (libcurl) to make requests to URLs using a variety of protocols such as HTTP, FTP, LDAP and even Gopher. (If you’ve spent time on the *nix command line, most environments also have the curl command available that uses the libcurl library)
In practice, however, the most commonly-used protocol tends to be HTTP, especially when using PHP for server-to-server communication. Typically this involves accessing another web server as part of a web service call, using some method such as XML-RPC or REST to query a resource. For example, Delicious offers a HTTP-based API to manipulate and read a user’s posts. However, when trying to access a HTTPS resource (such as the delicious API), there’s a little more configuration you have to do before you can get cURL working right in PHP.

The problem

If you simply try to access a HTTPS (SSL or TLS-protected resource) in PHP using cURL, you’re likely to run into some difficulty. Say you have the following code: (Error handling omitted for brevity)
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
If $url points toward an HTTPS resource, you’re likely to encounter an error like the one below:
Failed: Error Number: 60. Reason: SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
The problem is that cURL has not been configured to trust the server’s HTTPS certificate. The concepts of certificates and PKI revolves around the trust of Certificate Authorities (CAs), and by default, cURL is setup to not trust any CAs, thus it won’t trust any web server’s certificate. So why don’t you have problems visiting HTTPs sites through your web browser? As it happens, the browser developers were nice enough to include a list of default CAs to trust, covering most situations, so as long as the website operator purchased a certificate from one of these CAs.

The quick fix

There are two ways to solve this problem. Firstly, we can simply configure cURL to accept any server(peer) certificate. This isn’t optimal from a security point of view, but if you’re not passing sensitive information back and forth, this is probably alright. Simply add the following line before calling curl_exec():
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
This basically causes cURL to blindly accept any server certificate, without doing any verification as to which CA signed it, and whether or not that CA is trusted. If you’re at all concerned about the data you’re passing to or receiving from the server, you’ll want to enable this peer verification properly. Doing so is a bit more complicated.

The proper fix

The proper fix involves setting the CURLOPT_CAINFO parameter. This is used to point towards a CA certificate that cURL should trust. Thus, any server/peer certificates issued by this CA will also be trusted. In order to do this, we first need to get the CA certificate. In this example, I’ll be using the https://api.del.icio.us/ server as a reference.
First, you’ll need to visit the URL with your web browser in order to grab the CA certificate. Then, (in Firefox) open up the security details for the site by double-clicking on the padlock icon in the lower right corner:

Then click on “View Certificate”:

Bring up the “Details” tab of the cerficates page, and select the certificate at the top of the hierarchy. This is the CA certificate.



 Then click “Export”, and save the CA certificate to your selected location, making sure to select the X.509 Certificate (PEM) as the save type/format.




Now we need to modify the cURL setup to use this CA certificate, with CURLOPT_CAINFO set to point to where we saved the CA certificate file to.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/CAcerts/BuiltinObjectToken-EquifaxSecureCA.crt"); 
The other option I’ve included,CURLOPT_SSL_VERIFYHOST can be set to the following integer values:
  • 0: Don’t check the common name (CN) attribute
  • 1: Check that the common name attribute at least exists
  • 2: Check that the common name exists and that it matches the host name of the server
If you have CURLOPT_SSL_VERIFYPEER set to false, then from a security perspective, it doesn’t really matter what you’ve set
CURLOPT_SSL_VERIFYHOST
to, since without peer certificate verification, the server could use any certificate, including a self-signed one that was guaranteed to have a CN that matched the server’s host name. So this setting is really only relevant if you’ve enabled certificate verification.
This ensures that not just any server certificate will be trusted by your cURL session. For example, if an attacker were to somehow redirect traffic from api.delicious.com to their own server, the cURL session here would not properly initialize, since the attacker would not have access to a server certificate (i.e. would not have the private key) trusted by the CA we added. These steps effectively export the trusted CA from the web browser to the cURL configuration.

More information

If you have the CA certificate, but it is not in the PEM format (i.e. it is in a binary or DER format that isn’t Base64-encoded), you’ll need to use something like OpenSSL to convert it to the PEM format. The exact command differs depending on whether you’re converting from PKCS12 or DER format.
There is a CURLOPT_CAPATH option that allows you to specify a directory that holds multiple CA certificates to trust. But it’s not as simple as dumping every single CA certificate in this directory. Instead, they CA certificates must be named properly, and the OpenSSL c_rehash utility can be used to properly setup this directory for use by cURL.

Taken from HERE : http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/

Logging in to HTTPS websites using PHP cURL



To log in to a HTTPS website using PHP cURL you need to do the following:

enable cURL by uncommenting the line extension=php_curl.dll in your php.ini file.

Set up cURL to either accept all certificates or add the needed certificate authority to cURLs CA list (check out http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/)

Then you need to load the page to get the session cookie:
// Create temp file to store cookies
$ckfile = tempnam ("/tmp", "CURLCOOKIE");

// URL to login page
$url = "https://www.securesiteexample.com";

// Get Login page and its cookies and save cookies in the temp file
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Accepts all CAs
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile); // Stores cookies in the temp file
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch); 


Now you have the cookie, you can POST login values (check the source of the login page to check if you need any other fields too)
$fields = array(
$fields = array(
'username' => 'yourusername',
'password' => 'yourpassword',
);
$fields_string = '';
foreach($fields as $key=>$value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');

// Post login form and follow redirects
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Accepts all CAs
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile); //Uses cookies from the temp file
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Tells cURL to follow redirects
$output = curl_exec($ch); 
Now you should be able to access any pages within the password-restricted area by just including the cookies for each call:

$url = "https://www.securesiteexample.com/loggedinpage.html";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Accepts all CAs
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile); //Uses cookies from the temp file
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);


Source from:
http://www.herikstad.net/2011/06/logging-to-https-websites-using-php.html

Tuesday, December 25, 2012

C# Pulling images from google images ( support proxy )

 public string getHtmltt(string url)
    {

        string responseData = "";
        try
        {
            string host = string.Empty;

            if (url.Contains("/search?"))
            {
                host = url.Remove(url.IndexOf("/search?"));

                if(host.Contains("//"))
                {
                    host = host.Remove(0, host.IndexOf("//")).Replace("//","").Trim();
                }
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
            request.AllowAutoRedirect = true;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            request.Timeout = 60000;
            request.Method = "GET";
            request.KeepAlive = false; ;


           // request.Host = "www.google.com.af";
            request.Host = host;
            request.Headers.Add("Accept-Language", "en-US");

            //request.Proxy = null;
           // WebProxy prx = new WebProxy("199.231.211.107:3128");

            WebProxy prx = new WebProxy(proxies[0].ToString().Trim());

            request.Proxy = prx;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream responseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(responseStream);
                responseData = myStreamReader.ReadToEnd();
            }

            foreach (Cookie cook in response.Cookies)
            {
                inCookieContainer.Add(cook);
            }
            response.Close();



        }
        catch (System.Exception e)
        {
            responseData = "An error occurred: " + e.Message;

        }

        return responseData;

    }

Thursday, October 25, 2012

How to send a HTTP Post Request in Delphi 2010 using WinInet

Di scrapping dari sini
http://stackoverflow.com/questions/2977720/how-to-send-a-http-post-request-in-delphi-2010-using-wininet


uses WinInet;
procedure TForm1.Button1Click(Sender: TObject);
var
  hNet,hURL,hRequest: HINTERNET;
begin
  hNet := InternetOpen(PChar('User Agent'),INTERNET_OPEN_TYPE_PRECONFIG or INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if Assigned(hNet) then
  begin
  try
    hURL := InternetConnect(hNet,PChar('http://localhost/delphitest.php'),INTERNET_DEFAULT_HTTP_PORT,nil,nil,INTERNET_SERVICE_HTTP,0,DWORD(0));
    if(hURL<>nil) then
      hRequest := HttpOpenRequest(hURL, 'POST', PChar('test=test'),'HTTP/1.0',PChar(''), nil, INTERNET_FLAG_RELOAD or INTERNET_FLAG_PRAGMA_NOCACHE,0);
    if(hRequest<>nil) then
      HttpSendRequest(hRequest, nil, 0, nil, 0);
    InternetCloseHandle(hNet);
  except
      ShowMessage('error');
    end
  end;
end;

and my PHP script:

$data = $_POST['test'];
$file = "test.txt";
$fp = fopen($file, "a");
flock($fp, 2);
fwrite($fp, $data);
flock($fp, 3);
fclose($fp);
 
Major problems:
  • The second parameter of InternetConnect should contain only the name of the server, not the entire URL of the server-side script.
  • The third parameter of HttpOpenRequest should be the file name (URL) of the script, not the POST data!
  • The actual POST data should be the forth parameter of HttpSendRequest.
Minor problems
  • INTERNET_OPEN_TYPE_PRECONFIG or INTERNET_OPEN_TYPE_PRECONFIG: It is sufficient with INTERNET_OPEN_TYPE_PRECONFIG.
  • DWORD(0) is overkill. 0 is enough.
Sample Code
I use the following code to POST data:
procedure WebPostData(const UserAgent: string; const Server: string; const Resource: string; const Data: AnsiString); overload;
var
  hInet: HINTERNET;
  hHTTP: HINTERNET;
  hReq: HINTERNET;
const
  accept: packed array[0..1] of LPWSTR = (PChar('*/*'), nil);
  header: string = 'Content-Type: application/x-www-form-urlencoded';
begin
  hInet := InternetOpen(PChar(UserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  try
    hHTTP := InternetConnect(hInet, PChar(Server), INTERNET_DEFAULT_HTTP_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 1);
    try
      hReq := HttpOpenRequest(hHTTP, PChar('POST'), PChar(Resource), nil, nil, @accept, 0, 1);
      try
        if not HttpSendRequest(hReq, PChar(header), length(header), PChar(Data), length(Data)) then
          raise Exception.Create('HttpOpenRequest failed. ' + SysErrorMessage(GetLastError));
      finally
        InternetCloseHandle(hReq);
      end;
    finally
      InternetCloseHandle(hHTTP);
    end;
  finally
    InternetCloseHandle(hInet);
  end;
end;
For instance:
WebPostData('My UserAgent', 'www.rejbrand.se', 'mydir/myscript.asp', 'value=5');
Update in response to answer by OP
To read data from the Internet, use InternetReadFile function. I use the following code to read a small (one-line) text file from the Internet:
function WebGetData(const UserAgent: string; const Server: string; const Resource: string): string;
var
  hInet: HINTERNET;
  hURL: HINTERNET;
  Buffer: array[0..1023] of AnsiChar;
  i, BufferLen: cardinal;
begin
  result := '';
  hInet := InternetOpen(PChar(UserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  try
    hURL := InternetOpenUrl(hInet, PChar('http://' + Server + Resource), nil, 0, 0, 0);
    try
      repeat
        InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen);
        if BufferLen = SizeOf(Buffer) then
          result := result + AnsiString(Buffer)
        else if BufferLen > 0 then
          for i := 0 to BufferLen - 1 do
            result := result + Buffer[i];
      until BufferLen = 0;
    finally
      InternetCloseHandle(hURL);
    end;
  finally
    InternetCloseHandle(hInet);
  end;
end;
Sample usage:
WebGetData('My UserAgent', 'www.rejbrand.se', '/MyDir/update/ver.txt')
This function thus only reads data, with no prior POST. However, the InternetReadFile function can also be used with a handle created by HttpOpenRequest, so it will work in your case also. You do know that the WinInet reference is MSDN, right? All Windows API functions are described in detail there, for instance InternetReadFile.

function Check(const UserAgent: string; const Server: string; const Resource: string; const Data: AnsiString): string;
var
  hInet: HINTERNET;
  hHTTP: HINTERNET;
  hReq: HINTERNET;
  Buffer: array[0..1023] of AnsiChar;
  i, BufferLen: Cardinal;
const
  accept: packed array[0..1] of LPWSTR = (PChar('*/*'), nil);
  header: string = 'Content-Type: application/x-www-form-urlencoded';
begin
  Result := '';

  hInet := InternetOpen(PChar(UserAgent), INTERNET_OPEN_TYPE_PRECONFIG,
    nil, nil, 0);
  try
    hHTTP := InternetConnect(hInet, PChar(Server), INTERNET_DEFAULT_HTTP_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 1);
    try
      hReq := HttpOpenRequest(hHTTP, PChar('POST'), PChar(Resource), nil, nil, @accept, 0, 1);
      try
        if not HttpSendRequest(hReq, PChar(header), Length(header), PChar(Data), Length(Data)) then
          raise Exception.Create('HttpOpenRequest failed. ' + SysErrorMessage(GetLastError));
        repeat
          InternetReadFile(hReq, @Buffer, SizeOf(Buffer), BufferLen);
          if BufferLen = SizeOf(Buffer) then
            Result := Result + AnsiString(Buffer)
          else if BufferLen > 0 then
            for i := 0 to BufferLen - 1 do
              Result := Result + Buffer[i];
        until BufferLen = 0;
      finally
        InternetCloseHandle(hReq);
      end;
    finally
      InternetCloseHandle(hHTTP);
    end;
  finally
    InternetCloseHandle(hInet);
  end;
end;

...

Memo1.Text := Check('UserAgent', 'www.mysite.com', 'test.php', 'test=123');