Jefrey

HTTP lib (GET, POST and upload)

7 posts in this topic

#1 ·  Posted

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

2 people like this

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) 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



#2 ·  Posted (edited)

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

#3 ·  Posted (edited)

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
1 person likes this

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) 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

#4 ·  Posted (edited)

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

#5 ·  Posted

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

 

1 person likes this

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) 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

#6 ·  Posted

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

#7 ·  Posted

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 :)

1 person likes this

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) 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

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

    • spuuunit
      By spuuunit
      This is what I'm trying to do: In Firefox, if you hold down CTRL + C for about 200ms, then press CTRL + T. This is my code:
      While WinActive(" - Mozilla Firefox") If _IsPressed("A2", $hDLL) And _IsPressed("43", $hDLL) Then $timer = TimerInit() While _IsPressed("A2", $hDLL) And _IsPressed("43", $hDLL) Sleep(10) $diff = TimerDiff($timer) If $diff > 200 Then Send("^{T}") While _IsPressed("A2", $hDLL) And _IsPressed("43", $hDLL) Sleep(10) WEnd EndIf WEnd EndIf WEnd The problem is that the CTRL key gets stuck down after Send("^{T}"). I found this, but what I understand that happens when I release, and that is not what I want. The "General unstuck method" did nothing.
    • SkysLastChance
      By SkysLastChance
      #include <IE.au3> #include <MsgBoxConstants.au3> Local $oIE = _IECreate("website") Local $oForms = _IEFormGetCollection($oIE) For $oForm In $oForms MsgBox($MB_SYSTEMMODAL, "Form Info", $oForm.name) _IEImgClick($oForm.name, "Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=12.0.5522.0&amp;Name=Microsoft.ReportingServices.Rendering.HtmlRenderer.RendererResources.TogglePlus.gif", "src") Next I am having trouble clicking an image. Here is what I have tried. 

    • Baboo85
      By Baboo85
      Hi all,
      I need to start a script that include:
      - admin privileges
      - multiple cmd commands
      - no bat, no exe, no tmp files created anywhere (especially in the user temp folder)
      In a bat file it would be simple, but users shouldn't see what commands I'm sending.
      Example of the script:
      echo off cls echo. echo I AM A TOOL echo. echo NOTE: echo - note 1 echo - note 2 echo - etc set USER1=0 set COMPUTER1=0 if /i %username% equ user.user ( set USER1=1 set COMPUTER1=1 ) if /i %username% equ another.user set USER1=1 if /i %computername% equ notebook set COMPUTER1=1 if %USER1% EQU 1 ( if %COMPUTER1% EQU 1 ( reg delete "HKLM\SOFTWARE\blablabla" /f ) else ( echo Computer not authorized. Contact assistance.) ) else ( echo User not authorized. Contact assistance.) echo. pause exit With the send("") is a disaster.
      I'm a noob here, so what can I do?
       
      EDIT: OR ELSE I explain the situation and what I need, so if there is a simple solution I can use that.
       
      SITUATION: our domain users have Users rights on the machine. Some of them need administrator rights.
      We create a local user with administrator rights, so that the users must insert username and password when asked to run something with administrator rights.
      We have an internal domain group policy that blocks EXE, BAT, COM, TMP files from the user local temp directory, for a security reason (malware). That also blocks most software installation.
      But some users are often out of office, away from workplace and in another country, they need a complete control on their computers.
       
      WHAT I NEED: I need to check the username and the computer name. If the username is the one with local administrator rights and the computer name is a computer that is qualified to temporary remove the policy, then I need to execute a REG DELETE command with administrator rights.
       
      I hope I explained myself.
       
      Thank you very much.
    • mjolnirmarkiv
      By mjolnirmarkiv
      Hi!
      Does anyone have any idea why Test() returns 0, while Test2() returns 1?
      #include <IE.au3> MsgBox(0, "", Test() & " " & Test2()) Func Test() Local $oHTML = ObjCreate("HTMLFILE") $oHTML.body.innerHTML = FileRead("Test.html") Return IsObj($oHTML.getElementsByClassName("example")) EndFunc Func Test2() Local $oIE = _IEAttach("", "instance", 1) Return IsObj($oIE.document.getElementsByClassName("example")) EndFunc Sample Test.html I open in IE before testing:
      <!DOCTYPE html> <html> <body> <p class="example"></p> <div class="example"></div> </body> </html> I'm receiving html text in a response to http request, I need to parse it fast and easy, getElementsByClassName would have been ideal. I'm using 3.3.12.0 version.
    • caramen
      By caramen
      Hello guys.
      I have got this script
      $iPid = run("Powershell Get-ADUser "&$UserNameReaded&" -Properties * | select -Expand EmailAddress" , @WindowsDir , @SW_HIDE , 0x2) $MailUser = "" While 1 $MailUser &= StdoutRead($iPID) If @error Then ExitLoop EndIf WEnd GUICtrlSetData ($Label015, ""&$MailUser) If $MailUser = "" Then GUICtrlSetData ($Label017 , "N/A"&$MailUser) Everything is working fine i got correct value
      For my account the value is for exemple :
      J.Personnal@Enterprise.com in the $Label017 the value is correct i have still
      J.Personnal@Enterprise.com If i use :
      Send (""&$MailUser) i have now :
      J.Personnalnterprise.com Is there a way to correct this ?