Jump to content
Jefrey

HTTP lib (GET, POST and upload)

Recommended Posts

Jefrey

I've made this HTTP lib to simplify HTTP requests, mainly when dealing about POST data or file uploads.

Three functions are available:

  • string _HTTP_Get ( string $sURL )
  • string _HTTP_Post ( string $sURL , string $sPostData )
  • string _HTTP_Upload ( string $sURL , string $sFilePath , string $sFileField , string $sPostData = '' , string $sFilename = Default)

Additionaly, two helper functions are also available:

  • URLEncode($sStr)
  • URLDecode($sStr)

Full documentation: https://github.com/jesobreira/HTTP.au3/blob/master/README.md

Fork me on Github: https://github.com/jesobreira/HTTP.au3

Download lib + docs: https://github.com/jesobreira/HTTP.au3/archive/master.zip

  • Like 4

My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites
youtuber

Hello, how can I upload it? My txt file

_HTTP_Upload("http://test/postscript.php", @HomeDrive & "\testmy.txt", "uploadinput", "str=" & URLEncode("Code: AutoIt3") )

Example of my php upload

<html><title>Upload php</title>
<?php
echo '<form action="" method="post" enctype="multipart/form-data" name="uploader" id="uploader">';
echo '<input type="file" name="file" size="50"><input name="_upl" type="submit" id="_upl" value="Upload"></form>';
if( $_POST['_upl'] == "Upload" ) {
    if(@copy($_FILES['file']['tmp_name'], $_FILES['file']['name'])) { echo 'Uploaded<br>'; }
    else { echo 'Not uploaded<br>'; }
}
echo 'Test upload';
?>
</html>

or

<?php
($_POST["password"] == "Pass123") Or die("NOT AUTH");
(!empty($_POST["filename"])) Or die("NO FILENAME");
move_uploaded_file($_FILES['datei']['tmp_name'], $_POST["filename"]);
readfile($_POST["filename"]);
?>

 

Edited by youtuber

Share this post


Link to post
Share on other sites
Jefrey

Hi, @youtuber! I found several issues on your code...

  • Your first PHP code requires a file input named "file"; your second PHP code requires "datei", whereas your AutoIt script gives a file input named "uploadinput"
  • Your second PHP code requires a post variable named "filename", whereas your AutoIt script gives it named "str"
  • Your second PHP code requries a post variable named "password" to be "Pass123", whereas your AutoIt script doesn't give it.
  • Both the PHP codes are vulnerable, as anyone can upload malicious PHP files onto it.

Here's a short example (warning: I didn't test it):

_HTTP_Upload("http://test/postscript.php", "myFile.txt", "uploadinput", "pwd=123&filename=" & URLEncode("test.txt") )
<?php

define('PASSWORD', '123'); // put pwd here

$pwd = isset($_REQUEST['pwd']) ? $_REQUEST['pwd'] : null;

if ($pwd!=PASSWORD) {
  header("HTTP/1.0 403 Forbidden");
  echo "403 Forbidden";
  exit;
}

$allowed_extensions = ['txt', 'doc', 'docx']; // set it

if ($_FILES['uploadinput']['tmp_name']) {
  $file_extension = strtolower(end($tmp = explode(".", $_POST['filename']))); // $tmp to avoid "should be passed as ref" notice
  if(in_array($file_extension, $allowed_extensions)) {
    move_uploaded_file($_FILES['uploadinput']['tmp_name'], 'uploads/'.$_POST['filename']);
  }
}

echo 'ok';

 

Edited by Jefrey
fixed error in php code
  • Like 1

My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites
youtuber

There is an error
Can someone help me?

#include <HTTP.au3>
$test = _HTTP_Upload("http://mysite/index.php", @ScriptDir & "\myFile.txt", "uploadinput", "pwd=123&filename=" & URLEncode("test.txt") )
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $test = ' & $test & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

 

@@ Debug(3) : $test = 403 Forbidden

 

Or it gives such an error

\HTTP.au3" (123) : ==> Variable must be of type "Object".:

For $match In $matches^ ERROR

 

Line 123

Func URLDecode($urlText)
    $urlText = StringReplace($urlText, "+", " ")
    Local $matches = StringRegExp($urlText, "\%([abcdefABCDEF0-9]{2})", 3)
    For $match In $matches
        $urlText = StringReplace($urlText, "%" & $match, BinaryToString('0x' & $match))
    Next
    Return $urlText
