Dynamic Folders in Uploadfive with CodeIgniter - php

I started using uploadifive for file uploads. I am trying to create a dynamic folder into which the uploaded files will be saved. The folder is being created. but i cant upload the files into that folder.
This the view page:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>UploadiFive Test</title>
<script src="<?=base_url()?>application/views/Sample/jquery.min.js" type="text/javascript"></script>
<script src="<?=base_url()?>application/views/Sample/jquery.uploadifive.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="<?=base_url()?>application/views/Sample/uploadifive.css">
<style type="text/css">
body {
font: 13px Arial, Helvetica, Sans-serif;
}
.uploadifive-button {
float: left;
margin-right: 10px;
}
#queue {
border: 1px solid #E5E5E5;
height: 177px;
overflow: auto;
margin-bottom: 10px;
padding: 0 3px 3px;
width: 300px;
}
</style>
</head>
<body>
<h1>UploadiFive Demo</h1>
<form>
<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file" multiple="true">
<a style="position: relative; top: 8px;" href="javascript:$('#file_upload').uploadifive('upload')">Upload Files</a>
</form>
<?php
$query = $this->db->get('filename');
$folder_name = underscore($query->row()->file_name);
//$config['upload_path'] = "./uploads/$folder_name/";
if(!is_dir("uploads/$folder_name"))
{
mkdir("uploads/$folder_name",0777);
}
echo $folder_name;
?>
<script type="text/javascript">
<?php $timestamp = time();?>
$(function() {
$('#file_upload').uploadifive({
'auto' : false,
'checkScript' : '<?=base_url()?>check-exists.php',
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5('unique_salt' . $timestamp);?>'
},
'queueID' : 'queue',
'uploadScript' : '<?=base_url()?>application/views/Sample/uploadifive.php',
'onUploadComplete' : function(file, data) { console.log(data); }
});
});
</script>
</body>
</html>
In the code above i get the folder name from database and create a folder with 777 permissions.
And this is the uploadifive.php file:
<?php
// Set the uplaod directory
//Here i get the folder name
$query = $this->db->get('filename');
$folder_name = underscore($query->row()->file_name);
// Set the allowed file extensions
$fileTypes = array('jpg', 'jpeg', 'gif', 'png'); // Allowed file extensions
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$uploadDir = "/Applications/MAMP/htdocs/0.9.1/uploads/$folder_name/";
$targetFile = $uploadDir . $_FILES['Filedata']['name'];
// Validate the filetype
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array(strtolower($fileParts['extension']), $fileTypes)) {
// Save the file
move_uploaded_file($tempFile, $targetFile);
echo 1;
} else {
// The file type wasn't allowed
echo 'Invalid file type.';
}
}
?>
Here i get the file name from the database and use that as a dynamic folder.
When ever i include the code to get the file name from the database, it throws an error 500.
I'm not sure how to deal with this.
Any ideas?
Thanks for your help.
TL;DR : I Suck at coding.

Try changing the following:
$uploadDir = "/Applications/MAMP/htdocs/0.9.1/uploads/$folder_name/";
to
$uploadDir = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . $folder_name . "/";

Related

Script doesn't recognized file extension to upload pdf in php

