Using Curl & Powershell to POST Form Data to CakePHP

Written by James McDonald

September 30, 2021

CakePHP 2 Form and trying to POST to it using curl

This is what I am trying to duplicate with curl

-----------------------------1993502965129257581246610166
Content-Disposition: form-data; name="_method"

POST
-----------------------------1993502965129257581246610166
Content-Disposition: form-data; name="data[PrintLabel][printer]"

10
-----------------------------1993502965129257581246610166
Content-Disposition: form-data; name="data[PrintLabel][upload]"; filename=""
Content-Type: application/octet-stream


-----------------------------1993502965129257581246610166
Content-Disposition: form-data; name="data[PrintLabel][action]"

print
-----------------------------1993502965129257581246610166--

Curl POST to CakePHP Form

This is what is working with curl

#!/bin/sh
printer=10

curl 	--form _method=POST \
	--form 'data[PrintLabel][upload]'=@./ASN_R-34718415X-batch.xml \
	--form 'data[PrintLabel][action]'=print \
	--form 'data[PrintLabel][printer]'=${printer} \
	http://10.197.3.190:8093/project1/PrintLabels/xmlToPdf

Powershell (version 5.x) POST to CakePHP Form

Important!: The following doesn’t work on Powershell 7

If the file is named powershellPost.ps1 run it as follows:

powershell.exe powershellPost.ps1

$FilePath = "$($pwd)\ASN_R-34718415X-batch.xml";
$URL = 'http://10.197.3.190:8093/100pbc/PrintLabels/xmlToPdf';

$fileBytes = [System.IO.File]::ReadAllBytes($FilePath);
$fileEnc = [System.Text.Encoding]::GetEncoding('ISO-8859-1').GetString($fileBytes);
$boundary = [System.Guid]::NewGuid().ToString(); 
$LF = "`r`n";


$bodyLines = (
    "--$boundary",
    "Content-Disposition: form-data; name=`"_method`"",
    "",
    "POST",
    "--$boundary",
    "Content-Disposition: form-data; name=`"data[PrintLabel][printer]`"",
    "",
    10,
    "--$boundary",
    "Content-Disposition: form-data; name=`"data[PrintLabel][upload]`"; filename=`"hijames.txt`"",
    "Content-Type: application/octet-stream",
    "",
    $fileEnc,
    "--$boundary",
    "Content-Disposition: form-data; name=`"data[PrintLabel][action]`"$LF",
    "print",
    "--$boundary--$LF" 
) -join $LF

Invoke-RestMethod -Uri $URL -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

You May Also Like…

Network speed test host to host

On Ubuntu / Debian apt-get install iperf3 On Windows download it from https://iperf.fr/iperf-download.php#windows Make...

Clear HSTS Settings in CHrome

Open chrome://net-internals/#hsts enter the domain in the query field and click Query to confirm it has HSTS settings...