Consume dll from php wamp - php

I have been given 2 dll's.
The first encrypts a string.
The second, decrypts an encrypted string.
I do not know how it works this dll.
Also I have been given a code example in .net (Don't know .net)
dll_decrypt_.Decrypt myuser = new dll_decrypt.Decrypt();
user = myuser.DecryptString(userEncrypted);
I have searched among the web, but still cant' find the answer.
Also I have added the 2 dll's to the ext folder in wamp:
C:\wamp64\bin\php\php7.0.32\ext
And added the "extension=dll_decrypt.dll" into the php.ini file both in apache and php folders.
This would be my php code:
try
{
$dll = new COM('dll_decrypt.Decrypt');
$dll->Function();
}
catch(Exception $e)
{
echo 'error: ' . $e->getMessage(), "\n";
}
I expect to get the decrypted string so I can see the user.

Related

How can I read a .csv file in R using Rserve to communicate with PHP on a LAMP system?

I would like to read the .csv file into R. I have been able to send the absolute path of the file to R and it will return it via the $test variable in the PHP code below. The $r->evalString("data<-read.csv(filetim,header=TRUE)"); returns an error that I have listed below. Any ideas as to what is causing the error?
<?php
require_once 'rconfig.php';
require 'rConnection.php';
try {
# Connect to R via Rserve
echo '<p>Connecting to Rserve '.RSERVE_HOST;
$r = new Rserve_Connection(RSERVE_HOST);
echo ' Connection OK</p>';
# Associate filename with the file's absolute path
$r->evalString("filetim=('folder/folder/folder/file.csv')");
$r->evalString("filebob=('folder/folder/folder/file2.csv')");
# Check if the filename is being stored
$test = $r->evalString("filebob");
echo $test;
# Read the .csv file into variable "data"
$r->evalString("data<-read.csv(filetim,header=TRUE)");
$r->close();
} catch(Exception $e) {
echo $e;
}
?>
Error:
'Rserve_Exception' with message 'unable to evaluate' in /folder/folder/folder/folder/folder/rConnection.php:239 Stack trace: #0 /folder/folder/folder/folder/folder/rcodetest.php(17): Rserve_Connection->evalString('data<-read.csv(f...') #1 {main}
This solution assumes you're on a Linux system. For Windows (if you got Rserve to work...) the story is the same.
The path you gave to read.csv is not an absolute, but a relative path. R starts from the working directory (by default often the user home directory on Linux systems, indicated in R by ~)
In your case,the absolute path would be
$r->evalString("filetim=('/folder/folder/folder/file.csv')");
To find out what R considers the working directory, you can use getwd(). Using try(), you can catch error messages inside R to get a better idea of what went wrong, as explained on the page of Rserve here : http://rforge.net/Rserve/faq.html#errors
You can also use a tryCatch() in R to get the R error message or the warning message. In the specific case of read.csv() the warning message might be more useful than the error (which simply says "cannot open the connection")
eg:
$err = $r->evalString("tryCatch(read.csv(filetim,header=TRUE), error = function(e) e)");
echo $err;
to catch the error, or
$err = $r->evalString("tryCatch(read.csv(filetim,header=TRUE), warning = function(w) w)");
echo $err;
to catch the warning. This should give you an idea about where R is looking for your file. Note that you might have to wrap the whole call to tryCatch in as.character(). I'm not sure if Rserve in combination with php can handle simpleWarning objects.

Microsoft Excel cannot access the file

Microsoft Excel cannot access the file
'C:\xxx\test.xls'. There are several possible reasons: • The file name
or path does not exist. • The file is being used by another program. •
The workbook you are trying to save has the same name as a currently
open workbook.
I followed this steps
link
Also I included the extesion "php_com_dotnet.dll" in php.ini.
I have Zend Server CE with php 5.3.14
The issue persist when I reboot the computer.
code::
$file = "C:\\xxx\\test.xls";
try {
$excel = new COM("Excel.Application") or die ("ERROR: Unable to instantaniate COM!\r\n");
$excel->Visible = true;
$Workbook = $excel->Workbooks->Open($file) or die("ERROR: Unable to open " . $file . "!\r\n");
} catch (Exception $exc) {
echo $exc->getMessage();
Things to consider:
Have you checked the permissions of the file? I'm assuming "xxx" is a placeholder for the proper folder name as well?
Do you have file open by something else? Excel perhaps? Excel will grab the file and "lock" it down from use by other things.
What user is the web server running as? Can it access that path?
try the answer from this guy named Aardigspook
in https://www.excelforum.com/excel-general/1182105-excel-cannot-access-the-file-2.html
The problem is a 'Name' . Go to the 'Formulas' tab, click 'Name Manager' and scroll down to the entry named 'special'. It refers to '--filepath--/[xxxxx.xlsx]Sheet1'!$A:$A'. Delete this, or amend it to a reference you have/want, and the error should be gone.
-captain hair.
After searching for a week and 3 times a new office 365 installation, my solution was to replace my faulty Micro-SD adapter.

Using Office Word to read doc files with PHP

I am trying to use PHP with word.application to read a file. It simply will not open the file. It's echoing the right version.
$w = new COM("word.application") or die("Is office installed?");
echo 'Loaded Word, version ' . $w->Version . '<br>';
$w->Visible = false;
$w->Documents->Open(realpath('test.docx'));
$content = (string) $w->ActiveDocument->Content;
echo $content;
$w->Quit();
$w->Release();
$w = null;
I get the error:
Uncaught exception 'com_exception' with message 'Source: Microsoft Word
Description: This command is not available because no document is open.'
It feels like it's some kind of permission problem. I tried to put the path of the test.docx besides using realpath and that did not help. Also tried to put it in the root of my C drive. I am using Windows 7 Professional and Microsoft Office 2007.
Documents->Open returns a document if all is ok. Probably, the document does not exists (path incorrect), or you haven't got the rights to open it from PHP. Store the result in $var, check if it has an appropriate value (probably not isset, null or false if not), and use $var->Content to read the content.
Try doing a file_exists on said
file/path.
If that works, try
file_get_contents and see if you can
read it.
If that all works - then it's not a problem with permissions/etc.

PHP Copy command failing when spaces?

I am executing the following commands:
<?php
copy ("http://localhost/.../DSCF8253.JPG" , "sites/default/files/DSCF8253.JPG"); // Success!
copy ("http://localhost/.../DSCF8260.JPG" , "sites/default/files/DSCF8260.JPG"); // Success!
copy ("http://localhost/.../HERMAN 085.jpg" , "sites/default/files/HERMAN 085.jpg" ); // Fail!
?>
The first two copy fine, but not the last one. Why?
It must have something to do with the filenames (the last one has a SPACE before the 085).
Any help would be greatly appreciated!
http://localhost/.../HERMAN 085.jpg
Should be
http://localhost/.../HERMAN%20085.jpg
Copy & the http wrappers are less forgiving then browsers / user-agents when it comes to invalid urls. A space in an url is invalid, so it should be urlencode'd.
//i used this code once i tried to copy images to a wordpress site and set post featured image
//i only mentioned the part you want and did not mention other parts
$image_url = 'http://example.com/images/my image with spaces.jpg';
try {
//throw exception if can't move the file
if (!copy(str_replace(" ","%20",$image_url),$file)) {
$errors = error_get_last();
throw new Exception('Could not copy file');
}
} catch (Exception $e) {
echo $e->getMessage();
}
//using urlencode will corrupt the url if used with the full url
//it will generate something like http%dsf%swdfablablabla
//if you need to encode you will encode anything after http://yoursite.com/{encode only works here}
Strangest thing: the %20 way doesn't seem to do the trick, but after some trying
in vain (first with %20, then quoting the filename, then double-quoting, then
protecting spaces, tell me if I missed something), now the original version works flawlessly. This is Windows 10, PHP 5.5.12 and we are in year 2016.
Good luck with all these deterministic, finite-state systems :)
A possible solution btw, is to use exec() and do a copy on the operating
system level. Then again, it's OS specific.

Create an encrypted zip archive with PHP

I am searching for a way to encrypt a .txt file into a zip, but in a secure password protected way. My goal is to email this file to me, without anyone being able to read the content of the attachment.
Does anybody know an easy, and above all, secure way to accomplish this ? I can create zip archives, but I do not know how to encrypt them, or, how secure this is.
As of php 7.2 (which was released a hours ago), the right way to do this is to use additional functionality included in ZipArchive native php code. (thanks to abraham-tugalov for pointing out that this change was coming)
Now the simple answer looks something like this:
<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
$zip->setPassword('secret_used_as_default_for_all_files'); //set default password
$zip->addFile('thing1.txt'); //add file
$zip->setEncryptionName('thing1.txt', ZipArchive::EM_AES_256); //encrypt it
$zip->addFile('thing2.txt'); //add file
$zip->setEncryptionName('thing2.txt', ZipArchive::EM_AES_256); //encrypt it
$zip->close();
echo "Added thing1 and thing2 with the same password\n";
} else {
echo "KO\n";
}
?>
But you can also set the encryption method by index and not name, and you can set each password on a per-file basis... as well as specify weaker encryption options, using the newly supported encryption options.
This example exercises these more complex options.
<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
//being here means that we were able to create the file..
//setting this means that we do not need to pass in a password to every file, this will be the default
$zip->addFile('thing3.txt');
//$zip->setEncryptionName('thing3.txt', ZipArchive::EM_AES_128);
//$zip->setEncryptionName('thing3.txt', ZipArchive::EM_AES_192);
//you should just use ZipArchive::EM_AES_256 unless you have super-good reason why not.
$zip->setEncryptionName('thing3.txt', ZipArchive::EM_AES_256, 'password_for_thing3');
$zip->addFile('thing4.txt');
//or you can also use the index (starting at 0) of the file...
//which means the following line should do the same thing...
//but just referencing the text.txt by index instead of name..
//$zip->setEncryptionIndex(1, ZipArchive::EM_AES_256, 'password_for_thing_4'); //encrypt thing4, using its index instead of its name...
$zip->close();
echo "Added thing3 and thing4 with two different passwords\n";
} else {
echo "KO\n";
}
?>
The underlying support for zip encryption is enabled because libzip 1.2.0 introduced support for encryption. So you will need to have php 7.2 and libzip 7.2 in order to run this code... Hopefully this note will be cruft on this answer "real soon"
Note: this answer recommends a cryptographic method that is known
insecure, even with good password. Please see link from comments
and the Winzip QA on AES. Support for in-php AES zip encryption
arrives with php 7.2 (and libzip 1.2.0), which means this
answer will soon be outdated too. Until then see this answer for how
to call out to 7z instead of the zip command, which supports winzip's
AES encryption.
You can use this:
<?php echo system('zip -P pass file.zip file.txt'); ?>
Where pass is the password, and file.txt will be zipped into file.zip. This should work on Windows and Linux, you just need to get a free version of zip for Windows ( http://www.info-zip.org/Zip.html#Win32 )
This kind of security can be broken by brute force attacks, dictionary attacks and etc. But it's not that easy, specially if you chose a long and hard to guess password.
Although PHP is a mature language, there is no adequate method (excluding custom extension or something like that) to achieve such a simple task with pure PHP.
What you also can do, is to wait until PHP 7.2 will be available for production (because ZipArchive::setEncryptionName is implemented (thanks to Pierre and Remi)).
But, until then you also can try to port php_zip >= 1.14.0 to PHP < 7.2, but there is currently no compiled binaries available, so you have to compile it yourself and try if it is possible at all (I believe it is).
PS I would try it, but have no VS2015+ on my PC right now.
More and more tools are supporting AES-encrypted ZIP files. It works, it's secure.
EDIT2: You can use DotNetZip from PHP to dynamically generate AES-encrypted zip archives from PHP. DotNetZip is a .NET library that is designed for .NET languages (C#, VB, etc). It runs only on Windows :(. But DotNetZip does AES, and it's free, and it works from PHP.
This is the code I used. (PHP v5.2.9 on Win32)
<?php
try
{
$fname = "zip-generated-from-php-" . date('Y-m-d-His') . ".zip";
$zipOutput = "c:\\temp\\" . $fname;
$zipfact = new COM("Ionic.Zip.ZipFile");
$zip->Name = $zipOutput;
$dirToZip= "c:\\temp\\psh";
# Encryption: 3 => 256-bit AES.
# 2 => 128-bit AES.
# 1 => PKZIP (Weak).
# 0 => None
$zip->Encryption = 3;
$zip->Password = "AES-Encryption-Is-Secure";
$zip->AddDirectory($dirToZip);
$zip->Save();
$zip->Dispose();
if (file_exists($zipOutput))
{
header('Cache-Control: no-cache, must-revalidate');
header('Content-Type: application/x-zip');
header('Content-Disposition: attachment; filename=' . $fname);
header('Content-Length: ' . filesize($zipOutput));
readfile($zipOutput);
unlink($zipOutput);
}
else
{
echo '<html>';
echo ' <head>';
echo ' <title>Calling DotNetZip from PHP through COM</title>';
echo ' <link rel="stylesheet" href="basic.css"/>';
echo ' </head>';
echo '<body>';
echo '<h2>Whoops!</h2>' . "<br/>\n";
echo '<p>The file was not successfully generated.</p>';
echo '</body>';
echo '</html>';
}
}
catch (Exception $e)
{
echo '<html>';
echo ' <head>';
echo ' <title>Calling DotNetZip from PHP through COM</title>';
echo ' <link rel="stylesheet" href="basic.css"/>';
echo ' </head>';
echo '<body>';
echo '<h2>Whoops!</h2>' . "<br/>\n";
echo '<p>The file was not successfully generated.</p>';
echo '<p>Caught exception: ', $e->getMessage(), '</p>', "\n";
echo '<pre>';
echo $e->getTraceAsString(), "\n";
echo '</pre>';
echo '</body>';
echo '</html>';
}
?>
I had to modify DotNetZip to make it work with PHP: I had to make the Name property read/write, and I had to make it COM-callable. This change is first available in the v1.8.2.3 release.
This is how I did it.
It's with an excel, but it's the same thing.
Let php create a random codename.
Save the codename in db or in a file to be included by the retrieve.php.
Mail yourself the codename.
Access via web the retrieve.php?codename=[codename]
Let php check if codename is correct. (maybe even it's age).
Create the excel/textfile in memory from the data that needs to be send to you.
Create an encryption code by adding a local password (that only you know) with the codename.( I say add but can also be mixed or xor-ed or substr... )
Encrypt on the fly with the created encryption code.
Remove the codename from db or config file.
Return this encrypted document in a mail (zipped or not for size).
Maybe add two first characters from codename in the mail to know what local full codename to use.
Use a local decryption script to decode the downloaded file. Use same codename/password algorithm to create a decryption key.
I use gibberish-aes-php. ( https://github.com/ivantcholakov/gibberish-aes-php )
Because then I can use https://github.com/mdp/gibberish-aes as javascript on a client decoder (for things I want to take a quick peek at in a browser).

Categories