I try to modify the php scrip to allow it to upload pdf instead of image. I've done several modification but none of them are working. I really appreciate if someone can show me how to modify this script to allow uploading the pdf.
I'm very new in php and need more guidance from php experts out there.
Thanks in advance for your kind assistance.
Anyway this is the code:
## Heading ##<html>
<head>
<!-- Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
#uploader {
width: 300px;
height: 200px;
background: rgba(0,0,0,.075) url(../../img/pdf_icon.png) repeat fixed left;
border-radius:8px;
box-shadow: 5px 5px 10px 0px rgba(0,0,0,0.15);
display: block;
padding: 10px;
}
#uploader.highlight {
background:#ff0;
}
#uploader.disabled {
background:#aaa;
}
</style>
<script src="drag-drop-upload-pdf.js"></script>
</head>
<body>
<!-- DROP ZONE -->
<div id="uploader">
Muatnaik fail pdf di sini...
</div>
<!-- STATUS -->
<div id="upstat"></div>
<!-- FALLBACK -->
<form action="upload-pdf.php" method="post" enctype="multipart/form-data">
<br />
<input class="btn btn-primary" type="file" name="file-upload" id="file-upload" accept="pdf/*">
<br />
<br />
<input class="btn btn-primary" type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
## PHP Script ##
<?php
// SOURCE + DESTINATION
$source = $_FILES["file-upload"]["tmp_name"];
$destination = __DIR__.'/../../download/'. $_FILES["file-upload"]["name"];
echo "Uploaded ";
$error = "";
// CHECK IF FILE ALREADY EXIST
if (file_exists($destination)) {
$error = $destination . " already exist.";
}
// ALLOWED FILE EXTENSIONS
if ($error == "") {
$allowed = ["application/pdf", "application/x-pdf", "application/acrobat", "applications/vnd.pdf",
"text/pdf". "text/x-pdf"];
$ext = strtolower(pathinfo($_FILES["file-upload"]["name"], PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
$error = "$ext file type not allowed. File must be uploaded in PDF format. - " . $_FILES["file-
upload"]["name"];
}
}
// LEGIT TEXT FILE CHECK
if ($error == "") {
if (getimagesize($_FILES["file-upload"]["tmp_name"]) == false) {
$error = $_FILES["file-upload"]["name"] . " is not a valid file.";
}
}
// FILE SIZE CHECK
if ($error == "") {
// 1,000,000 = 1MB
if ($_FILES["file-upload"]["size"] > 50000000) {
$error = $_FILES["file-upload"]["name"] . " - file size too big!";
}
}
// ALL CHECKS OK - MOVE FILE
if ($error == "") {
if (!move_uploaded_file($source, $destination)) {
$error = "Error moving $source to $destination";
}
}
// ERROR OCCURED OR OK?
if ($error == "") {
echo $_FILES["file-upload"]["name"] . " Upload DONE.";
} else {
echo $error;
}
?>
Try change this in HTML:
accept="application/pdf"

angularjs file upload on file select with php

I wanted to upload an image after the selection without submit button.
I used danialfarids plugins from GitHub.
I suppose he made the server with C#, which I wanted to change to php. I'm having problems writing the php file handler.
This is my script files.
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadPic = function(file) {
file.upload = Upload.upload({
method:'POST',
url: 'http://localhost/angular/upload.php',
data: {file: file, username: $scope.username}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
}]);
And this is my html file
<form name="myForm" >
<fieldset>
<legend>Upload on file select</legend>
<br>Photo:
<input type="file" ngf-select="uploadPic(picFile)" ng-model="picFile" name="picFile"
accept="image/*" ngf-max-size="2MB" required
ngf-model-invalid="errorFiles">
<img ng-show="myForm.file.$valid" ngf-thumbnail="picFile" class="thumb">
<br>
<button ng-disabled="!myForm.$valid"
ng-click="uploadPic(picFile)">Submit</button>
<div class="con">
<div class="pg" style="width:{{picFile.progress}}%" ></p></div>
</div>
<p ng-bind="picFile.progress + '%'"></p>
<span ng-show="picFile.result">Upload Successful</span>
<span class="err" ng-show="errorMsg">{{errorMsg}}</span>
</fieldset>
</form>
This is the css
<style>
.thumb {
width: 240px;
height: 240px;
float: none;
position: relative;
top: 7px;
}
form .progress {
line-height: 1px;
}
.progress {
display: inline-block;
width: 300px;
}
.con{
width:300px;
}
.pg {
font-size: smaller;
background: #000000;
width:0px;
height:1px;
}
</style>
And this is the rudimentary upload.php (found in localhost/angular/) and I don't think it works.
<?php if ( !empty( $_FILES ) ) {
$tempPath = $_FILES[ 'picFile' ][ 'tmp_name' ];
$uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $_FILES[ 'picFile' ][ 'name' ];
move_uploaded_file( $tempPath, $uploadPath );
$answer = array( 'answer' => 'File transfer completed' );
$json = json_encode( $answer );
echo $json; } else {
echo 'No files'; } ?>
My xampp server is working. And I also included angular files, angularjs, ng-file-upload-shim.min.js and ng-file-upload.min.js from danialfarid.
I Found the answer to this question, the problem was not on the code, the problem happened because I was making XMLHttpRequest to a different domain than I was in. And the easy way to solve this problem is by adding extension to chrome. Cors extension. This solved the problem.

What's wrong in my ajax?

I own a site called flopl.com. It's pretty basic. Upload your files, and get a URL back with a link to the file. But I wasn't the one coding it, and now I can't get help from the person who did anymore. There's something wrong in the code, but I don't know enough to figure out what. So.. Here's the code:
HTML:
<!DOCTYPE html>
<html style="width:100%">
<head>
<title>flopl</title>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8" />
<link rel="shortcut icon" href="http://flopl.com/images/favicon.ico" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:25px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:-1px; left:48%; }
</style>
</head>
<body style="width:100%">
<div style="background-color:#2d2d2d; width: auto; height:150px; padding:-10px; margin-top:-20px;">
</div>
<div style="background-color:#8be1ab; width: auto; height:10px; padding:-10px; margin-top:0px;">
</div>
<center>
<img width="275px" src="images/logo.png" style="position:absolute; margin-top:-145px; margin-left:-145px;" />
</center>
<div style="width:400px; margin:auto; position:relative; margin-top:15%;" >
<center>
<div style="margin-top:90px; margin-left:25px;">
<p style="word-spacing:0.6px; font-family:Helvetica font-weight:light; margin-top:-20px; position:center;">Upload any type of file,</p>
<p style="word-spacing:0.6px; font-family:Helvetica font-weight:light; margin-top:-20px; position:center;">with no compression!</p>
</div>
</center>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajax_image.php'>
<img width="332px" src="images/upload.png" style="position:absolute; top:-120px; left:40px;"/>
<input type="file" name="photoimg" id="photoimg" style="padding: 0; margin: 0; display: none;" />
</form>
<div class="progress" style="display: none;">
<div class="bar"></div >
<div class="percent">0%</div>
</div>
<div id="status"></div>
<center>
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').live('change', function() {
$("#preview").html('');
$("#preview").html('<img width="300" src="images/uploading.png" alt="Laddar upp...."/>');
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
var progress = $('.progress');
$('#imageform').ajaxForm({
target: '#preview',
beforeSend: function() {
status.empty();
progress.show();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
//status.html(xhr.responseText);
}
}).submit();
});
});
</script>
<div id='preview' style="margin-top:40px;">
</div>
</center>
</div>
</div>
<div class="footer" id="footer">
<div id="top">
<img id="copyright" src="images/footer.png" alt="">
<a id="logo" href="http://www.simplyvisual.se" target="_blank">
<img width="150px" src="/images/SV.png" alt="Simply Visual">
</a>
</div>
<!--<div class="footer" id="footer"><img style="margin-top:1%; margin-left:0%" width="150" src="images/SV.png" /><img style="margin-top:0%;" src="images/footer.png" />--></div>
</body>
</html>
And the PHP:
<?php
session_start();
$session_id='1'; // User session id
$path = "upload/";
function url($url) {
$url = preg_replace('~[^\\pL0-9_]+~u', '-', $url);
$url = trim($url, "-");
$url = iconv("utf-8", "us-ascii//TRANSLIT", $url);
$url = strtolower($url);
$url = preg_replace('~[^-a-z0-9_]+~', '', $url);
return $url;
}
if(!empty($_POST) && !empty($_FILES['photoimg']) && $_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
$pi = pathinfo($name);
$txt = $pi['filename'];
$ext = $pi['extension'];
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
echo "Here's the link to your file: <a href='http://flopl.com/".$path.$actual_image_name."'>http://flopl.com/".$path.$actual_image_name."</a>";
}
} else {
echo "Something went wrong.";
exit;
}
?>
The progress-bar is showing, but I only get "Something went wrong" back. I've checked, the PHP.ini is set up correctly. The files are not uploading, and therefor also not giving me a URL back.
Could anyone figure out what's wrong?
Best regards,
primarypanda
I found at least 2 problems with your project.
Your host may allow upload big files but you need to check that file uploads are set or not in PHP.ini file. in most of the CPanels, they allow to make custom php.ini file settings, here you need to set max_file_uploads = 20M or so.
using isset() function may cause some problem, I use !empty() function instead because it checks whether the variable is set and not empty both. so you can do it in your code like...
if(!empty($_POST) && !empty($_FILES['photoimg']) && $_SERVER['REQUEST_METHOD'] == 'POST'){...}
You can notice that I have also checked that $_FILES['photoimg'] are also not empty, that means that the file is actually uploaded.
Best luck and Thank you

