Jefrey

HTTP lib (GET, POST and upload)

9 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

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

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

    • badcoder123
      By badcoder123
      Anyone know how to access the information circled in the photo?
       

    • Spask
      By Spask
      Hi, I'm trying to find a text value inside of a html.
      This is what the line looks like normally:
      <p id="line1" class> <span class="bot">TEXT HERE</span> </p> The text then changes to a non breaking space:
      <p id="line1" class> <span class="bot">&nbsp;</span> </p> And then it changes back to normal text but it's different every time.
      Can I code this so that it grabs the text every time it changes and has a variable that represents it?
      I currently have this inside of my loop:
      $span = .document.getElementsByTagName("span") For $text In $span If $text.value = "&nbsp;" Then Sleep(50) MsgBox(0,0,0) ;messagebox to test if it can be found, but I don't know how to grab the text EndIf Next The problem is that there are many other lines in the html that have the same span but are called "line3", "line5", etc and the one I need is from "line1".
      I will appreciate if anyone can help with this!
    • AndreyS
      By AndreyS
      Dear developers and creators of the language, please explain to me why when pressing the combination Crtl + Shift + C from the 5th or the 10th time "sticks / sinks" Ctrl or Shift? And then you need to press Ctrl or Shift again to reset their triggering. I only need to use hot keys like in the example!
      The code is a small example. Its essence is that when a user in the editor selects any number and presses a combination, then it increases by 1. 
      Dim $x HotKeySet("+^c","Calc") While 1 Sleep(10000) WEnd Func Calc() Send("^c") Sleep(50) $x=ClipGet()+1 ClipPut($x) Send("^v") EndFunc I thought that in my program some kind of glitch was searching for a reason for a long time. And it turned out that apparently somehow the work of some functions used in the example is not compatible. 
      Tell me, please, what is the problem?
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good evening everyone
      Before all, I want to say that I'm doing this script to see how _IE* functions work, and see if my studs can hack a quiz I'm working on.
      I want to clarify that I'm not automating any game, bypassing any CAPTCHAs, or anything that could damage anyone.
      I was trying to autofill a form, based on which question is displayed.
      The question is always stored in here:
      <header> <h1><span class="questionid">1. </span>Here goes the question</h1> </header> And answers are stored in here:
      <ul class="answers"> <li><label><span><input id="answer_0" name="answer[]" type="radio" value="0">Answer 1</span></label></li> <li><label><span><input id="answer_1" name="answer[]" type="radio" value="1">Answer 2</span></label></li> <li><label><span><input id="answer_2" name="answer[]" type="radio" value="2">Anwser 3</span></label></li> <li><label><span><input id="answer_3" name="answer[]" type="radio" value="3">Answer 4</span></label></li> </ul></fieldset></form></div> And, there are 15 questions like this.
      How can automatically fill my form?
      Thanks in advance
      Francesco
    • houser747
      By houser747
      I have previously used _IEFormElementGetObjByName and _IEFormElementSetValue to enter text into a search box on a form and then submit the form.
      I am now trying to enter text into a search box which is not part of a form. 
      Here is the HTML from the website that i'm trying to enter the data on and then submit the search.
      <div class="row">
          <div class="form-group col-xs-12">
              <span id="FullWidthWithSubmenuContent_FullWidthContent_MainContent_AircraftRegistry_lblSearchText" for="input-search">Registreringsbeteckning</span>
              <div class="input-group col-xs-12">
                  <span id="FullWidthWithSubmenuContent_FullWidthContent_MainContent_AircraftRegistry_preSearchText" class="input-group-addon">SE -</span>
                  <input name="ctl00$FullWidthWithSubmenuContent$FullWidthContent$MainContent$AircraftRegistry$txtSearchText" type="text" value="DTH" id="FullWidthWithSubmenuContent_FullWidthContent_MainContent_AircraftRegistry_txtSearchText" class="form-control" />
              </div>
          </div>
      </div>
      <div class="row">
          <div class="form-group col-xs-12">
              <label class="sr-only" for="">Sök</label>
              <input type="submit" name="ctl00$FullWidthWithSubmenuContent$FullWidthContent$MainContent$AircraftRegistry$btnSearch" value="Sök" id="FullWidthWithSubmenuContent_FullWidthContent_MainContent_AircraftRegistry_btnSearch" class="btn btn-primary ladda-button" data-style="expand-right" />
          </div>
      </div>
      Many thanks in advance
      cheers
      Roger