Related
$(document).ready(function(){
$("#add_small").click(function(event){
event.preventDefault();
$(".add_small").append('<div class="form-group">\
<label for="product_small_image">Product Image:</label>\
<input type="file" name="product_image[]" class="product_image" value=""/>\
Remove\
<div>');
});
jQuery(document).on('click', '.remove_small', function() {
jQuery(this).parent().remove();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" name="user_registration" class="register" enctype="multipart/form-data">
<div class="form-group">
<label for="product_small_image">Product Image:</label>
<input type="file" name="product_image[]" class="product_image" value=""/>
Add
</div>
<div class="add_small"></div>
<br/>
<input name="submit" type="submit" class="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit']))
{
$file_ary = reArrayFiles($_FILES['product_images']);
foreach ($file_ary as $file)
{
//print 'File Name: ' . $file['name'];
//print 'File Type: ' . $file['type'];
//print 'File Size: ' . $file['size'];
$folder_Path = "../images/product_image/";
$banner_image_name = str_replace(" ", "", strtolower(basename($file['name'])));
$banner_image_name_upload = $folder_Path.$banner_image_name;
//$banner_image_tmp = $_FILES['product_image']['tmp_name'];
$imageFileType = strtolower(pathinfo($banner_image_name,PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
$msg = "<div class='alert alert-success'>Sorry, only JPG, JPEG, PNG & GIF files are allowed.</div>";
}
else
{
if (move_uploaded_file($banner_image_name_upload))
{
$set_width = 600;
$set_height = 600;
$banner_image_source_file = $banner_image_name_upload;
$banner_image_save_file = $banner_image_name_upload;
list($width_orig, $height_orig) = getimagesize($banner_image_source_file);
$image_p = imagecreatetruecolor($set_width, $set_height);
$image = imagecreatefromjpeg($banner_image_source_file);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $set_width, $set_height, $width_orig, $height_orig);
imagejpeg($image_p, $banner_image_save_file, 75);
$query = "insert into inventory_add_in_stock(`product_image`)values('".$file['name']."')";
echo $query;
$result = mysqli_query($con,$query);
if($result==true)
{
$msg = "<div class='alert alert-success'>Record Save Successfully</div>";
}
else
{
$msg = "<div class='alert alert-danger'>Unable to Save Please Try Again !!!</div>";
}
}
else
{
$msg = "<div class='alert alert-danger'>Unable to Proceeed Please Try Again !!!</div>";
}
}
}
}
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
?>
This is my duplicate question. I have create add and remove more file using jQuery. Now, What happen when I click on add button it show me to choose another file similarly again and again. I am able to upload multiple file like this. But the problem is that when I click on submit button to insert into the database and move image to the folder it show me error i.e.
I found the reason in your code:
$banner_image_tmp = $_FILES['product_image']['tmp_name'];
The $banner_image_tmp will return an array. So, there will be an error
move_uploaded_file() expects parameter 1 to be string, array given
http://php.net/manual/en/features.file-upload.multiple.php. Your code should be:
if(isset($_POST['submit']))
{
$file_ary = reArrayFiles($_FILES['product_image']);
foreach ($file_ary as $file) {
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
//Your custom code here
}
}
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
The following php pdf to image code with imagick in codeigniter framework has a problem in the controller, imagick cannot read my file pdf.
error:
[codeigniter] An uncaught Exception was encountered Type: ImagickException Message: Failed to read the file in Codeigniter.
controller:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Files_upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('files');
}
function index(){
$data['gallery'] = $this->db->query("select * from gallery order by id desc limit 10")->result();
$data = array();
if($this->input->post('submitForm') && !empty($_FILES['upload_Files']['name'])){
$filesCount = count($_FILES['upload_Files']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['upload_File']['name'] = $_FILES['upload_Files']['name'][$i];
$_FILES['upload_File']['type'] = $_FILES['upload_Files']['type'][$i];
$_FILES['upload_File']['tmp_name'] = $_FILES['upload_Files']['tmp_name'][$i];
$_FILES['upload_File']['error'] = $_FILES['upload_Files']['error'][$i];
$_FILES['upload_File']['size'] = $_FILES['upload_Files']['size'][$i];
$uploadPath = 'uploads/files/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|mp4|avi';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('upload_File')){
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
}
}
if(!empty($uploadData)){
//Insert file information into the database
$insert = $this->files->insert($uploadData);
$statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('statusMsg',$statusMsg);
}
$this->load->helper('url');
$ImageName = $_FILES['upload_File']['name'];
$loc = base_url().$uploadPath.$ImageName;
echo $ImageName;
echo $loc;
$im = new imagick($loc);
$noOfPagesInPDF = $im->getNumberImages();
if ($noOfPagesInPDF) {
for ($i = 0; $i < 1; $i++) {
$url = $loc.'['.$i.']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->setImageCompressionQuality(80);
$image->writeImage("uploads/files/img/".($i+1).'-'.$ImageName.'.jpg');
}
}
for($i = 0; $i<1;$i++) {
$img = "uploads/files/img/".($i+1).'-'.$ImageName.'.jpg';
$display .= "<img src='$img' title='Page-$i' /><br>";
}
$message = "PDF converted to JPEG sucessfully!!";
}
//Get files data from database
$data['gallery'] = $this->files->getRows();
//Pass the files data to view
$this->load->view('files_upload/index', $data);
}
}
Solved
Is Correct Code
$ImageName= $fileData['file_name'];
$loc = realpath(APPPATH.'../uploads/files/').'/'.$ImageName;
Or you can just do
$loc = $fileData['full_path'];
This will work (tested):
//$data['gallery'] = $this->db->query("select * from gallery order by id desc limit 10")->result(); // same at bottom??
$message = '';
$display = '';
if ($this->input->post('submitForm') && !empty($_FILES['userfile']['name'])) {
$uploadPath = FCPATH . 'uploads/files/';
if (!is_dir($uploadPath) && mkdir($uploadPath, DIR_WRITE_MODE, true) == false) {
show_error('Folder cannot be made!');
}
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|mp4|avi';
$this->load->library('upload', $config);
// change input field to <input type="file" name="userfile">
if (!$this->upload->do_upload()) {
$this->session->set_flashdata('statusMsg', $this->upload->display_errors());
} else {
$fileData = $this->upload->data();
$uploadData['file_name'] = $fileData['file_name'];
$uploadData['created'] = date("Y-m-d H:i:s");
$uploadData['modified'] = date("Y-m-d H:i:s");
$insert = $this->files->insert($uploadData);
$insert = true;
if (!$insert) {
#unlink($fileData['full_path']); // remove orphan
$this->session->set_flashdata('statusMsg', 'Database error. Please try again');
} else {
$this->session->set_flashdata('statusMsg', 'Files uploaded successfully.');
if ($fileData['file_ext'] == '.pdf') {
try {
$newPath = $uploadPath . 'img/';
if (!is_dir($newPath) && mkdir($newPath, DIR_WRITE_MODE, true) == false) {
throw new Exception('Folder cannot be made!');
}
$ImageName = $fileData['raw_name'];
$loc = $fileData['full_path'];
$im = new Imagick($loc);
$pdfPageCount = $im->getNumberImages();
if ($pdfPageCount > 0) {
for ($i = 0; $i < $pdfPageCount; $i++) {
$url = $loc . '[' . $i . ']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->setImageCompressionQuality(80);
$image->writeImage($newPath . ($i + 1) . '-' . $ImageName . '.jpg');
$img = base_url("uploads/files/img/" . ($i + 1) . '-' . $ImageName . '.jpg');
$display .= "<img src='$img' title='Page-$i' /><br>";
}
echo $display; // debugging
$this->session->set_flashdata('statusMsg', "PDF converted to JPEG(s) sucessfully!");
}
} catch (Exception $e) {
#unlink($fileData['full_path']); // remove orphan
$this->session->set_flashdata('statusMsg', $e->getMessage());
}
} else {
echo 'not a pdf'; // debugging only
}
}
}
}
//Get files data from database
$data['gallery'] = $this->files->getRows();
//Pass the files data to view
$this->load->view('files_upload/index', $data);
Please note the input file field should now look like this:
<input type="file" name="userfile" />
You will also have to revise:
$this->files->insert($uploadData) function
Im new to php please help me, I have a website and people can upload files like pdf, doc,xls and I want to limit the number of file upload. the user after login can see the upload page and upload his files but i want that the user can only upload files 3 times a day if he submitted 3 times in a day then it should not allow the user to upload more files it should give a message that you can not post more that 3 projects per day.
My files are: form.php and Uploadfile.php
<?php
use foundationphp\UploadFile;
session_start();
require_once 'src/foundationphp/UploadFile.php';
if (!isset($_SESSION['maxfiles'])) {
$_SESSION['maxfiles'] = ini_get('max_file_uploads');
$_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
$_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']);
}
$max = 2000000;
$result = array();
if (isset($_POST['upload'])) {
$destination = __DIR__ . '/uploaded/';
try {
$upload = new UploadFile($destination);
$upload->setMaxSize($max);
// $upload->allowAllTypes();
$upload->upload();
$result = $upload->getMessages();
} catch (Exception $e) {
$result[] = $e->getMessage();
}
}
$error = error_get_last();
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Uploads</title>
<link href="styles/form.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Uploading Files</h1>
<?php if ($result || $error) { ?>
<ul class="result">
<?php
if ($error) {
echo "<li>{$error['message']}</li>";
}
if ($result) {
foreach ($result as $message) {
echo "<li>$message</li>";
}
}?>
</ul>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max;?>">
<label for="filename">Select File:</label>
<input type="file" name="filename[]" id="filename" multiple
data-maxfiles="<?php echo $_SESSION['maxfiles'];?>"
data-postmax="<?php echo $_SESSION['postmax'];?>"
data-displaymax="<?php echo $_SESSION['displaymax'];?>">
</p>
<ul>
<li>Up to <?php echo $_SESSION['maxfiles'];?> files can be uploaded simultaneously.</li>
<li>Each file should be no more than <?php echo UploadFile::convertFromBytes($max);?>.</li>
<li>Combined total should not exceed <?php echo $_SESSION ['displaymax'];?>.</li>
</ul>
<p>
<input type="submit" name="upload" value="Upload File">
</p>
</form>
<script src="js/checkmultiple.js"></script>
</body>
</html>
And uploadfile.php
<?php
namespace foundationphp;
class UploadFile
{
protected $destination;
protected $messages = array();
protected $maxSize = 2102400;//51200; //50 KB
protected $permittedTypes = array(
'image/jpeg',
'image/pjpeg',
'image/gif',
'image/png',
'image/webp',
'application/pdf',
'application/rar',
'application/zip',
'application/x-zip',
'application/x-zip-compressed',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.oasis.opendocument.spreadsheet',
'application/vnd.oasis.opendocument.presentation',
'application/vnd.oasis.opendocument.text'
);
protected $newName;
protected $typeCheckingOn = true;
protected $notTrusted = array('bin', 'cgi', 'exe', 'dmg', 'js', 'pl', 'php', 'py', 'sh');
protected $suffix = '.upload';
protected $renameDuplicates;
public function __construct($uploadFolder)
{
if (!is_dir($uploadFolder) || !is_writable($uploadFolder)) {
throw new \Exception("$uploadFolder must be a valid, writable folder.");
}
if ($uploadFolder[strlen($uploadFolder)-1] != '/') {
$uploadFolder .= '/';
}
$this->destination = $uploadFolder;
}
public function setMaxSize($bytes)
{
$serverMax = self::convertToBytes(ini_get('upload_max_filesize'));
if ($bytes > $serverMax) {
throw new \Exception('Maximum size cannot exceed server limit for individual files: ' . self::convertFromBytes($serverMax));
}
if (is_numeric($bytes) && $bytes > 0) {
$this->maxSize = $bytes;
}
}
public static function convertToBytes($val)
{
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
if (in_array($last, array('g', 'm', 'k'))){
switch ($last) {
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
}
return $val;
}
public static function convertFromBytes($bytes)
{
$bytes /= 1024;
if ($bytes > 1024) {
return number_format($bytes/1024, 1) . ' MB';
} else {
return number_format($bytes, 1) . ' KB';
}
}
public function allowAllTypes($suffix = null)
{
$this->typeCheckingOn = false;
if (!is_null($suffix)) {
if (strpos($suffix, '.') === 0 || $suffix == '') {
$this->suffix = $suffix;
} else {
$this->suffix = ".$suffix";
}
}
}
public function upload($renameDuplicates = true)
{
$this->renameDuplicates = $renameDuplicates;
$uploaded = current($_FILES);
if (is_array($uploaded['name'])) {
foreach ($uploaded['name'] as $key => $value) {
$currentFile['name'] = $uploaded['name'][$key];
$currentFile['type'] = $uploaded['type'][$key];
$currentFile['tmp_name'] = $uploaded['tmp_name'][$key];
$currentFile['error'] = $uploaded['error'][$key];
$currentFile['size'] = $uploaded['size'][$key];
if ($this->checkFile($currentFile)) {
$this->moveFile($currentFile);
}
}
} else {
if ($this->checkFile($uploaded)) {
$this->moveFile($uploaded);
}
}
}
public function getMessages()
{
return $this->messages;
}
protected function checkFile($file)
{
if ($file['error'] != 0) {
$this->getErrorMessage($file);
return false;
}
if (!$this->checkSize($file)) {
return false;
}
if ($this->typeCheckingOn) {
if (!$this->checkType($file)) {
return false;
}
}
$this->checkName($file);
return true;
}
protected function getErrorMessage($file)
{
switch($file['error']) {
case 1:
case 2:
$this->messages[] = $file['name'] . ' is too big: (max: ' .
self::convertFromBytes($this->maxSize) . ').';
break;
case 3:
$this->messages[] = $file['name'] . ' was only partially uploaded.';
break;
case 4:
$this->messages[] = 'No file submitted.';
break;
default:
$this->messages[] = 'Sorry, there was a problem uploading ' . $file['name'];
break;
}
}
protected function checkSize($file)
{
if ($file['size'] == 0) {
$this->messages[] = $file['name'] . ' is empty.';
return false;
} elseif ($file['size'] > $this->maxSize) {
$this->messages[] = $file['name'] . ' exceeds the maximum size for a file ('
. self::convertFromBytes($this->maxSize) . ').';
return false;
} else {
return true;
}
}
protected function checkType($file)
{
if (in_array($file['type'], $this->permittedTypes)) {
return true;
} else {
$this->messages[] = $file['name'] . ' is not permitted type of file.';
return false;
}
}
protected function checkName($file)
{
$this->newName = null;
$nospaces = str_replace(' ', '_', $file['name']);
if ($nospaces != $file['name']) {
$this->newName = $nospaces;
}
$nameparts = pathinfo($nospaces);
$extension = isset($nameparts['extension']) ? $nameparts['extension'] : '';
if (!$this->typeCheckingOn && !empty($this->suffix)) {
if (in_array($extension, $this->notTrusted) || empty($extension)) {
$this->newName = $nospaces . $this->suffix;
}
}
if ($this->renameDuplicates) {
$name = isset($this->newName) ? $this->newName : $file['name'];
$existing = scandir($this->destination);
if (in_array($name, $existing)) {
$i = 1;
do {
$this->newName = $nameparts['filename'] . '_' . $i++;
if (!empty($extension)) {
$this->newName .= ".$extension";
}
if (in_array($extension, $this->notTrusted)) {
$this->newName .= $this->suffix;
}
} while (in_array($this->newName, $existing));
}
}
}
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$result .= '.';
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
Thanks/Regards,
Sam
You can use SQL to store the amount of files uploaded by each user. Then you can check in php if a user can upload another file or not with SQL queries.
EDIT:
Let's elaborate a little.
There can be 2 ways for achieving this:
a) server-side.
As you say, you have a login form. I suppose you have a database with usernames and passwords, right? So, you can add an 'uploads' table in your database with the timestamp of each upload and the username of the uploader.
Then, each time your PHP class is called, you can make a query to your database to see the amount of files the uploader has uploaded within the last 24 hours. If the number is <3 then your PHP class will allow him to upload another one. Else, your PHP class will echo the message you want.
b) client-side.
Each time a user uploads a file, the info about his uploads is stored in his localStorage. So, this info will be checked on 'upload' button click event and either he will be allowed to upload or not.
However, as I said, the info is stored in HIS localStorage, so, this method is bypassable by the user. I wouldn't recommend it.
Improve your upload function and add destination inside UploadFile class for better re-usability and security:
class UploadFile
{
protected $destination = __DIR__ . '/uploaded/';
protected $messages = array();
protected $maxSize = 2102400;//51200; //50 KB
protected $permittedTypes = array(
'image/jpeg',
'image/pjpeg',
'image/gif',
'image/png',
'image/webp',
'application/pdf',
'application/rar',
'application/zip',
'application/x-zip',
'application/x-zip-compressed',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.oasis.opendocument.spreadsheet',
'application/vnd.oasis.opendocument.presentation',
'application/vnd.oasis.opendocument.text'
);
protected $newName;
protected $typeCheckingOn = true;
protected $notTrusted = array('bin', 'cgi', 'exe', 'dmg', 'js', 'pl', 'php', 'py', 'sh');
protected $suffix = '.upload';
protected $renameDuplicates;
public function __construct($uploadFolder)
{
if (!is_dir($uploadFolder) || !is_writable($uploadFolder)) {
throw new \Exception("$uploadFolder must be a valid, writable folder.");
}
if ($uploadFolder[strlen($uploadFolder)-1] != '/') {
$uploadFolder .= '/';
}
$this->destination = $uploadFolder;
}
public function setMaxSize($bytes)
{
$serverMax = self::convertToBytes(ini_get('upload_max_filesize'));
if ($bytes > $serverMax) {
throw new \Exception('Maximum size cannot exceed server limit for individual files: ' . self::convertFromBytes($serverMax));
}
if (is_numeric($bytes) && $bytes > 0) {
$this->maxSize = $bytes;
}
}
public static function convertToBytes($val)
{
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
if (in_array($last, array('g', 'm', 'k'))){
switch ($last) {
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
}
return $val;
}
public static function convertFromBytes($bytes)
{
$bytes /= 1024;
if ($bytes > 1024) {
return number_format($bytes/1024, 1) . ' MB';
} else {
return number_format($bytes, 1) . ' KB';
}
}
public function allowAllTypes($suffix = null)
{
$this->typeCheckingOn = false;
if (!is_null($suffix)) {
if (strpos($suffix, '.') === 0 || $suffix == '') {
$this->suffix = $suffix;
} else {
$this->suffix = ".$suffix";
}
}
}
public function upload($renameDuplicates = true)
{
$fi = new FilesystemIterator($this->destination, FilesystemIterator::SKIP_DOTS);
$totalFiles = iterator_count($fi);
if ($totalFiles <= 3){
$this->renameDuplicates = $renameDuplicates;
$uploaded = current($_FILES);
if (is_array($uploaded['name'])) {
foreach ($uploaded['name'] as $key => $value) {
$currentFile['name'] = $uploaded['name'][$key];
$currentFile['type'] = $uploaded['type'][$key];
$currentFile['tmp_name'] = $uploaded['tmp_name'][$key];
$currentFile['error'] = $uploaded['error'][$key];
$currentFile['size'] = $uploaded['size'][$key];
if ($this->checkFile($currentFile)) {
$this->moveFile($currentFile);
}
}
} else {
if ($this->checkFile($uploaded)) {
$this->moveFile($uploaded);
}
}
} else {
die('You can not post more that 3 projects per day!'); //Improve this to a thrown or stuff;
}
}
public function getMessages()
{
return $this->messages;
}
protected function checkFile($file)
{
if ($file['error'] != 0) {
$this->getErrorMessage($file);
return false;
}
if (!$this->checkSize($file)) {
return false;
}
if ($this->typeCheckingOn) {
if (!$this->checkType($file)) {
return false;
}
}
$this->checkName($file);
return true;
}
protected function getErrorMessage($file)
{
switch($file['error']) {
case 1:
case 2:
$this->messages[] = $file['name'] . ' is too big: (max: ' .
self::convertFromBytes($this->maxSize) . ').';
break;
case 3:
$this->messages[] = $file['name'] . ' was only partially uploaded.';
break;
case 4:
$this->messages[] = 'No file submitted.';
break;
default:
$this->messages[] = 'Sorry, there was a problem uploading ' . $file['name'];
break;
}
}
protected function checkSize($file)
{
if ($file['size'] == 0) {
$this->messages[] = $file['name'] . ' is empty.';
return false;
} elseif ($file['size'] > $this->maxSize) {
$this->messages[] = $file['name'] . ' exceeds the maximum size for a file ('
. self::convertFromBytes($this->maxSize) . ').';
return false;
} else {
return true;
}
}
protected function checkType($file)
{
if (in_array($file['type'], $this->permittedTypes)) {
return true;
} else {
$this->messages[] = $file['name'] . ' is not permitted type of file.';
return false;
}
}
protected function checkName($file)
{
$this->newName = null;
$nospaces = str_replace(' ', '_', $file['name']);
if ($nospaces != $file['name']) {
$this->newName = $nospaces;
}
$nameparts = pathinfo($nospaces);
$extension = isset($nameparts['extension']) ? $nameparts['extension'] : '';
if (!$this->typeCheckingOn && !empty($this->suffix)) {
if (in_array($extension, $this->notTrusted) || empty($extension)) {
$this->newName = $nospaces . $this->suffix;
}
}
if ($this->renameDuplicates) {
$name = isset($this->newName) ? $this->newName : $file['name'];
$existing = scandir($this->destination);
if (in_array($name, $existing)) {
$i = 1;
do {
$this->newName = $nameparts['filename'] . '_' . $i++;
if (!empty($extension)) {
$this->newName .= ".$extension";
}
if (in_array($extension, $this->notTrusted)) {
$this->newName .= $this->suffix;
}
} while (in_array($this->newName, $existing));
}
}
}
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$result .= '.';
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
I think you have a user table in you DB. just add a new attribute upload_day_count...
At every upload you check if the number is at 3 if not then you allow the upload and icrement the attribute value for this user. Day +1 at 00h01min you run a cron Job to reset all values for all users.
We are trying to use this plugin code in our php script
https://github.com/wp-plugins/google-drive-wp-media/tree/master/gdwpm-api
We modified code and using successfully in our project, But its working only for small files, When we upload large files to google drive files showing only in KB size.
May be only last chunk is uploaded to google drive for large files,
We tried to solve this error but failed, Please check and tell what we are doing wrong.
Here is our modified files.
index.php
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script type='text/javascript' src='http://myweb.com/wp-admin/load-scripts.php?c=0&load%5B%5D=jquery-core,jquery-migrate,utils,plupload&ver=4.4.2'></script>
<div class="container">
<div id="tabs-2" aria-labelledby="ui-id-12" class="ui-tabs-panel ui-widget-content ui-corner-bottom" role="tabpanel" aria-hidden="false" style="display: block;">
<p style="display: flex; align-items: center;">
Select folder: <select id="folder_pilian_aplod" name="folder_pilian_aplod" style="display: block;"><option value="0B0pm8dZPprJ-cElGclFoc2tVZ1E">testdata</option></select>
</p>
<!--<p>Short Description: <input type="text" name="gdwpm_aplod_deskrip" value="" size="65" placeholder="Optional"></p>-->
<p>
</p><ul>
<li><dfn>Accepted Media MIME types: */*</dfn>
<!-- <br /> <dfn>All Filetypes are allowed.</dfn>
--></li>
</ul>
<p></p>
<ul id="filelist"></ul>
<br>
<button id="gdwpm_tombol_bersih" style="display:none;float:right;" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" role="button"><span class="ui-button-icon-primary ui-icon ui-icon-grip-dotted-horizontal"></span><span class="ui-button-text">Clear List</span></button>
<div id="gdwpm_upload_container"><p id="gdwpm-pilih-kt" style="position: relative;">Choose your files:
<a id="gdwpm_tombol_browse" href="javascript:;" style="position: relative; z-index: 1;"><button id="gdwpm_tombol_bk_folder" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" role="button"><span class="ui-button-icon-primary ui-icon ui-icon-folder-open"></span><span class="ui-button-text">Browse</span></button></a><div id="html5_1asc3hchetiq1f6q14bnli91i4k3_container" class="moxie-shim moxie-shim-html5" style="position: absolute; top: 5px; left: 123px; width: 92px; height: 16px; overflow: hidden; z-index: 0;"><input id="html5_1asc3hchetiq1f6q14bnli91i4k3" type="file" style="font-size: 999px; opacity: 0; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;" multiple="" accept="" class="ui-corner-all"></div></p>
<input type="checkbox" id="gdwpm_cekbok_masukperpus" name="gdwpm_cekbok_masukperpus" value="1" checked="" class="ui-corner-all"> Add to Media Library. (just linked to, all files still remain in Google Drive)<!-- (Image only: <i>*.jpg, *.jpeg, *.png, & *.gif</i>)--><p>
<a style="" id="gdwpm_start-upload" href="javascript:;"><button id="gdwpm_tombol_upload" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" role="button"><span class="ui-button-icon-primary ui-icon ui-icon-arrowthickstop-1-n"></span><span class="ui-button-text">Upload to Google Drive</span></button></a>
</p>
<pre id="console"></pre>
</div>
<div id="gdwpm_loding_128" style="display:none;"><center>
<img src="http://localhost/wordpress/wp-content/plugins/google-drive-wp-media/images/animation/gdwpm_loader_128.gif"><br>Uploading...<br><small id="respon_progress"></small></center></div>
<script type="text/javascript">
var uploader = new plupload.Uploader({
browse_button: 'gdwpm_tombol_browse',
url: 'uploader.php',
chunk_size: '700kb',
max_retries: 3 });
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
var html = '';
plupload.each(files, function(file) {
html += '<li id="' + file.id + '"><code>' + file.name + '</code> (' + plupload.formatSize(file.size) + ') <span class="hasilprog"></span> <input type="text" id="' + file.id + 'gdwpm_aplod_deskrip" name="' + file.id + 'lod_deskrip" value="" size="55" placeholder="Short Description (optional) *Alphanumeric*"><hr></li>';
});
document.getElementById('filelist').innerHTML += html;
jQuery('#console').empty();
jQuery('#gdwpm_tombol_bersih').hide();
jQuery('#gdwpm_start-upload').show();
jQuery('#infopraupload').remove();
});
uploader.bind('UploadProgress', function(up, file) {
document.getElementById(file.id).getElementsByClassName('hasilprog')[0].innerHTML = "<dfn>" + file.percent + "%</dfn> <small>" + jQuery('#' + file.id + 'gdwpm_aplod_deskrip').val().replace(/[^\w\s-]/gi, '') + "</small>";
jQuery('#' + file.id + 'gdwpm_aplod_deskrip').hide();
jQuery('#gdwpm_upload_container').hide();
jQuery('#gdwpm_loding_128').show();
jQuery('#gdwpm_tombol_bersih').hide();
});
uploader.bind('Error', function(up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
jQuery('#gdwpm_upload_container').show();
jQuery('#gdwpm_loding_128').hide();
jQuery('#gdwpm_start-upload').hide();
jQuery('#gdwpm_tombol_bersih').show();
});
document.getElementById('gdwpm_start-upload').onclick = function() {
uploader.start();
};
uploader.bind('FileUploaded', function(up, file, response ) {
response=response["response"];
jQuery('#console').html(response);
var totalspan = document.getElementById('filelist').getElementsByClassName('hasilprog').length;
var totaldfn = document.getElementById('filelist').getElementsByTagName('dfn').length;
if(totalspan == totaldfn){
jQuery('#gdwpm_upload_container').show();
jQuery('#gdwpm_tombol_bersih').show();
jQuery('#gdwpm_loding_128').hide();
}
jQuery('#gdwpm_start-upload').hide();
jQuery('#respon_progress').empty();
if(jQuery('#gdwpm_folder_anyar').val() != ''){
jQuery('#gdwpm_info_folder_baru').show();
}
});
uploader.bind('BeforeUpload', function (up, file) {
up.settings.multipart_params = {gdpwm_nm_bks: jQuery("#folder_pilian_aplod option:selected").text(), gdpwm_nm_id: jQuery('select[name=folder_pilian_aplod]').val(),
gdpwm_nm_br: jQuery('#gdwpm_folder_anyar').val(), gdpwm_sh_ds: jQuery('#' + file.id + 'gdwpm_aplod_deskrip').val().replace(/[^\w\s-]/gi, ''), gdpwm_med_ly: jQuery('#gdwpm_cekbok_masukperpus:checked').val(),
gdpwm_nama_file: file.name};
});
uploader.bind('ChunkUploaded', function(up, file, info) {
response=info["response"];
jQuery('#respon_progress').empty();
jQuery('#console').html(response);
jQuery('#respon_progress').html('[Chunked: ' + info["offset"] + ' of ' + info["total"] + ' bytes]');
//jQuery('#gdwpm_upload_container').show();
//jQuery('#gdwpm_loding_128').hide();
//jQuery('#gdwpm_start-upload').hide();
});
</script>
</div>
</div>
uploader.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once 'gdwpm-api/Google_Client.php';
require_once 'gdwpm-api/contrib/Google_DriveService.php';
require_once 'gwbp.php';
set_time_limit(600000000);
global $cek_kunci, $gdwpm_opt_akun, $gdwpm_service, $gdwpm_apiConfig;
if (empty($_FILES) || $_FILES["file"]["error"]) {
die('<div class="error"><p>Oops.. error, upload failed! '.$_FILES["file"]["error"].'</p></div>');
}
if (isset($_REQUEST["gdpwm_nama_file"])) {
$filename = $_REQUEST["gdpwm_nama_file"];
} elseif (!empty($_FILES)) {
$filename = $_FILES["file"]["name"];
} else {
$filename = uniqid("file_");
}
$targetDir = ini_get("upload_tmp_dir");
$maxFileAge = 5000 * 3600; // Temp file age in seconds
// Create target dir
if (!file_exists($targetDir)) {
//#mkdir($targetDir);
if (!file_exists($targetDir = sys_get_temp_dir())){
$upload_dir = wp_upload_dir();
if (!file_exists($targetDir = $upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'gdwpm-tmp')) {
#mkdir($targetDir);
}
}
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $filename;
// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
die('<div class="error"><p>Oops.. error. Failed to open temp directory.</p></div>');
}
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}.part") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
#unlink($tmpfilePath);
}
}
closedir($dir);
// Open temp file
if (!$out = #fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
die('<div class="error"><p>Oops.. error. Failed to open output stream.</p></div>');
}
if (!empty($_FILES)) {
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
die('<div class="error"><p>Oops.. error. Failed to move uploaded file.</p></div>');
}
// Read binary input stream and append it to temp file
if (!$in = #fopen($_FILES["file"]["tmp_name"], "rb")) {
die('<div class="error"><p>Oops.. error. Failed to open input stream.</p></div>');
}
} else {
if (!$in = #fopen("php://input", "rb")) {
die('<div class="error"><p>Oops.. error. Failed to open input stream.</p></div>');
}
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
#fclose($out);
#fclose($in);
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
if($filePath){
rename("{$filePath}.part", $filePath);
}else{
$filePath = $_FILES["file"]["tmp_name"];
}
$gdwpm_opt_imel = 'myemail#gmail.com';
$gdwpm_opt_klaen_aidi = 'myid';
$gdwpm_opt_nama_service = 'uploadservice#m.gserviceaccount.com';
$gdwpm_opt_kunci_rhs = 'UploadFiles-f15596286d09.p12';
$gdwpm_opt_akun = array($gdwpm_opt_imel, $gdwpm_opt_klaen_aidi, $gdwpm_opt_nama_service, $gdwpm_opt_kunci_rhs);
$gdwpm_service = new GDWPMBantuan( $gdwpm_opt_akun[1], $gdwpm_opt_akun[2], $gdwpm_opt_akun[3] );
//$mime_berkas_arr = wp_check_filetype($filename);
$finfo = new finfo;
$mime_berkas_arr['type'] = $finfo->file($filePath, FILEINFO_MIME);
//print_r($mime_berkas_arr);
$mime_berkas = $mime_berkas_arr['type'];
if(empty($mime_berkas)){$mime_berkas = $_FILES['file']['type'];}
$folder_ortu = preg_replace("/[^a-zA-Z0-9]+/", " ", $_POST['gdpwm_nm_br']);
$folder_ortu = trim(($folder_ortu));
$folderId = $_POST['gdpwm_nm_id'];
$nama_polder = $_POST['gdpwm_nm_bks'];
if($folder_ortu != ''){
//cek folder array id namafolder
$last_folder = get_option('gdwpm_new_folder_kecing');
if($folder_ortu != $last_folder[1]){
$folderId = $gdwpm_service->getFolderIdByName( $folder_ortu );
if( $folderId ) { update_option('gdwpm_new_folder_kecing', array($folderId, $folder_ortu)); }
$nama_polder = $folder_ortu;
}else{
$folderId = $last_folder[0];
$nama_polder = $last_folder[1];
}
}
$content = $_POST['gdpwm_sh_ds'];
if( ! $folderId ) {
$folderId = $gdwpm_service->createFolder( $folder_ortu );
$gdwpm_service->setPermissions( $folderId, $gdwpm_opt_akun[0] );
update_option('gdwpm_new_folder_kecing', array($folderId, $nama_polder));
}
if(strpos($mime_berkas_arr['type'], 'image') !== false){
// cek gambar if img auto create thumb .. array('checked', '', '122', '122', 'false');
$gdwpm_img_thumbs = get_option('gdwpm_img_thumbs');
// ITUNG DIMENSI
$image = wp_get_image_editor( $filePath );
if ( !is_wp_error( $image ) ) {
$ukuran_asli = $image->get_size(); // $ukuran_asli['width']; $ukuran_asli['height'];
}
$idthumb_w_h = '';
if ($gdwpm_img_thumbs[0] == 'checked'){
$folderId_thumb = $gdwpm_img_thumbs[1];
if(empty($folderId_thumb) || $folderId_thumb == ''){
//$folderId_thumb = $gdwpm_service->getFolderIdByName( 'gdwpm-thumbnails' );
//if(!$folderId_thumb){
$folderId_thumb = $gdwpm_service->createFolder( 'gdwpm-thumbnails' );
$gdwpm_service->setPermissions( $folderId_thumb, $gdwpm_opt_akun[0] );
//}
$gdwpm_img_thumbs[1] = trim($folderId_thumb);
update_option('gdwpm_img_thumbs', $gdwpm_img_thumbs);
}
if ( $ukuran_asli ) {
if($gdwpm_img_thumbs[4] == 'true'){
$image->resize( $gdwpm_img_thumbs[2], $gdwpm_img_thumbs[3], true );
}else{
$image->resize( $gdwpm_img_thumbs[2], $gdwpm_img_thumbs[3], false );
}
$img = $image->save(); // path, file, mime-type
$filename_thumb = $img['file'];
$filePath_thumb = $img['path'];
$mime_berkas_thumb = $img['mime-type'];
$imgwidth_thumb = $img['width'];
$imgheight_thumb = $img['height'];
}
$fileParent_thumb = new Google_ParentReference();
$fileParent_thumb->setId( $folderId_thumb );
$fileId_thumb = $gdwpm_service->createFileFromPath( $filePath_thumb, $filename_thumb, $content, $fileParent_thumb );
$gdwpm_service->setPermissions( $fileId_thumb, 'me', 'reader', 'anyone' );
$idthumb_w_h = 'thumbId:' . $fileId_thumb . ' thumbWidth:' . $imgwidth_thumb . ' thumbHeight:' . $imgheight_thumb;
}
$gdwpm_sizez_meta = 'selfWidth:' . $ukuran_asli['width'] . ' selfHeight:' . $ukuran_asli['height'] . ' ' . $idthumb_w_h;
#unlink($filename_thumb);
}else{
$gdwpm_sizez_meta = '';
}
$fileParent = new Google_ParentReference();
$fileParent->setId( $folderId );
//$fileId = $gdwpm_service->createFileFromPath( $_FILES["file"]["tmp_name"], $filename, $content, $fileParent );
$fileId = $gdwpm_service->createFileFromPath( $filePath, $filename, $content, $fileParent );
if($fileId){
$gdwpm_service->setPermissions( $fileId, 'me', 'reader', 'anyone' );
if(strpos($mime_berkas_arr['type'], 'image') !== false && !empty($gdwpm_sizez_meta)){
$gdwpm_service->insertProperty($fileId, 'gdwpm-sizes', $gdwpm_sizez_meta);
}
$sukinfo = '';
$metainfo = '';
if(!empty($mime_berkas) && isset($_POST['gdpwm_med_ly']) == '1'){
//gdwpm_ijin_masuk_perpus($mime_berkas, $filename, $fileId, $content, $nama_polder, $gdwpm_sizez_meta, $metainfo);
$sukinfo = ' and added into your Media Library';
}
$to = "myemail#gmail.com";
$subject = "File Uploaded";
$txt = $filename." successfully uploaded to ".$nama_polder;
$headers = "From: webmaster#gmail.com";
mail($to,$subject,$txt,$headers);
echo '<div class="updated"><p>'.$filename.' (<strong>'.$fileId.'</strong>) successfully uploaded to <strong>'.$nama_polder.'</strong>'.$sukinfo.'.</p></div>';
}else{
echo '<div class="error"><p>Failed to upload <strong>'.$filename.'</strong> to Google Drive.</p></div>';
}
#unlink($filePath);
}
?>
gwbp.php
<?php
class GDWPMBantuan {
protected $scope = array('https://www.googleapis.com/auth/drive');
private $_service;
public function __construct( $clientId, $serviceAccountName, $key ) {
$client = new Google_Client();
$client->setApplicationName("Google Drive WP Media");
$client->setClientId( $clientId );
$client->setAssertionCredentials( new Google_AssertionCredentials(
$serviceAccountName,
$this->scope,
$this->getKonten( $key ) )
);
$this->_service = new Google_DriveService($client);
}
public function __get( $name ) {
return $this->_service->$name;
}
public function getKonten( $url ) {
if(function_exists('curl_version')){
$data = curl_init();
curl_setopt($data, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($data, CURLOPT_URL, $url);
curl_setopt($data, CURLOPT_FOLLOWLOCATION,TRUE);
curl_setopt($data, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($data, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($data, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201');
$hasil = curl_exec($data);
curl_close($data);
return $hasil;
}else{
$hasil = file_get_contents(str_replace(' ', '%20', $url));
return $hasil;
}
}
public function getAbout( ) {
return $this->_service->about->get();
}
public function buangFile( $fileId ) {
$result = $this->_service->files->delete($fileId);
if(empty($result)){
return true;
}else{
return false;
}
}
public function getNameFromId( $fileId ) {
$file_proper = $this->_service->files->get($fileId);
$file_name = $file_proper->title;
return $file_name;
}
public function insertProperty($fileId, $key, $value, $visibility = 'PUBLIC') {
if(!empty($value) || $value != ''){
$newProperty = new Google_Property();
$newProperty->setKey($key);
$newProperty->setValue($value);
$newProperty->setVisibility($visibility);
return $this->_service->properties->insert($fileId, $newProperty);
}else{
return false;
}
}
public function createFileFromPath( $path, $fileName, $description, Google_ParentReference $fileParent = null ) {
$finfo = new finfo;
$mimeType['type'] = $finfo->file($path, FILEINFO_MIME);
// $mimeType = wp_check_filetype($fileName);
$file = new Google_DriveFile();
$file->setTitle( $fileName );
$file->setDescription( $description );
$file->setMimeType( $mimeType['type'] );
if( $fileParent ) {
$file->setParents( array( $fileParent ) );
}
// $gdwpm_opsi_chunk = get_option('gdwpm_opsi_chunk');
$gdwpm_opsi_chunk=array('local' => array(
'cekbok' =>'checked',
'chunk' => 700,
'retries' => 3
),
'drive' => array
(
'cekbok' => 'checked',
'chunk' => 2,
'retries' => 3
)
);
$chunks = $gdwpm_opsi_chunk['drive']['chunk'];
$max_retries = (int) $gdwpm_opsi_chunk['drive']['retries'];
$chunkSize = (1024 * 1024) * (int) $chunks; // 2mb chunk
$fileupload = new Google_MediaFileUpload($mimeType['type'], null, true, $chunkSize);
$fileupload->setFileSize(filesize($path));
$mkFile = $this->_service->files->insert($file, array('mediaUpload' => $fileupload));
$status = false;
$handle = fopen($path, "rb");
while (!$status && !feof($handle)) {
$max = false;
for ($i=1; $i<=$max_retries; $i++) {
$chunked = fread($handle, $chunkSize);
if ($chunked) {
$createdFile = $fileupload->nextChunk($mkFile, $chunked);
break;
}elseif($i == $max_retries){
$max = true;
}
}
if($max){
if($createdFile){
$this->_service->files->trash( $createdFile['id'] );
}
$createdFile = false;
break;
}
}
fclose($handle);
if($createdFile){
return $createdFile['id'];
}else{
return false;
}
}
public function createFolder( $name ) {
$file = new Google_DriveFile();
$file->setTitle( $name );
$file->setMimeType( 'application/vnd.google-apps.folder' );
$createdFolder = $this->_service->files->insert($file, array('mimeType' => 'application/vnd.google-apps.folder'));
return $createdFolder['id'];
}
public function setPermissions( $fileId, $value, $role = 'writer', $type = 'user' ) {
$perm = new Google_Permission();
$perm->setValue( $value );
$perm->setType( $type );
$perm->setRole( $role );
return $this->_service->permissions->insert($fileId, $perm);
}
public function getFolderIdByName( $name ) {
$parameters = array('q' => "mimeType = 'application/vnd.google-apps.folder'", 'maxResults' => 50);
$files = $this->_service->files->listFiles($parameters);
foreach( $files['items'] as $item ) {
if( $item['title'] == $name ) {
return $item['id'];
break;
}
}
return false;
}
public function getFilesInFolder($folderId, $maxResults, $pageToken = '', $in_type = 'radio') {
if($in_type == 'radio'){
$div_id = 'hasil';
$id_max = 'maxres';
$id_folid = 'folid';
$id_tblpagi = 'paginasi';
$div_hal = 'halaman';
$div_pagi = 'vaginasi';
$opsi_kecing = 'gdwpm_kecing_hal';
$in_name = 'gdwpm_berkas_terpilih[]';
}elseif($in_type == 'checkbox'){
$div_id = 'hasil_del';
$id_max = 'maxres_del';
$id_folid = 'folid_del';
$id_tblpagi = 'paginasi_del';
$div_hal = 'halaman_del';
$div_pagi = 'vaginasi_del';
$opsi_kecing = 'gdwpm_kecing_hal_del';
$in_name = 'gdwpm_buang_berkas_terpilih[]';
}else{
$in_type = 'checkbox';
$div_id = 'hasil_gal';
$id_max = 'maxres_gal';
$id_folid = 'folid_gal';
$id_tblpagi = 'paginasi_gal';
$div_hal = 'halaman_gal';
$div_pagi = 'vaginasi_gal';
$opsi_kecing = 'gdwpm_kecing_hal_gal';
$in_name = 'gdwpm_berkas_gallery[]';
}
//setup 1st pagetokn is always enpty n create pagintion butt
$haldepan = 1;
////$hal = '<input type="hidden" id="maxres" value="'.$maxResults.'" /><button id="halaman" value="">'.$haldepan.'</button>';
$parameters = array('maxResults' => $maxResults);
$pageTokenInput = $pageToken;
$gdwpm_kecing_hal = get_option($opsi_kecing);
if (empty($pageToken) || $pageToken == '') {
// generate halaman
//if($gdwpm_kecing_hal || !empty($gdwpm_kecing_hal)){
//delete_option($opsi_kecing);
//}
$gdwpm_kecing_hal = array();
$errormes = '';
$halarr = array($haldepan => 'bantuanhalamansatu');
do {
$haldepan++;
try {
if($haldepan == 1){$pageToken = '';} //halman prtama pokoke token kudu kosong
$parameters['pageToken'] = $pageToken;
$children = $this->_service->children->listChildren($folderId, $parameters);
$pageToken = $children->getNextPageToken();
if($pageToken){
//$hal .= ' <button id="halaman" value="'.$pageToken.'">'.$haldepan.'</button>';
$halarr[$haldepan] = $pageToken;
if($haldepan % 10 == 0){sleep(1);}
//}elseif($haldepan > 1){
//cek n buang halman trakir jika kosong
//$parameters['pageToken'] = $halarr[$haldepan - 1];
//$files = $this->_service->children->listChildren($folderId, $parameters);
//$result = array();
//if(count(array_merge($result, $files->getItems())) < 1){
//unset($halarr[$haldepan - 1]);
//}
}
} catch (Exception $e) {
$errormes = "<kbd>An error occurred: " . $e->getMessage() . "</kbd>";
$haldepan -= 1;
$pageToken = $halarr[$haldepan]; //NULL;
sleep(1);
}
} while ($pageToken);
unset($parameters['pageToken']);
$gdwpm_kecing_hal[$folderId] = $halarr;
update_option($opsi_kecing, $gdwpm_kecing_hal);
}else{
$parameters['pageToken'] = $pageToken;
}
$daftarfile = '';
if(count($halarr) <= 1 || $pageToken != ''){
if($pageToken == 'bantuanhalamansatu'){
unset($parameters['pageToken']);
}
$folder_proper = $this->_service->files->get($folderId);
$folder_name = $folder_proper->title;
$i = 0;
$daftarfile = '<div id="'.$div_id.'"><table id="box-table-a" summary="File Folder" class="'.$id_tblpagi.'"><thead><tr><th scope="col"><span class="ui-icon ui-icon-check"></span></th><th scope="col">File ID</th><th scope="col">Title</th><!--<th scope="col">Description</th>--><th scope="col">Size</th><th scope="col">Action</th></tr></thead>';
$children = $this->_service->children->listChildren($folderId, $parameters);
foreach ($children->getItems() as $child) {
$i++; if($i == 1 && $in_type == 'radio'){$checked = 'checked';}else{$checked = '';}
if($maxResults != $i && $maxResults > 30 && $i % 20 == 0){sleep(1);}
$fileId = $child->getId();
$file = $this->_service->files->get($fileId); //getDescription getMimeType
$file_mime = $file->getMimeType();
$file_title = $file->getTitle();
$file_desc = $file->getDescription();
$file_icon = $file->getIconLink();
$file_md5 = $file->getMd5Checksum();
$file_size = size_format($file->getFileSize(), 2);
$file_thumb = $file->getThumbnailLink(); // str_replace('=s220', '=s300', $file->getThumbnailLink());
$view = 'Download';
$file_pptis = '';
if(strpos($file_mime, 'image') !== false){
$view = 'View';
$properties = $this->_service->properties->listProperties($fileId);
$getfile_pptis = $properties->getItems();
if(count($getfile_pptis) > 0){
$file_pptis = $getfile_pptis[0]->getValue();
// selfWidth:xx selfHeight:xx thumbId:xxx thumbWidth:xx thumbHeight:xx
preg_match_all('/(\w+):("[^"]+"|\S+)/', $file_pptis, $matches);
$img_meta = array_combine($matches[1], $matches[2]);
if(array_key_exists('thumbId', $img_meta)){
$file_thumb = 'https://www.googledrive.com/host/' . $img_meta['thumbId'];
}
}
}
$valson = json_encode(array($file_mime, $file_title, $fileId, $file_desc, $folder_name, $file_pptis));
$daftarfile .= '<tbody><tr><td><input type="'.$in_type.'" name="'.$in_name.'" value="'.base64_encode($valson).'" ' . $checked . '></td><td class="kolom_file" title="' . $file_thumb . '">'.$fileId.'</td>';
$daftarfile .= '<td title="' . $file_desc . '"><img src="' . $file_icon . '" title="' . $file_mime . '"> ' . $file_title . '</td>';
$daftarfile .= '<!--<td>' . $file_desc . '</td>-->';
$daftarfile .= '<td title="md5Checksum : ' . $file_md5 . '">' . $file_size . '</td>';
$daftarfile .= '<td>' . $view . ' | Preview</td></tr>';
}
$daftarfile .= '</tbody></table></div><br/>';
}
// merangkai paginasi soretempe
$range = 5;
$showitems = ($range * 2)+1;
$hal_folderid = $gdwpm_kecing_hal[$folderId];
$halterlihat = array_search($pageToken, $hal_folderid);
if(empty($halterlihat)){$halterlihat = 1;}
$totalhal = count($hal_folderid);
if(1 != $totalhal)
{
$halsiap = '<input type="hidden" id="'.$id_max.'" value="'.$maxResults.'" /><input type="hidden" id="'.$id_folid.'" value="'.$folderId.'" />';
if($halterlihat > 2 && $halterlihat > $range+1 && $showitems < $totalhal) $halsiap .= '<button id="'.$div_hal.'" value="'.$hal_folderid[1].'">«</button>';
if($halterlihat > 1 && $showitems < $totalhal) $halsiap .= '<button id="'.$div_hal.'" value="'.$hal_folderid[$halterlihat - 1].'">‹</button>';
for ($j=1; $j <= $totalhal; $j++)
{
if (1 != $totalhal &&( !($j >= $halterlihat+$range+1 || $j <= $halterlihat-$range-1) || $totalhal <= $showitems ))
{
if($halterlihat == $j && $pageTokenInput != ''){$disable_butt = ' disabled';}else{$disable_butt = '';}
$halsiap .= '<button id="'.$div_hal.'" value="'.$hal_folderid[$j].'"'.$disable_butt.'>'.$j.'</button>';
}
}
if ($halterlihat < $totalhal && $showitems < $totalhal) $halsiap .= '<button id="'.$div_hal.'" value="'.$hal_folderid[$halterlihat + 1].'">›</button>';
if ($halterlihat < $totalhal-1 && $halterlihat+$range-1 < $totalhal && $showitems < $totalhal) $halsiap .= '<button id="'.$div_hal.'" value="'.$hal_folderid[$totalhal].'">»</button>';
}
$vaginasi = '<div id="'.$div_pagi.'">'.$halsiap.'</div>';
$daftarfile .= $vaginasi;
if($i == 0 && $totalhal > 1 && $halterlihat == $totalhal){$daftarfile = $vaginasi;}
return array($daftarfile, $i, $totalhal, $halterlihat);//, $halterlihat, $totalhal);//items, items onpage, currentpage, totalpage
}
}
?>
As discussed in Upload Files, for reliable transfer especially important with larger files, using Resumable upload is a good strategy to use for most applications, since it also works for smaller files at the cost of one additional HTTP request per upload.
Additionally, apps that use resumable upload need to have code to resume an interrupted upload. If an upload is interrupted, find out how much data was successfully received, and then resume the upload starting from that point which is one of the good advantages of this uploading type.
For more information and steps in using resumable upload, kindly try going through given documentations above.
What I am trying to put images where my folder is generate from "$tablename", but fail to bring the image there. How do I store the uploaded files ?
I like to upload images from my form.
<input type="file" id="file" name="files" multiple />
No matter which of those upload techniques I use is not good to use, to save the file to a specific location on the server.
If you have an idea how to do this problem please.
here is the mkdir code. The code is works fine.
<?php
$tablename = "fisa";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die("" . mysql_error() . "" . $qShowStatus);
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "$next_increment";
$tablename = (string) ("$next_increment");
$year = date("Y");
$month = date("m");
$day = date("d");
If (!file_exists($year)) {
$createsyear = mkdir("$year", 0777);
} else {
If (!file_exists("$year/$month")) {
$createsmonth = mkdir("$year/$month", 0777);
} else {
If (!file_exists("$year/$month/$day")) {
$createsday = mkdir("$year/$month/$day", 0777);
} else {
If (!file_exists($year / $month / $day / $tablename)) {
$createsday = mkdir("$year/$month/$day/$tablename", 0777);
} else {
//dada
}
}
}
}
?>
Thank You.
Here I give basic example for file upload.
in HTML
<form action="phpfilename.php" method="post" enctype="multipart/form-data" >
<input type="file" name="files" />
<input type="submit" name="submit" />
</form>
In PHP
<?php
if(isset($_POST['submit']))
{
$path = $_FILES["files"]["name"];
$target = "$year/$month/$day/$tablename/$path"; //this is your path where image need to be saved
move_uploaded_file($_FILES["files"]["tmp_name"], $target);
}
?>
I fix the problem
<?php
$tablename = "fisa";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die ( "" . mysql_error() . "" . $qShowStatus );
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "$next_increment";
$tablename = (string)("$next_increment");
$year = date("Y");
$month = date("m");
$day = date("d");
If(!file_exists($year)){
$createsyear = mkdir("$year", 0777);
}
else
{
If(!file_exists("$year/$month")){
$createsmonth = mkdir("$year/$month", 0777);
}
else
{
If(!file_exists("$year/$month/$day")){
$createsday = mkdir("$year/$month/$day", 0777);
}
else
{
If(!file_exists($year/$month/$day/$tablename)){
$createsday = mkdir("$year/$month/$day/$tablename/", 0777);
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*100; //100 kb
$target = "$year/$month/$day/$tablename/";
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to execute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $target.$name)) {
$count++; // Number of successfully uploaded files
}
}
}
}
}
}
else
{
}
}
}
}
?>