Zend Framework - how to upload a file - zend-framework

How can i upload a file? Stackoverflow i cant page codes so please check this link: http://pastebin.org/386639
Thanks in advance
LATER:
Later i updated this as following, because ZF is not friendly, they keep still everything top secret! :P
public static function mvUploadFile()
{
//
// $_GET/_POST/FILE what ever
//
$fname = basename( $_FILES['attachment']['name']);
$_fname = strtolower (end(explode('.',$fname) ) );
Zend_Debug::dump( $_FILES );
//
// Filter the file
//
switch($_fname)
{
case ($_fname == 'jpg' ||
$_fname == 'jpeg' ||
$_fname == 'gif' ||
$_fname == 'bmp' ||
$_fname == 'png' ||
$_fname == 'html' ||
$_fname == 'pdf' ||
$_fname == 'doc' ||
$_fname == 'docx' ||
$_fname == 'xls'
):
$target_path = APPLICATION_PATH . "/../public/files/textual_translation_attachment/";
//chmod("../up" , 0777);
$target_path = $target_path . basename( $_FILES['attachment']['name']);
if(move_uploaded_file($_FILES['attachment']['tmp_name'], $target_path)) {
//echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
//$_sql = "insert into a (huis,image) values ('$_app','$_file')";
// send the file name only .....
//echo $fname ;
}else{
//echo "error ";
}
break;
}
return $fname;
}

If you
Zend_Debug::dump($_FILES);
Do you see your file?

If you are using jQuery, you may want to try Uploadify. This can be done using the
Zend Framework Uploadify Extension
http://gondo.webdesigners.sk/zend-framework-uploadify-extension/

Related

Why imagecreatefromjpeg not working for .jpg extension?

I have code for thumbnails which works great for gif, png and jpeg files but not for jpg.
Please help me how to make it work for jpg.
I get no errors and nothing in log file.
function create_thumb($src,$dest,$desired_width = false, $desired_height = false){
if (!$desired_height&&!$desired_width) return false;
$fparts = pathinfo($src);
$ext = strtolower($fparts['extension']);
if (!in_array($ext,array('gif','jpg','png','jpeg'))) return false;
if ($ext == 'gif') $resource = imagecreatefromgif($src);
else if ($ext == 'png') $resource = imagecreatefrompng($src);
else if ($ext == 'jpg' || $ext == 'jpeg') $resource = imagecreatefromjpeg($src);
$width = imagesx($resource);
$height = imagesy($resource);
if(!$desired_height) $desired_height = floor($height*($desired_width/$width));
if(!$desired_width) $desired_width = floor($width*($desired_height/$height));
$virtual_image = imagecreatetruecolor($desired_width,$desired_height);
imagecopyresized($virtual_image,$resource,0,0,0,0,$desired_width,$desired_height,$width,$height);
$fparts = pathinfo($dest);
$ext = strtolower($fparts['extension']);
if (!in_array($ext,array('gif','jpg','png','jpeg')))
$ext = 'jpg';$dest = $fparts['dirname'].'/'.$fparts['filename'].'.'.$ext;
if ($ext == 'gif') imagegif($virtual_image,$dest);
else if ($ext == 'png') imagepng($virtual_image,$dest,1);
else if ($ext == 'jpg' || $ext == 'jpeg') imagejpeg($virtual_image,$dest,72);
return array( 'width' => $width, 'height' => $height, 'new_width' => $desired_width, 'new_height'=> $desired_height, 'dest' => $dest ); }
I find solution for me...
$dest = $fparts['dirname'].'/'.$fparts['filename'].'.gif';
imagewebp($virtual_image,$dest,80);
Every image is gif and very small size ;)
Hope it will help to somebody.

email attachment not received magento form

