I am trying to upload an image to a WordPress website using my custom code but it is not working. The directory is writable and there is no other error. The subdirectory 'contracts' was created manually.
$uploads = wp_get_upload_dir();
$fileTmpPath = $_FILES['upload_img']['tmp_name'];
$fileName = $_FILES['upload_img']['name'];
$fileSize = $_FILES['upload_img']['size'];
$fileType = $_FILES[$filename]['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
$allowedfileExtensions = array('jpg', 'gif', 'png');
if (in_array($fileExtension, $allowedfileExtensions)) {
$dest_path = $uploads['basedir'].'/contracts/'. $newFileName;
if ( !is_writeable( $upload_path ) ) {
echo 'Unable to write to directory.';
}
if(move_uploaded_file($fileTmpPath, $dest_path)){
echo $uploads['baseurl'].'/contracts/'.$newFileName;
}
}
There is a small typo in the code, not sure if this would stop execution but non the less try with this code
$uploads = wp_get_upload_dir();
$fileTmpPath = $_FILES['upload_img']['tmp_name'];
$fileName = $_FILES['upload_img']['name'];
$fileSize = $_FILES['upload_img']['size'];
$fileType = $_FILES['upload_img']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
$allowedfileExtensions = array('jpg', 'gif', 'png');
if (in_array($fileExtension, $allowedfileExtensions)) {
$dest_path = $uploads['basedir'].'/contracts/'. $newFileName;
if ( !is_writeable( $upload_path ) ) {
echo 'Unable to write to directory.';
}
if(move_uploaded_file($fileTmpPath, $dest_path)){
echo $uploads['baseurl'].'/contracts/'.$newFileName;
}
}
Related
Unfortunately 7.3 doesn't support mcrypt and I have to refactor some code.
I cannot migrate this encription function:
mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, pkcs5_pad(trim($strToEncode), mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB)), MCRYPT_MODE_ECB, $iv);
I tried this code:
function pkcs5_pad ($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
$cipher = "aes-128-gcm";
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
$block_size = strlen(openssl_encrypt('', $cipher, '', OPENSSL_RAW_DATA, $iv));
$ciphertext = openssl_encrypt(pkcs5_pad(trim($strToEncode),$block_size), $cipher, $key, $options=0, $iv);
But it doesn't work and I got: Uncaught DivisionByZeroError in pkcs5_pad function
This is the working code:
$cipher = "aes-128-ecb";
$ciphertext = openssl_encrypt(trim($strToEncode), $cipher, $key, OPENSSL_RAW_DATA);
I am new in PHPUnit and i am required to run the test using browser and save the result in xml format.
But every time when i run this code, i got following error:
FatalErrorException: Error: Interface 'PHPUnit_Framework_Test' not found in /usr/share/php/PHPUnit/Framework/TestSuite.php line 83
My code looks like this:
require_once '/var/www/Drillsight/app/autoload.php';
require_once "PHPUnit/Framework/TestSuite.php";
require_once "PHPUnit/TextUI/TestRunner.php";
$run_command = new PHPUnit_TextUI_Command;
$run_command ->run(array('phpunit', '--log-junit', 'results.xml', 'MyPHPUnitTest.php'),true);
Can anybody help in this matter?
Any other recommendation options will be highly appreciated !
Thanks in advance !
Do it really need to be runned in a browser?
I personally use a .bat file containing all my unit test like this
REM GEM_MECHANIC_TESTS
ECHO.
ECHO FILE : GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GENERAL_CONTROLER/TEST/GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
REM GEM_MECHANIC_INTERFACE_BUILDER_TESTS
ECHO.
ECHO FILE : HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GENERAL_CONTROLER/TEST/TEST_INTERFACE_BUILDER/HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
And run a command like this in my Xampp console:
C:\xampp\htdocs\PC_administration_interface\Controler/script/temp_unit_test.bat >C:\xampp\htdocs\PC_administration_interface\Controler/test_result.txt
Or if you want to do it automatically each night with a windows task:
Launch_xampp.bat
#echo off
tasklist | find /i "xampp-control.exe" && goto :eof
start /b "xampp-control.exe" "C:\xampp\xampp-control.exe"
launch_automatic_test.bat
#echo off
call %~DP0\launch_xampp.bat
call %~DP0\..\..\..\..\xampp_shell.bat
cls
call %~DP0\run_unit_test.bat > "%~DP0\..\test_result.txt"
The method don't matter as much as I export the result in a textfile and than use PHP to parse the output (you can just change the code a bit to produce XML).
public static function fetchTestResult(&$errorMessage){
$echoString = '';
$failure = false;
$fileContent = '';
$errorMessage = '';
$dbManager = GeneralDbManager::getInstance();
if (file_exists(realpath(dirname(__FILE__)) . '/test_result.txt')) {
#$fileContent = file(realpath(dirname(__FILE__)) . '/test_result.txt');
if ($fileContent === false){
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_RESULT_LOG_ERR', "An error happened while reading the unit tests results log.");
}
else{
unlink(realpath(dirname(__FILE__)) . '/test_result.txt');
if (file_exists(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat')) {
unlink(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat');
}
$echoString = HtmlTagBuilder::createCustomTextArea("TA_UNIT_TEST_RESULT", TextAlign::ALIGN_LEFT, false, 1100, 500);
foreach ($fileContent as $line){
if (StringManager::stringStartWith($line, "FILE :")){
$failure = false;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::TITLE_LINE);
}
elseif (StringManager::stringStartWith($line, "time:")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::WARNING_LINE);
}
elseif (StringManager::stringStartWith($line, "OK (")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::SUCCESS_LINE);
}
elseif ((StringManager::stringStartWith($line, "There ") and strpos($line, "failure") !== false)
or $failure === true){
$failure = true;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
elseif (strpos(strtolower($line), "failure") !== false){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
else{
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::REGULAR_LINE);
}
}
$echoString .= '</DIV><br><br>';
}
}
else{
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_NO_RESULT_LOG_ERR', "You must run the unit test and generate the test log before displaying it.");
}
return $echoString;
}
i accomplished the read of excel with php but the write i cannot, i not know why..
in the file to read, take one column and write in a new file excel and paste there is.. for now only that..
Thank to all..
<?php
require_once "excel/Classes/PHPExcel.php";
require_once "excel/Classes/PHPExcel/IOFactory.php";
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
set_time_limit ( 0 );
ini_set('memory_limit', '-1');
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
?>
<form action="" method="post" enctype="multipart/form-data">
Desea comenzar el proceso ?
<input type="submit" value="Aceptar" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$objPHPExcel_load = new PHPExcel();
$PHPExcel_save = new PHPExcel();
$PHPExcel_save->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
$PHPExcel_save->setActiveSheetIndex(0)
->setCellValue('A1', 'Cedula');
$PHPExcel_save->getActiveSheet()->setTitle('Simple');
$PHPExcel_save->setActiveSheetIndex(0);
$inputFileName = 'discussdesk.xlsx';
$objPHPExcel_load = PHPExcel_IOFactory::load($inputFileName);
$objWorksheet = $objPHPExcel_load->getActiveSheet();
$cantidad = $objWorksheet->getHighestRow();// tamaƱo de los registros
$objeto_pegar = $PHPExcel_save->getActiveSheet(0);
echo "cantidad : ".$cantidad;
$prueba = true;
$row = 2;
$column = 1;
for($i = 1;$i <= $cantidad;$i++){
$celda = trim($objWorksheet->getCellByColumnAndRow(7, $row)->getValue());
$PHPExcel_save->setActiveSheetIndex(0)->setCellValueByColumnAndRow(1, $row, $celda);
echo $celda.'<br>';
if(is_null($celda)){
break;
}
$row +=1;
}
$PHPExcel_save->setActiveSheetIndex(0);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($PHPExcel_save, 'Excel2007');
$objWriter->save('php://output');
}
?>
$PHPExcel_writer = new PHPExcel();
$objReader = PHPExcel_IOFactory::createReader('Excel2007'); // crea el archivo a leer
$PHPExcel_ = $objReader->load('testFile.xlsx'); // load the file
$PHPExcel_->setActiveSheetIndex(0)
->setCellValue('A1', 'field1')
->setCellValue('B1', 'field2')
->setCellValue('C1', 'field3')
->setCellValue('D1', 'field4')
->setCellValue('E1', 'field5')
->setCellValue('F1', 'field6'); // write the first row(tittle)
//$PHPExcel_writer->setActiveSheet()->setTitle('Simple');
$PHPExcel_->setActiveSheetIndex(0);
//
$objPHPExcel_load = new PHPExcel();
$inputFileName = 'discussdesk.xlsx';
$objPHPExcel_load = PHPExcel_IOFactory::load($inputFileName);
$objWorksheet = $objPHPExcel_load->getActiveSheet();
$cantidad = $objWorksheet->getHighestRow();// size of row*/
//echo "count : ".$cantidad;
//$row = 2;
//$column = 1;
//$PHPExcel_writer->getActiveSheet()->setTitle('Simple');
//$PHPExcel_writer->setActiveSheetIndex(0)->setCellValueByColumnAndRow(1, 1, "prueba");
for($i = 1;$i <= 1000;$i++){ ?>
<script> envia_barra(<? echo $i; ?>);
</script>
<?php
/*$celda = trim($objWorksheet->getCellByColumnAndRow(12, $row+3)->getValue());
$data = file_get_contents("youweb?param=".$celda);
set_time_limit(5);
$PHPExcel_->getActiveSheetIndex(0);
if(preg_match('|<td width="180" class="tblbgcolort"><strong>Departamento:</strong></td>\s+<td width="400" class="tblbgcolort">(.*?)</td>|is' , $data , $dep )){
preg_match('|<td width="180" class="tblbgcolort"><strong>Departamento:</strong></td>\s+<td width="400" class="tblbgcolort">(.*?)</td>|is' , $data , $dep );
preg_match('|<td class="tblbgcolor"><strong>Municipio:</strong></td>\s+<td class="tblbgcolor">(.*?)</td>|is' , $data , $mun );
preg_match('%<strong>Puesto:</strong>.+?<td>(.+?)</td>%si',$data,$puesto);
preg_match("%<div style='float:left;'>(.*?)<\/div>%si", $data , $dir );
preg_match('|<td class="tblbgcolor"><strong>Mesa</strong></td>\s+<td class="tblbgcolor">(.*?)</td>|is' , $data , $mes );
$PHPExcel_->setActiveSheetIndex(0)->setCellValueByColumnAndRow(0,$row, $celda);
$PHPExcel_->setActiveSheetIndex(0)->setCellValueByColumnAndRow(1,$row,$dep[1]);
$PHPExcel_->setActiveSheetIndex(0)->setCellValueByColumnAndRow(2,$row,$mun[1]);
$PHPExcel_->setActiveSheetIndex(0)->setCellValueByColumnAndRow(3,$row,$puesto[1]);
$PHPExcel_->setActiveSheetIndex(0)->setCellValueByColumnAndRow(4,$row,$dir[1]);
$PHPExcel_->setActiveSheetIndex(0)->setCellValueByColumnAndRow(5,$row,$mes[1]);
}else{
$PHPExcel_->getActiveSheet()->setCellValueByColumnAndRow(0,$row,$celda);
$PHPExcel_->getActiveSheet()->setCellValueByColumnAndRow(1,$row ,"No hay registro");
}
$row++;
if(is_null($celda)){
break;
}
}
//$PHPExcel_writer->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($PHPExcel_, 'Excel2007');
$objWriter->save('testFile.xlsx');
//$objWriter->save('php://output');
//header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//header("Content-Disposition: attachment;filename=\"discussdesk.xlsx\"");
//header("Cache-Control: max-age=0");
//$objWriter = PHPExcel_IOFactory::createWriter($PHPExcel_writer, 'Excel2007');
//$objWriter->save('php://output');
exit;
I have been working on a powershell script that uses a .txt file to download multiple files from tinyurls. I have been successful in using Jobs to make this happen simultaneously, thanks to those on this forum.
The project requires some pretty large files to be downloaded, and using the current method has no progress indicator. I figured some users might think the program died. Looking for a way give a status of where it is in the download. Here is what I came up with, but I'm lost in how to pipe this information back out to the console. Any suggestions?
#Checks to see if NT-Download folder is on the Desktop, if not found, creates it
$DOCDIR = [Environment]::GetFolderPath("Desktop")
$TARGETDIR = "$DOCDIR\NT-Download"
if(!(Test-Path -Path $TARGETDIR )){
New-Item -ItemType directory -Path $TARGETDIR
}
$filepaths = Resolve-Path "files.txt"
Get-Content "$filepaths" | Foreach {
Start-Job {
function Save-TinyUrlFile
{
PARAM (
$TinyUrl,
$DestinationFolder
)
$response = Invoke-WebRequest -Uri $TinyUrl
$filename = [System.IO.Path]::GetFileName($response.BaseResponse.ResponseUri.OriginalString)
$filepath = [System.IO.Path]::Combine($DestinationFolder, $filename)
$totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)
$responseStream = $response.GetResponseStream()
$buffer = new-object byte[] 10KB
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $count
try
{
$filestream = [System.IO.File]::Create($filepath)
$response.RawContentStream.WriteTo($filestream)
$filestream.Close()
while ($count -gt 0)
{
[System.Console]::CursorLeft = 0
[System.Console]::Write("Downloaded {0}K of {1}K", [System.Math]::Floor($downloadedBytes/1024), $totalLength)
$targetStream.Write($buffer, 0, $count)
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $downloadedBytes + $count
}
"`nFinished Download"
$targetStream.Flush()
$targetStream.Close()
$targetStream.Dispose()
$responseStream.Dispose()
}
finally
{
if ($filestream)
{
$filestream.Dispose();
}
}
}
Save-TinyUrlFile -TinyUrl $args[0] -DestinationFolder $args[1]
} -ArgumentList $_, "$TARGETDIR"
}
Have a look at Write-Progress
PS C:> for ($i = 1; $i -le 100; $i++ )
{write-progress -activity "Search in Progress" -status "$i% Complete:" -percentcomplete $i;}
Far more simple way : rely on Bits:
Start-BitsTransfer -Source $tinyUrl
VMware ESX, ESXi, and VirtualCenter are supposed to be able to support HTTP PUT uploads since version 3.5. I know how to do downloads, that's easy. I've never done PUT before.
Background information on the topic is here: http://communities.vmware.com/thread/117504
You should have a look at the Send-PoshCode function in the PoshCode cmdlets script module ... it uses a POST, not a PUT, but the technique is practically identical. I don't have PUT server I can think of to test against, but basically, set your $url and your $data, and do something like:
param($url,$data,$filename,[switch]$quiet)
$request = [System.Net.WebRequest]::Create($url)
$data = [Text.Encoding]::UTF8.GetBytes( $data )
## Be careful to set your content type appropriately...
## This is what you're going to SEND THEM
$request.ContentType = 'text/xml;charset="utf-8"' # "application/json"; # "application/x-www-form-urlencoded";
## This is what you expect back
$request.Accept = "text/xml" # "application/json";
$request.ContentLength = $data.Length
$request.Method = "PUT"
## If you need Credentials ...
# $request.Credentials = (Get-Credential).GetNetworkCredential()
$put = new-object IO.StreamWriter $request.GetRequestStream()
$put.Write($data,0,$data.Length)
$put.Flush()
$put.Close()
## This is the "simple" way ...
# $reader = new-object IO.StreamReader $request.GetResponse().GetResponseStream() ##,[Text.Encoding]::UTF8
# write-output $reader.ReadToEnd()
# $reader.Close()
## But there's code in PoshCode.psm1 for doing a progress bar, something like ....
$res = $request.GetResponse();
if($res.StatusCode -eq 200) {
[int]$goal = $res.ContentLength
$reader = $res.GetResponseStream()
if($fileName) {
$writer = new-object System.IO.FileStream $fileName, "Create"
}
[byte[]]$buffer = new-object byte[] 4096
[int]$total = [int]$count = 0
do
{
$count = $reader.Read($buffer, 0, $buffer.Length);
if($fileName) {
$writer.Write($buffer, 0, $count);
} else {
$output += $encoding.GetString($buffer,0,$count)
}
if(!$quiet) {
$total += $count
if($goal -gt 0) {
Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100)
} else {
Write-Progress "Downloading $url" "Saving $total bytes..." -id 0
}
}
} while ($count -gt 0)
$reader.Close()
if($fileName) {
$writer.Flush()
$writer.Close()
} else {
$output
}
}
$res.Close();
In the VI Toolkit Extensions use Copy-TkeDatastoreFile. It will work with binaries.