Reusing code (function?) in PHP - php

Got this bit of code:
if ($_FILES["file1"]["error"] == 0) {
move_uploaded_file($_FILES["file1"]["tmp_name"], "path/".$_FILES["file1"]["name"]);
}
I would like to reuse it for more files being uploaded. Was thinking function with some params but it seems i can't get the vars correctly.
Ok fixed it like this:
function upload($file) {
$allowedExts = array("pdf, jpg, gif, png");
$extension = end(explode(".", $_FILES[$file]["name"]));
if (in_array($extension, $allowedExts)) && ($_FILES[$file]["error"] == 0) {
move_uploaded_file($_FILES[$file]["tmp_name"], "img/new/".$_FILES[$file]["name"]);
}
}
And calling via:
upload("file1");
Not sure about the $_FILES loop...

You can loop through the $_FILES array and execute your code for each file, like this:
foreach($_FILES as $file)
{
if ($file["error"] == 0) {
move_uploaded_file($file["tmp_name"], "path/".$file["name"]);
}
}

You could do this
function upload_file($file, $upload_path)
{
if($file["error"] == 0){
$moved = move_uploaded_file($file["tmp_name"], $upload_path.$file["name"]);
if($moved){
return true;
}
}
return false;
}
simple but works for your needs.

Documentation: PHP File Uploads
This works:
<?php
if(isset($_FILES['file']['tmp_name']))
{
$num_files = count($_FILES['file']['tmp_name']);
for($i=0; $i < $num_files;$i++)
{
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
else
{
if(move_uploaded_file(($_FILES['file']['tmp_name'][$i],$upload_dir.'/'.$_FILES['file']['name'][$i]))
{
$messages[] = $_FILES['file']['name'][$i].' uploaded';
}
else
{
$messages[] = 'Uploading '.$_FILES['file']['name'][$i].' Failed';
}
}
}
}
?>
Note: It's a good idea to validate the files using exif_imagetype(), getimagesize() and similar.. Every other value than $_FILES['image']['tmp_name'] and $_FILES['image']['error'] shouldn't be trusted. It takes whatever is sent from the browser and can easily be faked.

Related

Why doesn't my file upload function work properly? PHP

Hi I have a file upload function. Controls file size and file type. If the file is in PDF format and is smaller than 10MB, everything works as it should.
If the file is not PDF, it should show me the message: "ERROR: You can just upload PDF files." but no message.
If the file size is larger than 10MB, it should show me the message: "ERROR: Max file size 10MB." but no message.
If the file is PDF but larger than 10MB, it shows me: "ERROR: All fields must be filled."
What is wrong with my code?
Function :
<?php
function file_create($file) {
if(isset($file)){
$errors = array();
$target_dir = "../files/";
$file_name = uniqid();
$file_size = $file['size'];
$file_tmp = $file['tmp_name'];
$file_type = $file['type'];
$file_ext = strtolower(end(explode('.',$file['name'])));
if($file_type != "application/pdf") {
$error = "ERROR : You can upload just PDF files.";
array_push($errors, $error);
}
if($file_size > 1024*1024*10) {
$error = "ERROR : Max file size 10MB.";
array_push($errors, $error);
}
if(empty($errors) == true) {
move_uploaded_file($file_tmp,$target_dir.$file_name.".".$file_ext);
$errors['status'] = true;
$errors['patch'] = substr($target_dir.$file_name.".".$file_ext, 3);
} else {
$errors['status'] = false;
}
return $errors;
}
}
?>
Another File :
<?php
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$notice_title = secured_post("notice-title");
$notice_content = secured_post("notice-content");
// if there is empty field in form.
if (multi_empty($notice_title, $notice_content)) {
// if a file submitted.
if (isset($_FILES['notice-file'])) {
$notice_file = $_FILES['notice-file'];
// upload the file.
$upload = file_create($notice_file);
if ($upload['status'] == false) {
$size = count($upload);
for ($i=0; $i < $size; $i++) {
array_push($errors, $upload[$i]);
}
}
notice_create($conn, $notice_title, $notice_content, $upload['patch']);
} else {
notice_create($conn, $notice_title, $notice_content);
}
} else {
$error = "ERROR : All fields must be filled.";
array_push($errors, $error);
}
}
if ($errors) {
foreach ($errors as $error) {
echo "<div class='error'>".$error."</div></br>";
}
}
?>
Here's the problem. If your file is larger than 10MB then it can take some time to upload the file so you have to check if the $_FILES array is empty or not.
Try this:
<?php
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_FILES)) { //I've made changes to this line
$notice_title = secured_post("notice-title");
$notice_content = secured_post("notice-content");
// if there is empty field in form.
if (multi_empty($notice_title, $notice_content)) {
// if a file submitted.
if (isset($_FILES['notice-file'])) {
$notice_file = $_FILES['notice-file'];
// upload the file.
$upload = file_create($notice_file);
if ($upload['status'] == false) {
$size = count($upload);
for ($i=0; $i < $size; $i++) {
array_push($errors, $upload[$i]);
}
}
notice_create($conn, $notice_title, $notice_content, $upload['patch']);
} else {
notice_create($conn, $notice_title, $notice_content);
}
} else {
$error = "ERROR : All fields must be filled.";
array_push($errors, $error);
}
}
if ($errors) {
foreach ($errors as $error) {
echo "<div class='error'>".$error."</div></br>";
}
}
?>
And:
<?php
function file_create($file) {
if(!empty($file)){ //I've made changes to this line
$errors = array();
$target_dir = "../files/";
$file_name = uniqid();
$file_size = $file['size'];
$file_tmp = $file['tmp_name'];
$file_type = $file['type'];
$file_ext = strtolower(end(explode('.',$file['name'])));
if($file_type != "application/pdf" || $file_ext != ".pdf") { //I've made changes to this line
$error = "ERROR : You can upload just PDF files.";
array_push($errors, $error);
}
if($file_size > (1024*1024*10)) {
$error = "ERROR : Max file size 10MB.";
array_push($errors, $error);
}
if(empty($errors) == true) {
move_uploaded_file($file_tmp,$target_dir.$file_name.".".$file_ext);
$errors['status'] = true;
$errors['patch'] = substr($target_dir.$file_name.".".$file_ext, 3);
} else {
$errors['status'] = false;
}
return $errors;
}
}
?>
Note: The $_FILES array can be set and empty at the same time so isset() can't help you here.