create custom form with email file jpg attached successfully sent to server. but the problem is, there's no email attached when receive email. try looking for all this forum no result. still get no email attached on receiving email. here's my code on indexcontroller.
upload server controlling
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf', 'jpg'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'confirm' . DS ;
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path, $_FILES['attachment']['confirm'] );
$newFilename = $uploader->getUploadedFileName();
} catch (Exception $e) {
$error = true;
}
}
code to call email file attached
$attachmentFilePath = Mage::getBaseDir('media'). DS . 'confirm' . DS . $fileName;
if(file_exists($attachmentFilePath)){
$fileContents = file_get_contents($attachmentFilePath);
$attachment = $mail->getMail()->createAttachment($fileContents);
$attachment->filename = $fileName;
}
hope someone can help my problem thanks
Try this code
//upload code
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf', 'jpg'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'confirm' . DS ;
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path, $_FILES['attachment']['confirm'] );
$newFilename = $uploader->getUploadedFileName();
$mailTemplate = Mage::getModel('core/email_template');
$mailTemplate->setSenderName('Sender Name');
$mailTemplate->setSenderEmail('sender#sender.email');
$mailTemplate->setTemplateSubject('Subject Title');
$mailTemplate->setTemplateText('Body Text');
// add attachment
$mailTemplate->getMail()->createAttachment(
file_get_contents($path.$newFilename), //location of file
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
basename( $newFilename )
);
$mailTemplate->send('toemail#email.com','subject','set message');
} catch (Exception $e) {
$error = true;
}
}

column missing in exchangearray

