Jump to content

HTTP lib (GET, POST and upload)


Jefrey
 Share

Recommended Posts

  • 1 month later...

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
Link to comment
Share on other sites

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

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 GUICtrlStaticMarquee static text scrolling Random stuff Super Mario beep sound your ears will hurt

 

Link to comment
Share on other sites

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
Link to comment
Share on other sites

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

 

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 GUICtrlStaticMarquee static text scrolling Random stuff Super Mario beep sound your ears will hurt

 

Link to comment
Share on other sites

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

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 GUICtrlStaticMarquee static text scrolling Random stuff Super Mario beep sound your ears will hurt

 

Link to comment
Share on other sites

  • 3 months later...

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 GUICtrlStaticMarquee static text scrolling Random stuff Super Mario beep sound your ears will hurt

 

Link to comment
Share on other sites

  • 1 month later...

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
Link to comment
Share on other sites

  • 1 year later...

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
Link to comment
Share on other sites

  • Moderators

@Melque_Lima you need to read our forum rules. We are not going to support requests on getting around security measures like captcha.

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

  • Moderators

If you read the forum rules you will get the answer to that question in item #7

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

  • 1 year later...

Hi, i would like to be able to modify the Header sent with _HTTP_Upload, so i modified the source UDF func in :

_HTTP_Upload($strUploadUrl, $strFilePath, $strFileField, $strHeaderK, $strHeaderV, $strDataPairs = '', $strFilename = Default)

with Header adding with the line 2 inserted :

$oHTTP.SetRequestHeader("Content-Type", "multipart/form-data; boundary=" & $MULTIPART_BOUNDARY)
If $strHeaderK And $strHeaderV Then $oHTTP.SetRequestHeader($strHeaderK, $strHeaderV)
$oHTTP.Send($bytFormData)

My main prog successfully calls and it's working :

_HTTP_Upload($sAddress, $sImageFile, "image", "MyHeaderK", "MyHeaderV")

 

However, is there a way to modify it to simplify the formatting of passed Header ?

---> Am i obliged to pass $strHeaderK and $strHeaderV individually of is there a way to pass it at once ? Like passing <$strHeaderV, $strHeaderK> directly in just one argument in UDF ?

I've searched and found that it's impossible to pass <string> and <,> function argument at once, but i would want a confirmation.

 

Thanks.

Edited by JoeBar
Link to comment
Share on other sites

  • 1 year later...

Hello,

I have been struggling for a few hours to find a simple solution to the next problem.

I have the php file below and my autoit script.

The problem is the following, if on my server, I create the "dirnewname" directory (the one specified in the autoit file), and then run the autoit script, in which case it works perfectly and the "file.txt" file is created in the specified "dirnewname" directory.

Basically I can upload a .txt file to the server at any time if I know the location of the directory and if that directory exists.
The problem is that I need to create a new directory when I need it, calling the May function _HTTP_Upload.

Can I do that?

Basically at the moment, I can upload with _HTTP_Upload, a text file or another type of file, but I can't create a new directory in which to upload the desired file.

If anyone can help me, thank you in advance.

 

My php file:

<?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', 'jpg', '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';

My autoit file:

#include <HTTP.au3>
$test = _HTTP_Upload("https://site.com/key/file.php", "New folder\myFile.txt", "uploadinput", "pwd=123&filename=" & URLEncode("dirnewname/file.txt") )
ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $test = ' & $test & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

 

Link to comment
Share on other sites

  • Moderators

@beginner10 please wait 24 hours before bumping threads. This may be the most important thing in the world to you, but spamming the forum won't get you an answer faster. We have forum members all over the world; the person most suited to assist you may not be online at this time.

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

  • 3 years later...

Hi, and thanks for this fantastic UDF....

I'm doing a pilot test of API communication from AutoIT to ResourceSpace, and I've managed to get it working perfectly using GET requests. But when I make POST requests I always get the "Invalid Signature" error. The procedure and signature is exactly the same as in GET...
The information about the resourcespace is at: https://www.resourcespace.com/knowledge-base/api/

The GET script that I am using and that works perfectly is the following:

#include <HTTP.au3>
#include <Crypt.au3>

$urlapi="http://my-resourcespace-url/api/?"
$user="my-user"
$user_key="my-user-key"
$query="user=" & $user & "&function=create_resource&resource_type=3&archive=0"

;; Sign the query using the private key
$sign=_Crypt_HashData($user_key & $query, $CALG_SHA_256)
$sign=StringTrimLeft ($sign, 2)
$sign=StringLower ($sign)

ConsoleWrite ($sign & @CRLF)

;; Make the request and output the JSON results.
Local $apirequest=_HTTP_Post($urlapi & $query & "&sign=" & $sign)

ConsoleWrite ($apirequest & @CRLF)

    If @error Then
        MsgBox (16, "ERROR", " API Error! " & $apirequest)
        Exit
    EndIf

Exit

Can someone help me build the same request but with POST so that it works for me?

Thanks in advance

Link to comment
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
 Share

×
×
  • Create New...