EndFunc   ;==>URLDecode

 

Edited by youtuber

Share this post


Link to post
Share on other sites
Jefrey

Hi bro, thanks for your report! I've updated the code on the repo. Just replace the function by this one:

Func URLDecode($urlText)
    $urlText = StringReplace($urlText, "+", " ")
    Local $matches = StringRegExp($urlText, "\%([abcdefABCDEF0-9]{2})", 3)
    If Not @error Then
        For $match In $matches
            $urlText = StringReplace($urlText, "%" & $match, BinaryToString('0x' & $match))
        Next
    EndIf
    Return $urlText
EndFunc   ;==>URLDecode

 

  • Like 1

My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites
youtuber

Thank you for the correction
But still not working
403 Forbidden gives an error problem

 

Share this post


Link to post
Share on other sites
Jefrey

D'oh!

There's a problem on my PHP script.

This:

$pwd = isset($_GET['pwd']) ? $_GET['pwd'] : null;

Should only be used if you're calling so (the "pwd" parameter as GET, on the query string/part of the URL):

$test = _HTTP_Upload("http://139.59.137.45/index.php?pwd=123", @ScriptDir & "\myFile.txt", "uploadinput", "filename=" & URLEncode("test.txt") )

However, we are calling with the "pwd" parameter as POST:

$test = _HTTP_Upload("http://139.59.137.45/index.php", @ScriptDir & "\myFile.txt", "uploadinput", "pwd=123&filename=" & URLEncode("test.txt") )

So we should replace that line on the PHP file with this:

$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : null;

Or even this if we want to support the "pwd" parameter in any POST or GET method:

$pwd = isset($_REQUEST['pwd']) ? $_REQUEST['pwd'] : null;

So just replace the first PHP line of this answer by one of the last two lines above (you choose) and you're all done :)

  • Like 1

My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites
txdancer

jefrey - you are my hero! You're functions saved my b**t on a project that required comms with a credit card API. You're HTTP_POST function solved the problem.

Thx a bazillion!

Share this post


Link to post
Share on other sites
Jefrey

Hi, @txdancer! I'm happy for being helpful! :) 


My stuff

Spoiler

My UDFs  _AuThread multithreading emulation for AutoIt · _ExtInputBox an inputbox with multiple inputs and more features · forceUTF8 fix strings encoding without knowing its original charset · JSONgen JSON generator · _TCPServer UDF multi-client and multi-task (run on background) event-based TCP server easy to do · _TCPClient_UDF multi-server and multi-task (runs on background) event-based TCP client easy to do · ParseURL and ParseStr functions ported from PHP · _CmdLine UDF easily parse command line parameters, keys or flags · AutoPHP Create documents (bills, incomes) from HTML by sending variables/arrays from AutoIt to PHP · (Un)Serialize Convert arrays and data into a storable string (PHP compatible) · RTTL Plays and exports to MP3 Nokia-format monophonic ringtones (for very old cellphones) · I18n library Simple and easy to use localization library · Scripting.Dictionary OOP and OOP-like approach · Buffer/stack limit arrays to N items by removing the last one once the limit is reached · NGBioAPI UDF to work with Nitgen fingerprint readers · Serial/Licensing system require license key based on unique machine ID from your users · HTTP a simple WinHTTP library that allows GET, POST and file uploads · Thread true AutoIt threads (under-dev) · RC4 RC4 encryption compatible with PHP and JS ·  storage.au3 localStorage and sessionStorage for AutoIt Classes _WKHtmlToX uses wkhtmlto* to convert HTML files and webpages into PDF or images (jpg, bmp, gif, png...) Snippets _Word_DocFindReplaceByLongText replace strings using Word UDF with strings longer than 255 characters (MSWord limit) rangeparser parser for printing-like pages interval (e.g.: "1,2,3-5") EnvParser parse strings/paths with environment variables and get full path Random stuff Super Mario beep sound your ears will hurt

 

Share this post


Link to post
Share on other sites
robertocm

Simple examples for currency exchange rates from Open Exchange Rates (using a free user account: 'Free plan')

#include <HTTP.au3>

ConsoleWrite( _HTTP_Get("https://openexchangerates.org/api/latest.json?app_id=YOUR_APP_ID&prettyprint=true") )

 

#include <HTTP.au3>