I'm missing a column in my exchangeArray. It is the column with the filename, here a snippet of my controller add action:
if ($form->isValid()) {
$data = $form->getData();
// Upload path
$location = "public/files/";
// A bit validation of uploaded file
$allowedExtension = array('xls', 'xlsx');
$extension = explode('.', $data['DCL_Path']['name']);
$extension = end($extension);
$import['DCL_Path']=$data['DCL_Path']['name'];
//$fileName = time() . '.' . $extension;
$fileName = $data['DCL_Path']['name'];
// Check if everything is OK!
//echo $fileName;
if (0 === $data['DCL_Path']['error'] && in_array($extension, $allowedExtension)) {
move_uploaded_file($data['DCL_Path']['tmp_name'], $location . $fileName);
} else {
echo 'Something went wrong!';
}
//$namen = explode(",", $import ); //Konvertierung des Strings in ein Array
//echo "<pre>"; var_dump($namen); echo "</pre>"; //Formartierte Ausgabe des Arrays
$this->table->saveImport($import);
Everything will be saved, but DCL_path is missing.
Here my exchangearray also:
public function exchangeArray(array $data)
{
$this->DCLID= !empty($data['DCLID']) ? $data['DCLID'] : null;
$this->UnitID= !empty($data['UnitID']) ? $data['UnitID'] : null;
$this->DCL_Path= !empty($data['DCL_Path']) ? $data['DCL_Path'] : null;
$this->Importdate= !empty($data['Importdate']) ? $data['Importdate'] : null;
$this->Importuser= !empty($data['Importuser']) ? $data['Importuser'] : null;
$this->Importok= !empty($data['Importok']) ? $data['Importok'] : null;
$this->DCL_Type= !empty($data['DCL_Type']) ? $data['DCL_Type'] : null;
$this->Changed_per_User= !empty($data['Changed_per_User']) ? $data['Changed_per_User'] : null;
$this->Description_Changes= !empty($data['Description_Changes']) ? $data['Description_Changes'] : null;
}
I added this statement: $import['DCL_Path']=$data['DCL_Path']['name']; to force it, but it didn't help. So my question would be how to add data in datafields of my exchangeArray.
EDIT1: Here is the start off my addAction.
$import = new Import(); //Neue Instanz von Import
$form->setInputFilter($import->getInputFilter()); //Filter an Form binden
$form->setData($request->getPost()); //Daten abholen
//echo $form->isValid();
if (! $form->isValid()) {
return ['form' => $form]; //Wenn die Daten nicht valide sind
// return $this->redirect()->toRoute('import'); //Routing
// Zend_Debug::dump("nicht valide");
//echo "nicht valide";
}
else{ //aus Tableadapter
$import->exchangeArray($form->getData());
// echo "valide";
//echo $import["DCL_Path"];
// Merge data thus
$data = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
$form->setData($data);
I also find another solution which is working, I post it additional perhaps it might help somebody else. Of course I still would prefer the way via exchangeArray.
$this->table->saveImport($import); //Daten speichern
$letzter = $this->table->getlastImport($fileName);
echo ($letzter->DCLID);
$this->table->updateoneRow($letzter->DCLID, 'DCL_Path', $fileName);

Change target link based on visitor's country

I have website.com/sample-page with some text and a download button (external link like download.com/file)
I want to change the target link (download.com/file) if a user is from France. I dont want to redirect entire page/website, only this link.
I am using wordpress (if helps).
Some advices, please.
Is very simple, you need to detect the user language, then go with if, elseif, else and call the header location when need or simple doing echo of link...
$find = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$lang = substr($find,0,2);
if ($lang == "fr") {
header("Location: download.com/file_fr");
exit();
} elseif ($lang == "it") {
header("Location: download.com/file_it");
exit();
} elseif ($lang == "xx") {
header("Location: download.com/file_xx");
exit();
} else {
header("Location: download.com/file");
exit();
}
or using another trick...
$link = "";
$find = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$lang = substr($find,0,2);
if ($lang == "fr") {
$link = "download.com/file_fr";
} elseif ($lang == "it") {
$link = "download.com/file_it";
} elseif ($lang == "xx") {
$link = "download.com/file_xx";
} else {
$link = "download.com/file";
}
echo "$link";
Let's me know if my answer is what you want :)

Uploading transparent images adds a black background

I am trying to make a function to handle avatar uploads.
My problem is, when I upload a transparent image, it turned everything which is transparent black after I resize it.
I have tried using the imagesavealpha() & imagealphablending() options, but the background is still turning black.
It might just be me being blind and not seeing the problem in the code, but I have no idea why it does this.
I can confirm that after the image has been moved to the image/avatars folder just after being uploaded, the background is still transparent.
this is my current code, I have been testing with .png images:
function upload_avatar(){
$base_path = SYSTEM_PATH;
if($_FILES['avatar_img']['tmp_name'] != '') {
$id = md5($this->user_id());
$filename = $_FILES['avatar_img']['name'];
$file_basename = substr($filename, 0, strripos($filename, '.')); // strip extention
$file_ext = substr($filename, strripos($filename, '.')); // strip name
$filesize = $_FILES['avatar_img']['size'];
$newfilename = $id . $file_ext;
if ($file_ext == ".jpg" || $file_ext == ".JPG" || $file_ext == ".jpeg" || $file_ext == ".png" || $file_ext == ".gif"){
if($filesize <= 153600){
move_uploaded_file($_FILES['avatar_img']['tmp_name'], $base_path."/images/avatars/" . $newfilename);
//resize image form
list($width, $height) = getimagesize($base_path."/images/avatars/" . $newfilename);
$scale_height = $height/$width;
$scale_width = $width/$height;
//Find height and width of the image
if($width > $height && $width > 150){
$width_new = 150;
$height_new = round($width_new*$scale_height);
}else if($height > $width && $height > 150){
$height_new = 150;
$width_new = round($height_new*$scale_width);
}else{
$height_new = $height;
$width_new = $width;
}
switch($file_ext) {
case ".jpg" :
case ".jpeg":
$source = imagecreatefromjpeg($base_path."/images/avatars/" . $newfilename);
break;
case ".png" :
$source = imagecreatefrompng($base_path."/images/avatars/" . $newfilename);
break;
default:
$source = imagecreatefromgif($base_path."/images/avatars/" . $newfilename);
break;
}
$destination = imagecreatetruecolor($width_new, $height_new);
imagesavealpha($destination, true);
imagealphablending($destination, true);
imagecopyresized($destination, $source, 0, 0, 0, 0, $width_new, $height_new, $width, $height);
switch($file_ext) {
case ".jpg":
case ".jpeg":
imagejpeg($destination, $base_path."/images/avatars/" . $newfilename, 85);
break;
case ".png":
imagepng($destination, $base_path."/images/avatars/" . $newfilename, 8);
break;
default:
imagegif($destination, $base_path."/images/avatars/" . $newfilename, 85);
break;
}
return $newfilename;
}else{
$this->upload_avatar = '<br />But the avatar was not updated. The avatar\'s size exceeded the 150kb limit. ';
return '';
}
}else{
$this->upload_avatar = '<br />But the avatar was not updated. The avatar must be one of the following formats: jpg, jpeg, png or gif. ';
return '';
}
}else{
return '';
}
}
Any help would be appreciated as I am going nuts looking at this now.
Thanks!
This here may be what you're looking for. The second comment contains an example of resizing pngs and gifs while preserving transparency.
p.s. I'd have added this as a comment but I don't have the rights to do that yet.