Limiting the checking condition while uploading SWF files - php

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::";
}
}
?>

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.

Multiple file upload in laravel 4

I need to upload multiple files in laravel 4
I have written the following code in controller
public function post_files()
{
$allowedExts = array("gif", "jpeg", "jpg", "png","txt","pdf","doc","rtf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$filename= $temp[0];
$destinationPath = 'upload/'.$filename.'.'.$extension;
if(in_array($extension, $allowedExts)&&($_FILES["file"]["size"] < 20000000))
{
if($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
$uploadSuccess=move_uploaded_file($_FILES["file"]["tmp_name"],$destinationPath);
if( $uploadSuccess )
{
$document_details=Response::json(Author::insert_document_details_Call($filename,$destinationPath));
return $document_details; // or do a redirect with some message that file was uploaded
}
else
{
return Response::json('error', 400);
}
}
}
}
else
{
return "Invalid file";
}
}
}
I am able to upload a single file via this code but not able to upload multiple files.
Please help me in this isue..Thank you in advance..
public function post_abc()
{
// $file = Input::file('file'); // your file upload input field in the form should be named 'file'
$allowedExts = array("gif", "jpeg", "jpg", "png","txt","pdf","doc","rtf","docx","xls","xlsx");
foreach($_FILES['file'] as $key => $abc)
{
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$filename= $temp[0];
$destinationPath = 'abc/'.$filename.'.'.$extension;
if(in_array($extension, $allowedExts)&&($_FILES["file"]["size"] < 20000000))
{
if($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
if (file_exists($destinationPath))
{
echo $filename." already exists. ";
}
else
{
$uploadSuccess=move_uploaded_file($_FILES["file"]["tmp_name"],$destinationPath);
if( $uploadSuccess )
{
return "hello";
}
else
{
return Response::json('error', 400);
}
}
}
}
}
Using postman rest client on google chrome I have passed key as 'file' and value as '3 files selected' and input type is file
Call This part into a loop
if(in_array($extension, $allowedExts)&&($_FILES["file"]["size"] < 20000000))
{
if($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
$uploadSuccess=move_uploaded_file($_FILES["file"]["tmp_name"],$destinationPath);
if( $uploadSuccess )
{
$document_details=Response::json(Author::insert_document_details_Call($filename,$destinationPath));
return $document_details; // or do a redirect with some message that file was uploaded
}
else
{
return Response::json('error', 400);
}
}
}
}
else
{
return "Invalid file";
}
Issue solved. I changed the code as follows in the controller:
public function post_multiple()
{
// $file = Input::file('file'); // your file upload input field in the form should be named 'file'
$allowedExts = array("gif", "jpeg", "jpg", "png","txt","pdf","doc","rtf","docx","xls","xlsx");
if(isset($_FILES['image']['tmp_name']))
{
$i=0;
foreach(Input::file('image') as $key => $file)
{
$temp = explode(".", $_FILES["image"]["name"][$i]);
$extension = end($temp);
$filename= $temp[0];
$destinationPath = 'abc/'.$filename.'.'.$extension;
if(in_array($extension, $allowedExts)&&($_FILES["image"]["size"][$i] < 20000000))
{
if($_FILES["image"]["error"][$i] > 0)
{
echo "Return Code: " . $_FILES["image"]["error"][$i] . "<br>";
}
if (file_exists($destinationPath))
{
echo $filename." already exists. ";
}
else
{
$uploadSuccess=move_uploaded_file($_FILES["image"]["tmp_name"][$i],$destinationPath);
if( $uploadSuccess )
{
$name=$filename.".".$extension;
$document_details=Response::json(Author::insert_document_details_Call($name,$destinationPath));
echo "Update";
}
else
{
return Response::json('error', 400);
}
}
}
$i++;
}
}
}
And in View part I had written name=image instead of image[]

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
}

error in php file upload

