Create a plain HTTP PUT multipart request with a jpg attached - http

I'm creating a HTTP PUT request manualy. I have the following format
POST http://server.com/id/55/push HTTP/1.0
Content-type: multipart/form-data, boundary=AaB03x
Content-Length: 168
--AaB03x
Content-Disposition: form-data; name="image"; filename="small.jpg"
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
<file content>
--AaB03x--
My question is, how should I fill the "file content" area? If I open a jpeg with TexMate or with cat command line application and I paste the ASCII output, the request does not work.
UPDATE
I'm working with a microprocessor and I can't use C or a high level language I need to manually do the raw request. Do I need to separate with spaces every binary byte read from the file?
In case of saving the jpg into a file in the server side, Do I have to convert the binary stream to ASCII?
I read the binary code of a JPG from my hard drive with a simple php conde:
$filename = "pic.jpg";
$handle = fopen($filename, "rb");
$fsize = filesize($filename);
$contents = fread($handle, filesize($filename));
fclose($handle);
//echo $contents;
for($i = 0; $i < $fsize; $i++)
{
// get the current ASCII character representation of the current byte
$asciiCharacter = $contents[$i];
// get the base 10 value of the current characer
$base10value = ord($asciiCharacter);
// now convert that byte from base 10 to base 2 (i.e 01001010...)
$base2representation = base_convert($base10value, 10, 2);
// print the 0s and 1s
echo($base2representation);
}
whit this code I get a stream of 1 and 0. I can send it including the string of 101010101... to where the tag "file content" of my manually http request is but in the server side I can't visualise the JPG... ¿should I convert it to ASCII again?
SOLUTION
Okay the solution was very simple, I just dumped the ASCII code into the tag "file content" of the http request. Despite I'm using a micro controller I opened a socket with PHP and tested out. The solution was to read the ASCII from the file instead of paste directly the ASCII into the code.
Here a working example of the solution:
<?php
//We read the file from the hard drive
$filename = "pic.jpg";
$handle = fopen($filename, "rb");
$fsize = filesize($filename);
$contents = fread($handle, filesize($filename));
fclose($handle);
$mesage = $contents;
//A trick to calculate the length of the HTTP body
$len = strlen('--AaB03x
Content-Disposition: form-data; name="image"; filename="small.jpg"
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
'.$mesage.'
--AaB03x--');
//We create the HTTP request
$out = "POST /temp/test.php HTTP/1.0\r\n";
$out .= "Content-type: multipart/form-data boundary=AaB03x\r\n";
$out .= "Content-Length: $len\r\n\r\n";
$out .= "--AaB03x\r\n";
$out .= "Content-Disposition: form-data; name=\"image\"; filename=\"small.jpg\"\r\n";
$out .= "Content-Type: image/jpeg\r\n";
$out .= "Content-Transfer-Encoding: binary\r\n\r\n";
$out .= "$mesage\r\n";
$out .= "--AaB03x--\r\n\r\n";
//Open the socket
$fp = fsockopen("127.0.0.1", 8888, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
//we send the message thought the opened socket
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
//Visualize the query sent
echo nl2br($out);
?>
In the real implementation I will simple read directly from the memory of the microcontroler just as I did in the php

You are mistyping the last boundary, it should have been:
--AaB03x--

You need to have an OutputStream of your outcoming connection and use this Stream to write ALL BYTES that you have read from the file.
If you used C#. You can check this: Sending Files using HTTP POST in c#
For Java:
Image writing over URLConnection
how to send data with file upload to the server
HttpURLConnection POST, conn.getOutputStream() throwing Exception

Related

Signature mismatch. Authorization signature or client credential is wrong

Using the following code to try and create the signature and get the bearer token.
<?php
$tm=time();
$param_str = "grant_type=client_credentials&oauth_consumer_key=xxxx&oauth_nonce=xxx&oauth_signature_method=HMAC-SHA256&oauth_timestamp=".$tm."&oauth_version=1.0";
//die($param_str);
$base_str = "POST&" .urlencode("https://account.api.here.com/oauth2/token") . "&" . urlencode($param_str);
//die($base_str);
$sign_key = urlencode("xxxxxxxxxxxxxxxxxxxxxxxxx")."&";
$signature= hash_hmac("sha256",$base_str,$sign_key);
$url = "https://account.api.here.com/oauth2/token";
$ch = curl_init( $url );
$headers = [
'Content-Type: application/x-www-form-urlencoded',
'Authorization: OAuth oauth_consumer_key="xxx",oauth_nonce="xxx",oauth_signature="'.$signature.'",oauth_signature_method="HMAC-SHA256",oauth_timestamp="'.$tm.'",oauth_version="1.0"',
'Cache-Control: no-cache'
];
$payload="grant_type=client_credentials";
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
curl_close($ch);
?>
Tried various combinations. Getting the same error (Signature mismatch. Authorization signature or client credential is wrong). Even tried copying the exact url encoded string from the document, replacing relevant information and still not working. Is there something I am not understanding at all from the documentation or something I am missing here in my code.
The reason for signature mismatch is that the one you created is different than the one server created. Check the following –
Did you convert the signing key and base string into bytes before
passing it to HMAC-SHA256 hashing algorithm.
Did you convert the output of HMAC-SHA256 hashing algorithm into
base64 string.
also check this link if this can help you.

Sending multipart text and html email in Fat Free Framework

Currently I'm using the following code to send my e-mails in Fat Free Framework:
$smtp = new SMTP ( $f3->get('MAILHOST'), $f3->get('MAILPORT'), $f3->get('MAILPROTOCOL'), $f3->get('MAILUSER'), $f3->get('MAILPW') );
$smtp->set('Content-type', 'text/html; charset=UTF-8');
$smtp->set('Errors-to', '<$my_mail_address>');
$smtp->set('To', "<$my_mail_address>");
$smtp->set('From', '"$my_mailer_name" <$my_mail_address>');
$smtp->set('Subject', "$subject");
$smtp->set('Date', date("r"));
$smtp->set('Message-Id',generateMessageID());
$smtp->send(Template::instance()->render('emails/'.$mailTemplate.'.html'));
And it works like a charm. But I would like to add a text version to this e-mail.
Is there a way to do this within the Fat Free Framework smtp plugin?
If so, how should I do this?
And if not, how else should I do this in F3?
Actually it can send a multiplart text + html mail. The SMTP class is just a protocol implementation, so it might feel a little bit bare-bone at this point. You basically need to prepare your mail body with the multipart like this:
$text = 'Hello world.';
$html = 'Hello <b>world</b>';
$smtp = new \SMTP();
$hash=uniqid(NULL,TRUE);
$smtp->set('From', 'info#domain.com');
$smtp->set('To', 'info#domain.com');
$smtp->set('Content-Type', 'multipart/alternative; boundary="'.$hash.'"');
$smtp->set('Subject', 'Multipart test');
$eol="\r\n";
$body = '--'.$hash.$eol;
$body .= 'Content-Type: text/plain; charset=UTF-8'.$eol;
$body .= $text.$eol.$eol;
$body .= '--'.$hash.$eol;
$body .= 'Content-Type: text/html; charset=UTF-8'.$eol.$eol;
$body .= $html.$eol;
$smtp->send($body,true);

how to set the download path in php

I'm a web developer.
DownloadController.php
$local_file = 'file.zip';
$download_file = 'd:\temp\download.zip';
if(file_exists($local_file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($local_file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($local_file));
readfile($download_file);
}
I hope download the 'file.zip' and downloaded path that 'd:\temp\download.zip'
Anyone help me!
Thank u.
You can use following code to download a file:
return response()->download($pathToFile);
OR
return response()->download($pathToFile, $name, $headers)
The download method may be used to generate a response that forces the user's browser to download the file at the given path. The download method accepts a file name as the second argument to the method, which will determine the file name that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:
Docs

How to decode string using unkown algorithm?

I use Fiddler capture http request, but meet mojibake in http body.
mojibake http request img
I copy the http body as bas64 encode and try to know what it is.
There is the base64 encode string:
H4sIAAAAAAAAAIVUz2/cRBR2ckAcEFeuZYSE1O5aM+MZz9gHqONdixyaA0XNoa2qWXucjOK1t/6R7DYbqULcuNBKgLhFIQiQUoEQNy4lFw45cF9x459A4sLzbrNJowKWZc37Md/3/M1788XMettxPEcPBsqNB1JIJiRPJeNM0kQOUpzyeGZdIyTi2OlxFlEacRawXkR6nrfGRcQ8yp2vfo6Loa3ypCxMYleTqtbDxvzIbGbTrmO7NrGxoN4R8X63rJU7v9SH7/0ULLJvfNS7cYfY1BYMiAIZ9J2eE4UsXIt6QUix47q8x4UXMIrX+qfz/eyv1z5YLv6w3vphYLYqNayafMvfKMabwPP0zHrxLBdfj6V7Iii+TqjE1ynHR+HGSbhtcnXtVjEwmT56tP36s/Oy5rVbx5vr0frpN8zFGC++h4fWzPqYTqkQEgtGOQG1PG8ahUFAWJ/1HS4gDU8dTqlkGASVgr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Iii+TqjE1ynHR+HGSbhtcnXtVjEwmT56tP36s/Oy5rVbx5vr0frpN8zFGC++h4fWzPqYTqkQEgtGOQG1PG8ahUFAWJ/1HS4gDU8dTqlkGASVgrtk2u4WlFMiMGGUTqUnwSMJJpec/3sY07zJsmlejGer797dR3FTljqvkQ9rkyAfRaEfBD5hfh9ex+cCdVCmd3WG/C7nHVSNtIY8gnEHbZsk0TnyU5VVuoNyXe8V5c46hCGYq6EGvHto05Q6uX17vXcPAVayHY+Qv4+SvCIA40rJPU47aKiqndYWQlACPBCnc5xMq0r3mlLVpgAu6bKWutLlri6Rz0AlTAQAbO1dtgyQUJe41PEkPmjh43/5uZcz7wN0rPJcDTJ9IQomvsR+TH2M569zRZS6gtKZcBn1HI9jj3VQWuqHAMwIXUqxFAK1NGpXmWxBU5cNyFdPRm3WnkkNwMdFnpqtpmzFhjJGpSlKU0/+S9rL+rcMAJHruG4RWoaDzv45R6yzrMlUiV5KenGMVwo7uD+zfrt7sRXmtNZ5DE1jD2Fk47hooH+WRf35+DFqmfS4LhWcMJo3PcTnDjhSFN4Kw3ObtfZG2xamGmVqsrEAudLqaClOZYbnW10wr4zIRRWvmg1Q3bKePF39cma9o2IpU+k5XXeARZelmHYVTWlXJ2nsAJJ2vbi9IDZ//fvNh6vWZ08+f/bgQT22q2THrnSeHK7Mo6dvvH/yyVFdfK9ylU1qE1fHcZHos5tmcWN8m6lWq8nZzQ+fzx3HlXkE4U+/m1srz/8Br1K6vkAFAAA=";
$str = base64_decode($b64Encode);
$str = gzdecode($str);
var_dump($str);
file_put_contents('d:/123.txt', $str);
$enclist = array(
'UTF-8', 'ASCII',
'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4', 'ISO-8859-5',
'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9', 'ISO-8859-10',
'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
'Windows-1251', 'Windows-1252', 'Windows-1254', 'GBK', 'GB2312',
);
var_dump(mb_detect_encoding($str, $enclist));
$str2 = iconv("ISO-8859-1", "UTF-8", $str);
var_dump($str2);
php result img
It is already mojibake. How to decode it?

PHPExecel file is empty when send as in attachment

An excel file is created using phpexcel which is saved in the folder with all the data. The same file cannot be send as an attachment in the mail. I would also like to upload the excel in the form in order to make changes.
Please advice. Here is the code.
<?php
//include PHPExcel library
require_once "Classes/PHPExcel.php";
require_once "Classes/PHPExcel/IOFactory.php";
if (!empty($_POST['submit'])) {
//give a filename
$dtime = date('Y-m-d H-i-s');
$dtimeFile = date('Y-m-d-H-i-s');
date_default_timezone_set('Asia/Singapore');
$filename = 'myexcel'.$dtimeFile.'.xls';
$path = __DIR__;
//set headers to download file
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename='.$filename);
// create new PHPExcel object
$objTpl = new PHPExcel;
// set default font
$objTpl->getDefaultStyle()->getFont()->setName('Calibri');
// set default font size
$objTpl->getDefaultStyle()->getFont()->setSize(8);
// create the writer
$objWriter = PHPExcel_IOFactory::createWriter($objTpl, "Excel5");
// writer already created the first sheet for us, let's get it
$objSheet = $objTpl->getActiveSheet();
// rename the sheet
$objSheet->setTitle('My Personal Details');
// let's bold and size the header font and write the header
// as you can see, we can specify a range of cells, like here: cells from A1 to A4
$objSheet->getStyle('A1:C1')->getFont()->setBold(true)->setSize(12);
$objSheet->getStyle('A2:C2')->getFont()->setSize(12);
// write header
$objSheet->getCell('A1')->setValue('Name');
$objSheet->getCell('B1')->setValue('Email');
$objSheet->getCell('C1')->setValue('Location');
// we could get this data from database, but for simplicty, let's just write it
$objSheet->getCell('A2')->setValue(stripslashes($_POST['name']));
$objSheet->getCell('B2')->setValue(stripslashes($_POST['email']));
$objSheet->getCell('C2')->setValue(stripslashes($_POST['location']));
// // autosize the columns
// $objSheet->getColumnDimension('A')->setAutoSize(true);
// $objSheet->getColumnDimension('B')->setAutoSize(true);
// $objSheet->getColumnDimension('C')->setAutoSize(true);
// $objSheet->getColumnDimension('D')->setAutoSize(true);
$objWriter->save('php://output');
$to = "cloudinnovates#hotmail.com";
$subject = $filename;
$from = "shabs0#hotmail.com";
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n"
."Content-Type: multipart/mixed; boundary=\"1a2a3a\"";
$message .= "If you can see this MIME than your client doesn't accept MIME types!\r\n"
."--1a2a3a\r\n";
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n"
."Attached is the file number \"".$filename."\"\r\n\r\n"
."--1a2a3a\r\n";
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$message .= "Content-Type: application/vnd.ms-excel; name=\"".$filename."\"\r\n"
."Content-Transfer-Encoding: base64\r\n"
."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n"
."\r\n"
.chunk_split(base64_encode($content))
."--1a2a3a--";
// Send email
//
$success = mail($to, $subject, $message, $headers);
if (!$success) {
echo "Mail to ".$to." failed .";
} else {
echo "Success : Mail was send to ".$to;
}
}
//*************** upload file ***************//
if (!empty($_POST['btn-upload'])) {
$file = 'file';
$Reader = PHPExcel_IOFactory::createReaderForFile($file);
$Reader->setReadDataOnly(true);// set this, to not read all excel properties, just data
$objXLS = $Reader->load($file);
$value = $objXLS->getSheet(0)->getCell('A1')->getValue();
$objXLS->disconnectWorksheets();
unset($objXLS);
}
?>
I'm not familiar with PHP Excel and have not worked with PHP for a long time, but something stands out to me in your code.
You initialize a variable for the file name
$filename = 'myexcel'.$dtimeFile.'.xls';
and attempt to read the content of the file like this
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
But you don't appear to actually save your Excel sheet to that file. Rather, you seem to write it to the output stream of the current PHP page.
$objWriter->save('php://output');
Setting the content-disposition header
header('Content-Disposition: attachment;filename='.$filename);
tells the browser opening this PHP page what to do with the data returned by the PHP page, but does not save the file to your local server, so that it can be attached to an email on that server.
You will need to save the Excel file to a location on your local server before it is attached to the email.

Resources