ConsoleWrite( _HTTP_Get("https://openexchangerates.org/api/latest.json?app_id=YOUR_APP_ID&symbols=GBP,EUR&prettyprint=true") )

And this is an example to send SMS messages using the API of Mensatek

Local $sResp = _HTTP_Post("http://api.mensatek.com/sms/v5/enviar.php", "Correo=" & URLEncode("yourmailaddress@yourdomain.com") & "&Passwd=yourpassword&Remitente=YourName&Destinatarios=" & URLEncode("34600000001;34600000002") & "&Mensaje=" & URLEncode("Your message" & $sString) & "&Resp=JSON")

ConsoleWrite($sResp)

 

Edited by robertocm
Adding an example

Share this post


Link to post
Share on other sites
Melque_Lima

A little help here please !?

I'm trying to parse a file but the function is not working well!

It is not parsing the username and password, it is returning that couldn't login in api

 

#include <HTTP.au3>

$test = _HTTP_Upload("http://myapi/", @ScriptDir & "\myimage.bmp", "uploadinput", "username=myusername&password=mypassword")

ConsoleWrite($test)

 

Capturar.PNG

Edited by Melque_Lima

Share this post


Link to post
Share on other sites
Melque_Lima

@JLogan3o13 really sorry, can i edit it?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • ternal
      By ternal
      Hi,
      The FAQ proposed as a solution to keys getting stuck  to do this command
      ControlSend("", "", "", "text", 0) However this sends "text" to the last active control if I am not mistaken.I have tried this with
      controlsend("", "", "", "{altup}{shiftup}{ctrlup}", 0) This is already a lot better but still fails 1/10
      I cannot allow the script to send "text" to the last active control, and its a bit silly to let it send to somewhere where its harmless no?
      Are there any other methods of unstucking keys?
    • ur
      By ur
      Is there any UDF to remove all anchor tags <a> with a particular class (and also its sub elements completely) in a html document.
      Here the classes are browse and breadcrumbs
      Like in the below image.


       
      I am not able to find that option in IE.au3
       
      Please suggest.
    • milkmoron
      By milkmoron
      I am trying to automate something in a web browser but i need some help with finding the html code to a web applet. How do I access the code.
    • Fortitude
      By Fortitude
      Hello!
      I have made a program, that opens a folder, and then store the path ("C:\programFiles\etc") in a variable.
      Then i need to open the command panel as administrator, and write  in the stored path, and some other text.

      Can i somehow instantly copypaste the text i needed, instead of writing in the command panel with the Send commands?
       
      #RequireAdmin #include <MsgBoxConstants.au3> Global Const $sMessage = "Select a folder" ; Display an open dialog to select a file. Global $sFileSelectFolder = FileSelectFolder($sMessage, "") If @error Then MsgBox($MB_SYSTEMMODAL, "", "Nem választottál ki mappát!") Exit EndIf Global $Tiff_path = $sFileSelectFolder & "\TiffChecker_2_32" FileCopy( "C:\TiffChecker_2_32.exe" , $sFileSelectFolder) $CMD = $Tiff_path & " " & $sFileSelectFolder & " /s/d" Run("C:\WINDOWS\system32\cmd.exe") WinWaitActive("C:\WINDOWS\system32\cmd.exe") Send($CMD) Sleep(1000) Send("{ENTER}") sleep(1000) MsgBox(0,"Press OK", "Press OK to continue") FileCopy("C:\Tiffchecker.txt", $sFileSelectFolder) Also, how do i close the command panel, when the program is finished? (usually its under 1 second, so after the send i just put a Sleep function there)
    • Seminko
      By Seminko
      Is there a way to grab non-hardcoded but rather javascript generated data from a webpage?
      Tried a get request as well as _IEBodyReadHTML but both seem to grab the code without the javascript generated data.
      $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("GET", "link", False) $oHTTP.Send() $oReceived = $oHTTP.ResponseText $oStatusCode = $oHTTP.Status Global $DataArray[10][5] If $oStatusCode <> 200 Then Exit MsgBox(1, "Error", "Status Code <> 200") EndIf FileWrite(@ScriptDir & "\output.txt", $oReceived) ; //////// #include <IE.au3> Local $FullLink = "link" Local $oIE = _IECreate($FullLink, 0, 0) _IELoadWait($oIE) Local $sText = _IEBodyReadHTML($oIE) FileWrite(@ScriptDir & "\output.txt", $sText)  
×