I have been over and over this but I can not find why it is giving this error. Parse error: syntax error, unexpected $end in /home/valerie2/public_html/elinkswap/snorris/file.php on line 78. Maybe if there was more eyes on it maybe be able to find where I didnt do something right. Thanks for looking.
<?php
session_start();
include "connect.php";
if ($_POST["submit"])
{
//Coding
if($_SESSION["name"])
{
//variables
$name = $_FILES["file"]["name"];
$type = $_FILES["file"]["type"];
$size = $_FILES["file"]["size"];
$tmp_name = $_FILES["file"]["tmp_name"];
$error = $_FILES["file"]["error"];
if ($type =="image/jpeg" || $type =="image/gif")
{
if ($size >1100000 && $size <1700000)
{
if($error > 0)
{
echo "Error!!!!!!".$error;
}
else
{
if(file_exists("upload/".$name))
{
echo $name." already exists.";
}
else
{
$location ="upload/".$name;
move_uploaded_file($tmp_name,$location);
$user = $_SESSION["name"];
$sqlcode = mysql_query("INSERT INTO imageupload (id,user,location) VALUES ('','$user','$location')");
echo "<a href='$location'>Click here to view your image.</a>";
}
}
}
else
{
echo "Please check the size of your File..";
}
}
else
{
echo "Invalid file format.";
}
?>
Line 78 is just before the ?>
It is difficult to follow with so many nested IF staements, but it looks like you have failed to close 2 IFs (if submit and if name)
Change you code to:
<?php
session_start();
include "connect.php";
if ( $_POST[ "submit" ] ) {
if ( $_SESSION[ "name" ] ) {
$name = $_FILES[ "file" ][ "name" ];
$type = $_FILES[ "file" ][ "type" ];
$size = $_FILES[ "file" ][ "size" ];
$tmp_name = $_FILES[ "file" ][ "tmp_name" ];
$error = $_FILES[ "file" ][ "error" ];
if ( $type == "image/jpeg" || $type == "image/gif" ) {
if ( $size > 1100000 && $size < 1700000 ) {
if ( $error > 0 ) {
echo "Error!!!!!!" . $error;
} else {
if ( file_exists( "upload/" . $name ) ) {
echo $name . " already exists.";
}
}
} else {
$location = "upload/" . $name;
move_uploaded_file( $tmp_name , $location );
$user = $_SESSION[ "name" ];
$sqlcode = mysql_query( "INSERT INTO imageupload (id,user,location) VALUES ('','$user','$location')" );
echo "<a href='$location'>Click here to view your image.</a>";
}
}
} else {
echo "Please check the size of your File..";
}
} else {
echo "Invalid file format.";
}
?>
And please use the practice to indent your code, it will be a quick and easy way to correct these errors.
Change this:
if ($size >1100000 && $size <1700000)
{
if($error > 0)
{
echo "Error!!!!!!".$error;
}
to....
if ($size >1100000 && $size <1700000)
{
if($error > 0)
{
echo "Error!!!!!!".$error;
}
}

Attempt at running a condition based on file type using strpos

I am in the process of creating a condition. The condition is to check if any of the files are not basic image files (png, jpg, etc -- files shown in the condition) right away (in the if). If this is the case then the file_put_contents should run. If there are only basic image files being uploaded then the else should run.
As of now, the else never runs. For example, if I upload one file that is a .png the else statement should run.
When someone adds a file, I check the file type with $uploadedFileTypes = $fu->getImageFileTypes(); and then implode it to a list. This 100% works.
Here is an example of what I am wanting to happen:
If someone uploads two files - a .png and .stp, then the if should run. I am wanting the else to run only if the files being uploaded are the basic image files. Is there a better way to do this?
Then I am using the strpos function to check each type of image file I specified.
if (strpos($fileTypeString,$pdf) || strpos($fileTypeString,$jpg) || strpos($fileTypeString,$jpeg) || strpos($fileTypeString,$png) || strpos($fileTypeString,$gif) === false) {
Does anyone see what I am doing wrong?
$date = new DateTime();
$fu = new fileUpload();
$filename = $fu->upload();
$uploadedFileTypes = $fu->getImageFileTypes();
$fileTypeString = implode( ", ", $uploadedFileTypes );
$pdf = "pdf";
$jpg = "jpg";
$jpeg = "jpeg";
$png = "png";
$gif = "gif";
file_put_contents('file_type_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r($uploadedFileTypes, true), FILE_APPEND);
foreach ($_FILES as $file) {
foreach($file['name'] as $key => $value) {
if (!empty($value)) { //empty string
if ($file['error'][$key] != 4) {
if (strpos($fileTypeString,$pdf) || strpos($fileTypeString,$jpg) || strpos($fileTypeString,$jpeg) || strpos($fileTypeString,$png) || strpos($fileTypeString,$gif) === false) {
file_put_contents('file_norm_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r('There were other types of files uploaded', true), FILE_APPEND);
} else {
$out = (count($filename) > 1 ? 'Multiple files were' : 'A file was'). ' uploaded. You can download ' . (count($filename) > 1 ? 'them' : 'the file'). ' from:</ul>';
foreach ($filename as $indFile) {
//print_r($template);
$out .= "<li><a href='/php/uploads/{$indFile}'>{$indFile}</a></li>";
}
$out .= '</ul>';
$template = str_replace("{filename}", $out, $template);
}
} else { //error code IS #4
//echo "error code is 4";
}
} else {
//echo "name is empty!";
$template = str_replace("{filename}", '', $template);
}
}
}
Edit, New code with different approach:
$date = new DateTime();
$fu = new fileUpload();
$filename = $fu->upload();
$uploadedFileTypes = $fu->getImageFileTypes();
$fileTypeString = implode( ", ", $uploadedFileTypes);
$imageTypes = ["pdf","jpg", "jpeg", "png", "gif"];
$nonImgFiles = false;
$imgFiles = false;
if (!in_array($uploadedFileTypes, $imageTypes)) {
$nonImgFiles = true;
}
if (in_array($uploadedFileTypes, $imageTypes)) {
$imgFiles = true;
}
foreach ($_FILES as $file) {
foreach($file['name'] as $key => $value) {
if (!empty($value)) { //empty string
if ($file['error'][$key] != 4) {
if ($nonImgFiles == true) {
file_put_contents('file_norm_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r('There were other types of files uploaded', true), FILE_APPEND);
} else {
}
You have to add === false to all the conditionals and change the operator to &&, like:
if (
strpos($fileTypeString,$pdf) === false &&
strpos($fileTypeString,$jpg) === false &&
strpos($fileTypeString,$jpeg) === false &&
strpos($fileTypeString,$png) === false &&
strpos($fileTypeString,$gif) === false
) {
//do something
} else {
//do something
}
But it seems that you can achieve that using less code in that if doing:
$date = new DateTime();
$fu = new fileUpload();
$filename = $fu->upload();
file_put_contents('file_type_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r($uploadedFileTypes, true), FILE_APPEND);
$extensions = ['pdf', 'jpg', 'jpeg', 'png', 'gif']; //an array with your extensions
foreach ($_FILES as $file) {
foreach($file['name'] as $key => $value) {
if (!empty($value)) { //empty string
if ($file['error'][$key] != 4) {
$fileData = pathinfo($file['name']); //explod file path to array
if (!in_array($fileData['extension'], $extensions)) { //if file extension not in your $extensions array
file_put_contents('file_norm_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r('There were other types of files uploaded', true), FILE_APPEND);
} else {
$out = (count($filename) > 1 ? 'Multiple files were' : 'A file was'). ' uploaded. You can download ' . (count($filename) > 1 ? 'them' : 'the file'). ' from:</ul>';
foreach ($filename as $indFile) {
//print_r($template);
$out .= "<li><a href='/php/uploads/{$indFile}'>{$indFile}</a></li>";
}
$out .= '</ul>';
$template = str_replace("{filename}", $out, $template);
}
} else { //error code IS #4
//echo "error code is 4";
}
} else {
//echo "name is empty!";
$template = str_replace("{filename}", '', $template);
}
}
}
EDIT:
I reread your question. I believe you will need to remove the file extension checking outside the loop. Something like this would work:
$date = new DateTime();
$fu = new fileUpload();
$filename = $fu->upload();
$uploadedFileTypes = $fu->getImageFileTypes();
file_put_contents('file_type_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r($uploadedFileTypes, true), FILE_APPEND);
//your per-file validation loop can go here
$extensions = 'pdf', 'jpg', 'jpeg', 'png', 'gif'];
//fill $differentExtensions with all $uploadedFileTypes elements that
//does not exist inside $extensions
$differentExtensions = array_diff($uploadedFileTypes, $extensions);
if (count($differentExtensions) > 0) {
file_put_contents('file_norm_log', "\n[{$date->format('Y-m-d H:i:s')}]" . print_r('There were other types of files uploaded', true), FILE_APPEND);
} else {
$out = (count($filename) > 1 ? 'Multiple files were' : 'A file was'). ' uploaded. You can download ' . (count($filename) > 1 ? 'them' : 'the file'). ' from:</ul>';
foreach ($filename as $indFile) {
//print_r($template);
$out .= "<li><a href='/php/uploads/{$indFile}'>{$indFile}</a></li>";
}
$out .= '</ul>';
$template = str_replace("{filename}", $out, $template);
}
//your per-file validation loop can go here
The loop you are using to validate errors would be a separate code block. You could place it before or after the file extension checking, depending on what you need (I mentioned suggested places as comments in the code above):
foreach ($_FILES as $file) {
foreach($file['name'] as $key => $value) {
if (empty($value)) {
//echo "name is empty!";
$template = str_replace("{filename}", '', $template);
}
if ($file['error'][$key] == 4) {
//echo "error code is 4";
}
}
}
May I suggest an alternative way of checking the file types, rather than mangling strings and checking different variables, have an array of the types you want to capture and then check if the ones uploaded match any of them (using array_intersect() in this example)...
$uploadedFileTypes = $fu->getImageFileTypes();
$imagesTypes = ["pdf","jpg", "jpeg", "png", "gif"];
would give you the arrays to compare
Then your test would be something like...
if ( empty(array_intersect($uploadedFileTypes, $imagesTypes)) ) {
If you want to ensure what types are loaded, you can change this round so that you start with...
$imagesTypes = ["png","stp"];
and then the check would be if there are any differences between the types and the extensions you are expecting...
if ( !empty(array_diff($uploadedFileTypes, $imagesTypes)) ) {

Categories