PrestaShop: allow customers to upload PDF, AI and EPS files as product customization

I am running Prestashop 1.6.1.7 and I have the following pictureUpload() method that allows users to upload files of their choosing. By default Prestashop allows uploads of GIF, JPG, JPEG or PNG only.
I'm trying to allow users the ability to upload a few more types (pdf, ai and eps specifically)
Here is the pictureUpload() method in the productController override:
protected function pictureUpload()
{
if (!$field_ids = $this->product->getCustomizationFieldIds()) {
return false;
}
$authorized_file_fields = array();
foreach ($field_ids as $field_id) {
if ($field_id['type'] == Product::CUSTOMIZE_FILE) {
$authorized_file_fields[(int)$field_id['id_customization_field']] = 'file'.(int)$field_id['id_customization_field'];
}
}
$indexes = array_flip($authorized_file_fields);
foreach ($_FILES as $field_name => $file) {
if (in_array($field_name, $authorized_file_fields) && isset($file['tmp_name']) && !empty($file['tmp_name'])) {
//$file_name = md5(uniqid(rand(), true));
$file_name = $file['name']; // In this
if ($error = ImageManager::validateUpload($file, (int)Configuration::get('PS_PRODUCT_PICTURE_MAX_SIZE'))) {
$this->errors[] = $error;
}
$product_picture_width = (int)Configuration::get('PS_PRODUCT_PICTURE_WIDTH');
$product_picture_height = (int)Configuration::get('PS_PRODUCT_PICTURE_HEIGHT');
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if ($error || (!$tmp_name || !move_uploaded_file($file['tmp_name'], $tmp_name))) {
return false;
}
/* Original file */
if (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
}
/* A smaller one */
elseif (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name.'_small', $product_picture_width, $product_picture_height)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
} elseif (!chmod(_PS_UPLOAD_DIR_.$file_name, 0777) || !chmod(_PS_UPLOAD_DIR_.$file_name.'_small', 0777)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
} else {
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
}
unlink($tmp_name);
}
}
return true;
}
This is looking to the ImageManager class, which has this method (that I have updated the error message on):
public static function validateUpload($file, $max_file_size = 0, $types = null)
{
if ((int)$max_file_size > 0 && $file['size'] > (int)$max_file_size) {
return sprintf(Tools::displayError('Image is too large (%1$d kB). Maximum allowed: %2$d kB'), $file['size'] / 1024, $max_file_size / 1024);
}
if (!ImageManager::isRealImage($file['tmp_name'], $file['type']) || !ImageManager::isCorrectImageFileExt($file['name'], $types) || preg_match('/\%00/', $file['name'])) {
return Tools::displayError('Image format not recognized, allowed formats are: .gif, .jpg, .png, .pdf, .ai, .eps'); //I Updated This - this is the error kicking off when I try to upload AI
}
if ($file['error']) {
return sprintf(Tools::displayError('Error while uploading image; please change your server\'s settings. (Error code: %s)'), $file['error']);
}
return false;
}
The place where that method fails is pointing to two additional methods posted below. I updated the isRealImage method to try and allow the types I wanted through, but it still fails (and I commented where it fails).
public static function isRealImage($filename, $file_mime_type = null, $mime_type_list = null)
{
// Detect mime content type
$mime_type = false;
if (!$mime_type_list) {
//I UPDATED THIS LIST TO ALLOW FOR OTHER FILETYPES
$mime_type_list = array('image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png', 'application/illustrator', 'application/ai', 'application/eps', 'application/x-eps', 'image/eps', 'image/x-eps', 'application/pdf', 'application/acrobat', 'application/x-pdf', 'text/pdf', 'text/x-pdf');
}
// Try 4 different methods to determine the mime type
if (function_exists('getimagesize')) {
$image_info = #getimagesize($filename);
//HERE IMAGE_INFO IS SHOWING AS 'FALSE' SO IT GOES NO FURTHER WHEN UPLOADING A .AI FILE
if ($image_info) {
$mime_type = $image_info['mime'];
} else {
$file_mime_type = false;
}
} elseif (function_exists('finfo_open')) {
$const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
$finfo = finfo_open($const);
$mime_type = finfo_file($finfo, $filename);
finfo_close($finfo);
} elseif (function_exists('mime_content_type')) {
$mime_type = mime_content_type($filename);
} elseif (function_exists('exec')) {
$mime_type = trim(exec('file -b --mime-type '.escapeshellarg($filename)));
if (!$mime_type) {
$mime_type = trim(exec('file --mime '.escapeshellarg($filename)));
}
if (!$mime_type) {
$mime_type = trim(exec('file -bi '.escapeshellarg($filename)));
}
}
if ($file_mime_type && (empty($mime_type) || $mime_type == 'regular file' || $mime_type == 'text/plain')) {
$mime_type = $file_mime_type;
}
// For each allowed MIME type, we are looking for it inside the current MIME type
foreach ($mime_type_list as $type) {
if (strstr($mime_type, $type)) {
return true;
}
}
return false;
}
I also updated the isCorrectImageFileExt method:
public static function isCorrectImageFileExt($filename, $authorized_extensions = null)
{
// Filter on file extension
if ($authorized_extensions === null) {
//ADDED ALLOWED TYPES I WANT
$authorized_extensions = array('gif', 'jpg', 'jpeg', 'jpe', 'png', 'pdf', 'ai', 'eps');
}
$name_explode = explode('.', $filename);
if (count($name_explode) >= 2) {
$current_extension = strtolower($name_explode[count($name_explode) - 1]);
if (!in_array($current_extension, $authorized_extensions)) {
return false;
}
} else {
return false;
}
return true;
}
Thoughts on this?
Help on this?
You have gone too deep :). This is the pictureUpload method of ProductController that I've already made, you don't need others overrides. With my override you can upload pdf, ai, cdr and eps, but obviously you can change with your needs.
protected function pictureUpload()
{
if (!$field_ids = $this->product->getCustomizationFieldIds()) {
return false;
}
$authorized_file_fields = array();
foreach ($field_ids as $field_id) {
if ($field_id['type'] == Product::CUSTOMIZE_FILE) {
$authorized_file_fields[(int)$field_id['id_customization_field']] = 'file'.(int)$field_id['id_customization_field'];
}
}
$indexes = array_flip($authorized_file_fields);
foreach ($_FILES as $field_name => $file) {
if (in_array($field_name, $authorized_file_fields) && isset($file['tmp_name']) && !empty($file['tmp_name'])) {
$file_name = md5(uniqid(rand(), true));
// Bad check, but rapid
$extension = substr($file['name'], -3, 3);
if($extension == 'jpg' OR $extension == 'gif' OR $extension == 'png'){
if ($error = ImageManager::validateUpload($file, (int)Configuration::get('PS_PRODUCT_PICTURE_MAX_SIZE'))) {
$this->errors[] = $error;
}
$product_picture_width = (int)Configuration::get('PS_PRODUCT_PICTURE_WIDTH');
$product_picture_height = (int)Configuration::get('PS_PRODUCT_PICTURE_HEIGHT');
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if ($error || (!$tmp_name || !move_uploaded_file($file['tmp_name'], $tmp_name))) {
return false;
}
/* Original file */
if (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
}
/* A smaller one */
elseif (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name.'_small', $product_picture_width, $product_picture_height)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
} elseif (!chmod(_PS_UPLOAD_DIR_.$file_name, 0777) || !chmod(_PS_UPLOAD_DIR_.$file_name.'_small', 0777)) {
$this->errors[] = Tools::displayError('An error occurred during the image upload process.');
} else {
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
}
unlink($tmp_name);
} elseif ($extension == 'pdf' OR $extension == '.ai' OR $extension == 'cdr' OR $extension == 'eps') {
$file_name = $file_name.'.'.str_replace('.', '', $extension);
if (!move_uploaded_file($file['tmp_name'], _PS_UPLOAD_DIR_.$file_name)) {
return false;
}
chmod(_PS_UPLOAD_DIR_.$file_name, 0777);
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
} else {
$this->errors[] = Tools::displayError('This format is not accepted');
}
}
}
return true;
}
After that you have to customize product.tpl, the cart summary of your template, and the backoffice order detail :)
Another solution if you do not want to hack your PrestaShop installation, which is not recommended if you want to be able to upgrade PretaShop safely, is to develop or use an existing module.
This module on the PrestaShop marketplace is probably what you are looking for:
https://addons.prestashop.com/en/front-office-features-prestashop-modules/88383-upload-any-file-type-in-product-customization.html