How to add delete in php script in my photo gallery

I made a Photo gallery by php.
I am able to make upload image and show the image list. But i want to add a delete button where users can delete there unwanted image. But i was failed to add this button work.
Someone please help to fix it?
Here is my code on GitHub: https://github.com/sagar290/photo_gallerey/blob/6cad3743e735ea109723de7e14d5477bff1e964b/gallery.php
<?php
if (isset($_FILES["file"]["name"])) {
$name = $_FILES['file']['name'];
//$size = $_FILES['file']['size'];
//$extention = $type;
$type = strtolower($_FILES['file']['type']);
$tmp_name = $_FILES['file']['tmp_name'];
if (isset($name)) {
if (!empty($name)) {
if (($type=='image/jpg')||($type=='image/jpeg')||($type=='image/gif')) {
$location = 'photos/';
if(move_uploaded_file($tmp_name, 'photos/'.$name)) {
echo $name.' is uploaded';
}
}else {
echo 'file must be jpg or jpeg ';
}
}else {
echo 'please choose a file';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Photo gallery</title>
<style type="text/css">
ul {
list-style-type: none;
}
li {
float: left;
padding: 10px;
margin: 10px;
font: bold 10px Verdana, sans-serif;
}
img {
display: block;
border: 1px solid #333300;
margin-bottom: 5px;
}
</style>
</head>
<body>
<h2>Photo gallery</h2>
<form action="gallery.php" method="POST" enctype="multipart/form-data">
UPLOAD:
<input type="file" name="file"><br><br>
<input type="submit" value="submit">
</form>
<ul>
<form action="gallery.php" method="POST">
<?php
//define location of photo image
$photosDir = './photos';
//define which file extention are images
$photosExt = array('gif','jpg','jpeg','tif','tiff','bmp','png');
//initialize array to hold filenames of images found
$photoList = array();
//read directory contents
//build photo list
if (file_exists($photosDir)) {
$dp = opendir($photosDir) or die('Error: cannot open file');
while ($file = readdir($dp)) {
if ($file != '.' && $file != '..') {
$fileData = pathinfo($file);
if (in_array($fileData['extension'], $photosExt)) {
$photoList[] = "$photosDir/$file"; // file includes as an array
}
}
}
closedir($dp);
}else {
die('ERROR: directory dosent exists');
}
//itarate over photo list
//display each image and file name
if (count($photoList)>0) {
for ($x=0; $x <count($photoList) ; $x++) {
?>
<li>
<input type="submit" name="delete" value="Delete">
<img src="<?php echo $photoList[$x]; ?>" height="150" width="200"/>
<?php echo basename($photoList[$x]); ?><br>
<?php echo round(filesize($photoList[$x])/1024) . 'KB'; ?>
</li>
<?php
}
} else {
die('ERROR: No image found');
}
?>
</form>
</ul>
</body>
</html>
hello just change your submit input to:
<input type="submit" name="delete" value="<?php echo $photoList[$x] ?>">
and then check for that value:
<?php if(isset($_POST['delete']) && !empty($_POST['delete'])){
//find the file
$file = 'photos/'.$_POST['delete'];
if(is_file($file)){
unlink($file);
}else{
echo $_POST['delete']." has not been found!";
}
}?>

404 Error when uploading files with Uploadify on WordPress

I recently installed uploadifive on my site http://tradersprinting.com/contact/send-file-2/ , and am experiencing a 404 error every time that I attempt to upload a file.
The site is powered by the WordPress Content Management System, and the site is hosted on 1&1. The uploadify files are stored in the directory: "http://tradersprinting.com/wp-content/themes/traders/uploadify". The WordPress function "bloginfo('template_directory')" returns "http://tradersprinting.com/wp-content/themes/traders/". Everything is currently at "factory settings" without any adjustments, save the snippet of code I am attaching below:
Code on the Page http://tradersprinting.com/contact/send-file-2/
<?php
chmod("wp-content/themes/traders/uploads/",0777);
chmod("wp-content/themes/traders/uploadify/uploads/",0777);
?>
<script src="<?php bloginfo('template_directory'); ?>/uploadify/jquery.min.js" type="text/javascript">
</script>
<script src="<?php bloginfo('template_directory'); ?>/uploadify/jquery.uploadifive.min.js" type="text/javascript">
</script>
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/uploadify/uploadifive.css">
<style type="text/css">
body {
font: 13px Arial, Helvetica, Sans-serif;
}
.uploadifive-button {
float: left;
margin-right: 10px;
}
#queue {
border: 1px solid #E5E5E5;
height: 177px;
overflow: auto;
margin-bottom: 10px;
padding: 0 3px 3px;
width: 300px;
}
</style>
<form>
<div id="queue">
</div>
<input id="file_upload" name="file_upload" type="file" multiple="true">
<a style="position: relative; top: 8px;" href="javascript:$('#file_upload').uploadifive('upload')">Upload Files</a>
</form>
<script type="text/javascript">
<?php $timestamp = time();?>
$(function() {
$('#file_upload').uploadifive({
'auto' : false,
'checkScript' : 'check-exists.php',
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5('unique_salt' . $timestamp);?>'
},
'queueID' : 'queue',
'uploadScript' : 'uploadifive.php',
'onUploadComplete' : function(file, data) { console.log(data); }
});
});
</script>
My copy of uploadifive.php
<?php
/*
UploadiFive
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
*/
// Set the uplaod directory
$uploadDir = '/uploads/';
// Set the allowed file extensions
$fileTypes = array('jpg', 'jpeg', 'gif', 'png'); // Allowed file extensions
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
// Commenting out this line as a potential bugfix for 404 error
//$uploadDir = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
$uploadDir = "/wp-content/themes/traders/uploadify/uploads";
$targetFile = $uploadDir . $_FILES['Filedata']['name'];
// Validate the filetype
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array(strtolower($fileParts['extension']), $fileTypes)) {
// Save the file
move_uploaded_file($tempFile, $targetFile);
echo 1;
} else {
// The file type wasn't allowed
echo 'Invalid file type.';
}
}
?>
I have created an "uploads" directory in every branch of the directory tree starting from the root, and including one at every step of the way down to the sample uploadify directory, but none of them receive files.
I love the program, and I think the designer has done a stellar job, but I would really like for the product to work, especially after investing! Please help!
Uploadify uses a Flash SWF based uploader. In many cases Apache web server's mod_security module prevents data uploaded by any SWF. So I'd say check server's mod_security log (not Apache error log) if it is blocking your script.

Categories