Compress image php with move_uploaded_files

I have a php script which upload a photo from an Ajax call, and i want to upload the photo two times, one with standard size and another one compressed. Does anyone know how to do it with this following code? I tried to compress the image with scripts that I found on stackoverflow, but I can't do it correctly. Everytime appears an black photo.
I got this code:
$data = array();
if (isset($_GET['files'])) {
$error = false;
$files = array();
$uniqid = uniqid();
$uploaddir = '../../images/'.$uniqid;
foreach($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir.basename($file['name']))) {
$files[] = $uploaddir.$file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' = > 'There was an error uploading your files') : array('files' = > $files);
} else {
$arr - > image = $file['name'];
$_SESSION['image'] = "img-".$file['name'];
$arr - > ok = "ok";
$data = array('success' = > 'Form was submitted', 'formData' = > $file['name']);
}
Thank you all!
Try using basename() also in your $files[] array insertion:
Change this:
foreach($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir.basename($file['name']))) {
$files[] = $uploaddir.$file['name'];
} else {
$error = true;
}
}
To this:
foreach($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir.basename($file['name']))) {
$files[] = $uploaddir.basename($file['name']);
} else {
$error = true;
}
}

how can I add imaging handling got this script effectively

hopefully someone can help me here. been up all night browsing and nothing I try seems to work, but im new to php so im slow. I need to upload 6 images, and this works great. but then I realized you can upload not only images but all other file types. Im trying to be able to limit it to just images under 100kb each. heeeeelllllllpppppp!!!! please!
function findexts ($filename) { $filename = strtolower('$filename') ;
$exts = preg_split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['images']['name']) ;
$ran = rand ();
$ran2 = $ran.".";
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
See the answer to both your questions here:
https://stackoverflow.com/a/9153419/723855
Add this function to your script (modified from link):
function acceptFileUpload($thefile){
if(isset($_FILES[$thefile])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES[$thefile]['size'] >= $maxsize) || ($_FILES[$thefile]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES[$thefile]['type'], $acceptable)) && (!empty($_FILES[$thefile]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) !== 0) {
return true;
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
return false;
}
die(); //Ensure no more processing is done
}
}
}
Then in your script change your while loop to use this function to check for a valid file:
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
if(acceptFileUpload('images'))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
}
I might not have that parameter right that is getting passed to acceptFileUpload().
Four functions to run on the processing script on each file, if all tests pass then the file meets your conditions and can be safely stored (png / jpg / gif + non-zero + 10Kb limit + is uploaded file)
//Example Call: checkFileExtension($_FILES['fieldname']['name']);
function checkFileExtension($filename) {
$filename = strtolower($filename) ;
$filenamePartsArray = preg_split("[/\\.]", $filename) ;
$extension = $filenamePartsArray[count($filenamePartsArray) - 1];
if (($extension == 'gif') || ($extension == 'jpeg') || ($extension == 'jpg') || ($extension == 'png')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileMIME($_FILES['fieldname']['type']);
function checkFileMIME($filetype) {
if (($filetype == 'image/png') || ($filetype == 'image/jpeg') || ($filetype == 'image/gif')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileSize($_FILES['fieldname']['size'], 10);
function checkFileSize($filesize, $limitKb = 0) {
if ($filesize == 0) {
return false;
}
if ($limitKb != 0) {
if ($filesize > ($limitKb * 1024)) {
return false;
}
}
return true;
}
//Native Call: is_uploaded_file($_FILES['fieldname']['tmp_name']);
Edit: pseudo example use
foreach ($_FILES as $fieldname => $file) {
if ((checkFileExtension($file['name'])) && (checkFileMIME($file['type'])) && (checkFileSize($file['size'], 10)) && (is_uploaded_file($file['tmp_name']))) {
//Move the image with move_uploaded_file
//Save the file location with DB insert
}
}
you can check the file type with
$_FILES['image']['type']
or if you want to check the extension too
$extension = explode('.',(string)$_FILES['image']['name']);
//then check if its "jpg", "gif" or "png"
the file size can be checked with
$_FILES['image']['size']
so your script should be like this for each of your image updates:
$extension = explode('.',$_FILES['image']['name']);
$imgextensions = array();
$size = $_FILES['image']['size'];
if(($extension == 'jpg' || $extension == 'gif' || $extension == 'png') &&
$size < 100000 ){
// upload your file to your filesystem
}else{
//inform the user
}

Limiting the checking condition while uploading SWF files

I am creating an application of uploading swf files in a folder using PHP.
My script is all working except for the first if condition where I'm checking whether the extension is swf or not, but I seems to have some error.
I'm not sure whether video/swf is a valid checking parameter for SWF files or not. My full script is below. I'm checking the size of the SWF using getimagesize(). Some people may wonder that getimagesize works for image, but I saw some examples where getimagesize() has been used for getting size of SWF files.
It's giving me the message "invalid swf file", that means its not satisfying the first checking condition at all.
<?php
foreach($_FILES['item_swf']['tmp_name'] as $key=>$val)
{
list($width, $height) = getimagesize($_FILES['item_swf']['tmp_name'][$key]);
if (( ($_FILES["item_swf"]["type"][$key] == "video/swf") || ($_FILES["item_swf"]["type"][$key] == "video/SWF") )
&& ($_FILES["item_swf"]["size"][$key] < 800000))
{
if ($_FILES["item_swf"]["error"][$key] > 0)
{
echo "Error: " . $_FILES["item_swf"]["error"][$key] . "<br />";
}
else if($width==1000 && $height==328)
{
if (file_exists('../../swf_folder/header_swf/' . $_FILES["item_swf"]["name"]))
{
echo $_FILES["item_swf"]["name"][$key] . " already exists. ";
}
else
{
move_uploaded_file($val, '../../swf_folder/header_swf/'.$_FILES['item_swf']['name'][$key]);
echo "done";
}
}
else
{
echo "size doest permit";
}
}
else
{
echo "Not a valid swf file::";
}
}
?>
The line given below
move_uploaded_file($val, '../../swf_folder/header_swf/'.$_FILES['item_swf']['name'][$key]);
is working perfectly as it is uploading files to the dedicated folder, it somehow seems that the checking parameters for SWF only files are not set properly.
Edit
I got my answer. Instead of using video/swf I need to use application/x-shockwave-flash.
So the ultimate code will be:
<?php
foreach($_FILES['item_swf']['tmp_name'] as $key=>$val)
{
list($width, $height) = getimagesize($_FILES['item_swf']['tmp_name'][$key]);
if (($_FILES["item_swf"]["type"][$key] == "application/x-shockwave-flash")
&& ($_FILES["item_swf"]["size"][$key] < 800000))
{
if ($_FILES["item_swf"]["error"][$key] > 0)
{
echo "Error: " . $_FILES["item_swf"]["error"][$key] . "<br />";
}
else if($width==1000 && $height==328)
{
if (file_exists('../../swf_folder/header_swf/' . $_FILES["item_swf"]["name"]))
{
echo $_FILES["item_swf"]["name"][$key] . " already exists. ";
}
else
{
move_uploaded_file($val, '../../swf_folder/header_swf/'.$_FILES['item_swf']['name'][$key]);
echo "done";
}
}
else
{
echo "size doest permit";
}
}
else
{
echo "Not a valid swf file::";
}
}
?>
you can try
$savePath = "PATH_TO_SAVE";
$errors = array ();
$output = array ();
//
if (isset ( $_FILES ['item_swf'])) {
foreach ( $_FILES ['item_swf'] ['tmp_name'] as $key => $val ) {
$fileName = $_FILES ['item_swf'] ['name'] [$key];
$fileSize = $_FILES ['item_swf'] ['size'] [$key];
$fileTemp = $_FILES ['item_swf'] ['tmp_name'] [$key];
$fileExtention = pathinfo ( $fileName, PATHINFO_EXTENSION );
$fileExtention = strtolower ( $fileExtention );
if ($fileExtention != ".swf") {
$errors [$fileName] [] = "Invalid File Extention";
continue;
}
if ($fileSize > 800000) {
$errors [$fileName] [] = "File Too large";
continue;
}
list ( $width, $height ) = getimagesize ( $fileTemp );
if ($width != 1000 && $height != 328) {
$errors [$fileName] [] = "Wrong File dimention ";
continue;
}
if (file_exists ( $savePath . DIRECTORY_SEPARATOR . $fileName )) {
$errors [$fileName] [] = "File Exist";
continue;
}
if(!is_writable($savePath ))
{
$errors [$fileName] [] = "File Destination not writeable";
}
if(count($errors [$fileName]) == 0)
{
if(#move_uploaded_file ( $fileTemp, $savePath . DIRECTORY_SEPARATOR . $fileName))
{
$output[$fileName] == "OK" ;
}
else
{
$errors [$fileName] [] = "Error Saving File";
}
}
}
var_dump($errors, $output);
}
Let me know if you have any more challenge
ok, i got my answer....
instead of using video/swf i need to use application/x-shockwave-flash
so the ultimate code will be
<?php
foreach($_FILES['item_swf']['tmp_name'] as $key=>$val)
{
list($width, $height) = getimagesize($_FILES['item_swf']['tmp_name'][$key]);
if (( ($_FILES["item_swf"]["type"][$key] == "application/x-shockwave-flash") || ($_FILES["item_swf"]["type"][$key] == "video/SWF") )
&& ($_FILES["item_swf"]["size"][$key] < 800000))
{
if ($_FILES["item_swf"]["error"][$key] > 0)
{
echo "Error: " . $_FILES["item_swf"]["error"][$key] . "<br />";
}
else if($width==1000 && $height==328)
{
if (file_exists('../../swf_folder/header_swf/' . $_FILES["item_swf"]["name"]))
{
echo $_FILES["item_swf"]["name"][$key] . " already exists. ";
}
else
{
move_uploaded_file($val, '../../swf_folder/header_swf/'.$_FILES['item_swf']['name'][$key]);
echo "done";
}
}
else
{
echo "size doest permit";
}
}
else
{
echo "Not a valid swf file::";
}
}
?>

Categories