<?php
require_once(dirname(__FILE__) . '/connectionClass.php');
class webcamClass
{
public $imageFolder = "ABC";
//This function will create a new name for every image captured using the current data and time.
public function getNameWithPath()
{
$name = $this->imageFolder . date('D/M/Y') . ".jpg";
return $name;
}
//function will get the image data and save it to the provided path with the name and save it to the database
public function showImage()
{
$file = file_put_contents($this->getNameWithPath(), file_get_contents('php://input'));
if (!$file) {
return "ERROR: Failed to write data to " . $this->getNameWithPath() . ", \n";
} else {
$this->saveImageToDatabase($this->getNameWithPath()); // this line is for saving image to database
return $this->getNameWithPath();
}
}
//function for changing the image to base64
public function changeImagetoBase64($image)
{
$path = $image;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
}
public function saveImageToDatabase($imageurl)
{
$image = $imageurl;
// $image= $this->changeImagetoBase64($image); //if you want to go for base64 encode than enable this line
if ($image) {
$query = "Insert into snapshot (Image) values('$image')";
$result = $this->query($query);
if ($result) {
return "Image saved to database";
} else {
return "Image not saved to database";
}
}
}
}
Not able to access a file using file_put_contents.
Check your file path. For example you access to ABCSat/Jun/2017.jpg! I think you try to access ABC/Sat/Jun/2017.jpg, so add / or DIRECTORY_SEPARATOR at the end of $image_folder:
<?php
require_once(dirname(__FILE__) . '/connectionClass.php');
class webcamClass
{
public $imageFolder = "ABC" . DIRECTORY_SEPARATOR;
//This function will create a new name for every image captured using the current data and time.
public function createDirectories($file_name = ''){
$directories = explode('/', $file_name);
$dir_path = '';
for($i = 0; $i < count($directories) - 1; $i++) {
$dir_path .= $directories[$i] . DIRECTORY_SEPARATOR;
if(!file_exists($dir_path)) {
mkdir($dir_path);
}
}
}
public function getNameWithPath()
{
$name = $this->imageFolder . date('D/M/Y') . ".jpg";
$this->createDirectories($name);
return $name;
}
//function will get the image data and save it to the provided path with the name and save it to the database
public function showImage()
{
$file = file_put_contents($this->getNameWithPath(), file_get_contents('php://input'));
if (!$file) {
return "ERROR: Failed to write data to " . $this->getNameWithPath() . ", \n";
} else {
$this->saveImageToDatabase($this->getNameWithPath()); // this line is for saving image to database
return $this->getNameWithPath();
}
}
//function for changing the image to base64
public function changeImagetoBase64($image)
{
$path = $image;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
}
public function saveImageToDatabase($imageurl)
{
$image = $imageurl;
// $image= $this->changeImagetoBase64($image); //if you want to go for base64 encode than enable this line
if ($image) {
$query = "Insert into snapshot (Image) values('$image')";
$result = $this->query($query);
if ($result) {
return "Image saved to database";
} else {
return "Image not saved to database";
}
}
}
public function query($query) {
$dbObj = new dbObj();
$conn = $dbObj->getConnstring();
return mysqli_query($conn, $query);
}
}
Related
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
I am making basic photo hosting, just to upload images and resize them.
Everything works fine, I also have added accept="image/*" for my File upload button, but it is still possible to upload other files. So in my PHP code I check whether it is image or other file, so if it is not image, I basically remove it. But I have a problem. If user uploads "index.php" file, my index file on server will be overwritten and as my code should do, it removes "index.php" so. basically self destruction.
Is there way to restrict file upload before file is actually uploaded on server?
Or at least, is there way to change root directory of file that is
uploaded?
I don't think that JavaScript or HTML restriction will do anything, because "hackermans" can change it easily in inspect element.
class Upload {
private $destinationPath;
private $errorMessage;
private $extensions;
private $allowAll;
private $maxSize;
private $uploadName;
private $seqnence;
private $imageSeq;
public $name = 'Uploader';
public $useTable = false;
function setDir($path) {
$this->destinationPath = $path;
$this->allowAll = false;
}
function allowAllFormats() {
$this->allowAll = true;
}
function setMaxSize($sizeMB) {
$this->maxSize = $sizeMB * (1024 * 1024);
}
function setExtensions($options) {
$this->extensions = $options;
}
function setSameFileName() {
$this->sameFileName = true;
$this->sameName = true;
}
function getExtension($string) {
$ext = "";
try {
$parts = explode(".", $string);
$ext = strtolower($parts[count($parts) - 1]);
} catch (Exception $c) {
$ext = "";
}
return $ext;
}
function setMessage($message) {
$this->errorMessage = $message;
}
function getMessage() {
return $this->errorMessage;
}
function getUploadName() {
return $this->uploadName;
}
function setSequence($seq) {
$this->imageSeq = $seq;
}
function getRandom() {
return strtotime(date('Y-m-d H:i:s')) . rand(1111, 9999) . rand(11, 99) . rand(111, 999);
}
function sameName($true) {
$this->sameName = $true;
}
function uploadFile($fileBrowse) {
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if (!is_dir($this->destinationPath)) {
$this->setMessage("Destination folder is not a directory ");
} else if (!is_writable($this->destinationPath)) {
$this->setMessage("Destination is not writable !");
} else if (empty($name)) {
$this->setMessage("File not selected ");
} else if ($size > $this->maxSize) {
$this->setMessage("Too large file !");
} else if ($this->allowAll || (!$this->allowAll && in_array($ext, $this->extensions))) {
if ($this->sameName == false) {
$this->uploadName = $this->imageSeq . "-" . substr(md5(rand(1111, 9999)), 0, 8) . $this->getRandom() . rand(1111, 1000) . rand(99, 9999) . "." . $ext;
} else {
$this->uploadName = $name;
}
if (move_uploaded_file($_FILES[$fileBrowse]["tmp_name"], $this->destinationPath . $this->uploadName)) {
$result = true;
} else {
$this->setMessage("Upload failed , try later !");
}
} else {
$this->setMessage("Invalid file format !");
}
return $result;
}
function deleteUploaded() {
unlink($this->destinationPath . $this->uploadName);
}
}
How to use it :
function callMe(){
$uploader = new Upload();
$directory = "NAMEDIR"
if(!is_dir($directory)){
mkdir($directory);
}
$uploader->setDir($directory);
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
$uploader->sameName(true);
if($uploader->uploadFile('file')){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
echo json_encode(array("success"=>true,"message"=>"Success Add","image"=>$directory.$image,"image_upload"=>$image));
}else{//upload failed
echo json_encode(array("success"=>false,"message"=>$uploader->getMessage(),"image"=>""));
}
}
callMe();
I'm trying to upload a file in my symfony2 project by using a simple Form.
I did read the official doc of symfony but Id want only move my file to directory and update a field in a db table (called user) not create an entity for the file. I use an example I succeed to upload but in .tmp extension (ex. phpXXX.tmp). Any Ideas please.
here my code :
Document.php:
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class Document
{
private $file;
private $subDir;
private $filePersistencePath;
/** #var string */
protected static $uploadDirectory = '%kernel.root_dir%/../styles/images';
static public function setUploadDirectory($dir)
{
self::$uploadDirectory = $dir;
}
static public function getUploadDirectory()
{
if (self::$uploadDirectory === null) {
throw new \RuntimeException("Trying to access upload directory for profile files");
}
return self::$uploadDirectory;
}
public function setSubDirectory($dir)
{
$this->subDir = $dir;
}
public function getSubDirectory()
{
if ($this->subDir === null) {
throw new \RuntimeException("Trying to access sub directory for profile files");
}
return $this->subDir;
}
public function setFile(File $file)
{
$this->file = $file;
}
public function getFile()
{
return new File(self::getUploadDirectory() . "/" . $this->filePersistencePath);
}
public function getOriginalFileName()
{
return $this->file->getClientOriginalName();
}
public function getFilePersistencePath()
{
return $this->filePersistencePath;
}
public function processFile()
{
if (! ($this->file instanceof UploadedFile) ) {
return false;
}
$uploadFileMover = new UploadFileMover();
$this->filePersistencePath = $uploadFileMover->moveUploadedFile($this->file, self::getUploadDirectory(),$this->subDir);
}
}
UploadFileMover
use Symfony\Component\HttpFoundation\File\UploadedFile;
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath, $relativePath) {
$originalName = $file->getFilename();
// use filemtime() to have a more determenistic way to determine the subpath, otherwise its hard to test.
// $relativePath = date('Y-m', filemtime($file->getPath()));
$targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;
$targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;
$ext = $file->getExtension();
$i = 1;
while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
if ($ext) {
$prev = $i == 1 ? "" : $i;
$targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);
} else {
$targetFilePath = $targetFilePath . $i++;
}
}
$targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath;
if (!is_dir($targetDir)) {
$ret = mkdir($targetDir, umask(), true);
if (!$ret) {
throw new \RuntimeException("Could not create target directory to move temporary file into.");
}
}
$file->move($targetDir, basename($targetFilePath));
return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
}
}
controller :
public function uploadImgAction(Request $req) {
if ($req->getMethod() == 'POST') {
$status = 'success';
$uploadedURL = '';
$message = 'Image modifiée';
$image = $req->files->get('fileselect');
if (($image instanceof UploadedFile) && ($image->getError() == '0')) {
if ($image->getSize() < 2000000) {
$originalName = $image->getClientOriginalName();
$name_array = explode('.', $originalName);
$file_type = $name_array[sizeof($name_array) - 1];
$valid_filetypes = array('jpg', 'jpeg', 'bmp', 'png');
if (in_array(strtolower($file_type), $valid_filetypes)) {
//télécharegement du fichier
//Start Uploading File
$document = new Document();
$document->setFile($image);
$document->setSubDirectory('uploads');
$document->processFile();
$uploadedURL=$uploadedURL = $document->getUploadDirectory() . DIRECTORY_SEPARATOR . $document->getSubDirectory() . DIRECTORY_SEPARATOR . $image->getBasename();
} else {
$status = 'echoue';
$message = 'Seuls les extensions png, jpg, jpeg et bmp sont acceptées';
}
} else {
$status = 'echoue';
$message = 'La taille du fichier dépasse 2MB';
}
} else {
$status = 'echoue';
$message = 'Une erreur de télechargement';
}
return $this->render('PIRecrutementBundle:xx:xxx.html.twig');
//return new Response($uploadedUrl);
} else {
return $this->render('xxxBundle:xx:xxx.html.twig');
}
}
Exactly as Tomasz Turkowski said the solution is to change the base-name of the file by its real name using $file->getClientOriginalName( in class UploadFileMover.
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath, $relativePath)
{
// $originalName = $file->getFilename();
$originalName = $file->getClientOriginalName();
// use filemtime() to have a more determenistic
Without changing anything like .tmp to some other extention or the original name, you can still store the same obtained path in DB. I think you can write a query to store the path in DB after this statement in your controller
$uploadedURL=$uploadedURL = $document->getUploadDirectory() . DIRECTORY_SEPARATOR . $document->getSubDirectory() . DIRECTORY_SEPARATOR . $image->getBasename();
By using the variable $uploadURL like
{
//in your methodAction
"Update [YOUR TABLE] SET [PATHcolomn]=".$uploadURL." WHERE USERid=".$user->getUid()." "
$path= "SELECT [PATHcolomN] FROM [YOUR TABLE] WHERE USERid=".$user->getUid()." "
$this->data['path']=$path;
return $this->data;
}
After Updating, you can fetch this path in the place of <img src= {{ path }} >
I am making image uploader and It works fine until I tryed to upload image with same name. I did recursive method in class, maybe that is problem.
I got this error:
500 Internal Server Error
Image is not big, and it works when does not exists.
Here is my upload.php file:
$upload = new Upload("post", $_FILES['file']);
$upload->upload();
And here is my Uploader.php class file:
class Upload {
protected $_type = null,
$_file = null,
$_file_name = null,
$_file_tmp = null,
$_slug = null,
$_path = null;
public function __construct($type, $file, $slug = null) {
$this->_file = $file;
$this->_file_tmp = $file['tmp_name'];
$this->_file_name = $file['name'];
$this->_slug = $slug;
if($type == "post") {
$this->_type = "post";
$config1 = '/admin/posts/images'; // Relative to domain name
$config = $_SERVER['DOCUMENT_ROOT'] . $config1; // Physical path. [Usually works fine like this]
$this->_path = $config . "/";
} else if($type == "gallery") {
$this->_type = "gallery";
$config1 = '/admin/galeries/images'; // Relative to domain name
$config = $_SERVER['DOCUMENT_ROOT'] . $config1; // Physical path. [Usually works fine like this]
$this->_path = $config . "/";
}
}
public function upload() {
$new_name = "";
if($this->_slug == null) {
$new_name = $this->_file_name;
} else {
$new_name = $this->_slug . "-" . $this->_file_name;
}
if (file_exists($this->_path.$new_name)) {
if($this->_slug != null)
$new_name = $this->_slug . "-" . rand(00,99) . "-" . $this->_file_name;
else
$new_name = rand(0000,9999) . "-" . $new_name;
// MAYBE HERE IS PROBLEM...
$this->upload();
} else {
move_uploaded_file($this->_file_tmp, $this->_path.$new_name);
return true;
}
}
As you can see my method upload() is called recursively. I am wondering if these protected variables are gone after that call.
I had to add $this->_file_name = $new_name; above $this->upload();
I have a PHP uploader on my Dedi server, the uploader works as it should, only after it uploads the files it dose not rename them from their temp names..
it comes out something like
2b4134a1f559b6da866c9febbc92d709.mp3
The uploader file.php
<?php
class file {
public $id;
public $fileName;
public $systemFilename;
public $fileType;
public $fileExtension;
public $systemUrl;
public $originalUrl;
public $thumbPath;
public $thumbUrl;
public $canHaveThumb;
public $ts;
public $size;
public $authorized;
public $knownExtensions;
public $mimeType;
public $filePath;
public function __construct() {
$this->setKnownExtensions();
}
// Check and save a new file on the disk and the database
public function uploadNewFile($files) {
$result = array(); // The variable we will send back when we have finished to check and save the file
$this->setFileName($files['Filedata']['name']);
if ($this->authorized) {
// Build the target path
$siteUrl = F3::get('siteUrl'); // Set in config.php
$uploadFolder = F3::get('uploadFolder'); // Set in config.php
$uploadUrl = $_SERVER['DOCUMENT_ROOT'] . '/' . $uploadFolder . '/';
// Get the temporary file
$tempFile = $_FILES['Filedata']['tmp_name'];
// Get a unique system name
$rand = rand(1, 414342);
$ts = time();
$systemName = md5($rand . $ts);
$this->systemFilename = $systemName . '.' . $this->fileExtension;
$this->ts = $ts;
// Clean the path
$targetFile = str_replace('//', '/', $uploadUrl) . $this->systemFilename;
// Save the file on the disk
move_uploaded_file($tempFile, $targetFile);
// Save the file in the database
DB::sql('INSERT INTO hm_files (fileName, systemFilename, fileType, time) VALUES ("' . $this->fileName . '", "' . $this->systemFilename . '", "' . $this->fileType . '", ' . $this->ts . ')');
$this->id = F3::get('DB->pdo')->lastInsertId();
// Retrieve the template for the file list
$result['tableRow'] = $this->getTableRow();
// We create a thumbnail if it is a simple image
$this->createThumb();
}
$result['file'] = $this;
return $result;
}
public function canHaveThumb() {
if ($this->fileType == 'image') {
$this->canHaveThumb = true;
} else {
$this->canHaveThumb = false;
}
return $this->canHaveThumb;
}
public function createThumb() {
if ($this->canHaveThumb()) {
$filePath = $this->getFilePath();
if (file_exists($filePath)) {
$thumbPath = site::getThumbsPath();
$thumb = new image($filePath);
$thumb->dir($thumbPath);
$thumb->width(250);
$thumb->save();
}
}
}
public function getThumbPath() {
$thumbFolderPath = site::getThumbsPath();
$this->thumbPath = $thumbFolderPath . $this->systemFilename;
if (!file_exists($this->thumbPath)) {
$this->createThumb();
}
return $this->thumbPath;
}
public function getThumbUrl() {
$base = F3::get('BASE');
$thumbsFolder = F3::get('thumbsFolder');
$this->thumbUrl = $base . '/' . $thumbsFolder . '/' . $this->systemFilename;
return $this->thumbUrl;
}
// Delete a file
public function delete() {
$filePath = $this->getFilePath();
if (file_exists($filePath)) {
unlink($filePath); // Remove the file from the hard drive
}
if ($this->canHaveThumb()) {
$thumbPath = $this->getThumbPath();
if (file_exists($thumbPath)) {
unlink($thumbPath); // Remove the thumb from the hard drive
}
}
DB::sql('DELETE FROM hm_files WHERE id = ' . $this->id); // Remove from database
}
// Set the filename and the file extension
public function setFileName($fileName) {
$this->fileName = $fileName;
$this->fileExtension = strtolower(substr(strrchr($this->fileName, '.'), 1));
$this->checkExtension();
$this->getFileType();
}
// Check if a file has an authorized extension
public function checkExtension() {
$okExtensions = F3::get('okExtensions'); // defined in config.php
if (in_array($this->fileExtension, $okExtensions)) {
$this->authorized = true;
} else {
$this->authorized = false;
}
return $this->authorized;
}
// Define the file type (eg: image, video, ...)
// Not used in this version
public function getFileType() {
$ext = $this->fileExtension;
if (isset($this->knownExtensions[$ext])) {
$this->fileType = $this->knownExtensions[$ext];
} else {
$this->fileType = 'file';
}
return $this->fileType;
}
public function getFileSize() {
$this->size = filesize($this->getFilePath());
return $this->size;
}
// Transform the filesize in kilobytes, megabytes, ... and append the unit.
public function getReadableSize() {
$bytes = $this->getFileSize();
$decimals = 2;
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . #$sz[$factor];
}
// Get the HTML for the file list
public function getTableRow() {
F3::set('file', $this);
// We check if the file exist before displaying the table row
if (file_exists($this->getFilePath())) {
$tableRow = F3::render('views/table_row.php');
return $tableRow;
} else {
return '';
}
}
// Get a file path on the server harddrive
public function getFilePath() {
$path = F3::get('rootPath');
$uploadsFolder = F3::get('uploadFolder');
$this->filePath = $path . '/' . $uploadsFolder . '/' . $this->systemFilename;
return $this->filePath;
}
public function getSystemUrl() {
$base = F3::get('BASE');
$this->systemUrl = $base . '/file/' . $this->systemFilename;
return $this->systemUrl;
}
public function getOriginalUrl() {
$siteUrl = F3::get('siteUrl');
$uploadsFolder = F3::get('uploadFolder');
$this->originalUrl = $siteUrl . '/' . $uploadsFolder . '/' . $this->systemFilename;
return $this->originalUrl;
}
public function getMime() {
$filePath = $this->getFilePath();
$finfo = new finfo(FILEINFO_MIME);
$info = $finfo->file($filePath);
return $info;
}
public function gearUp($queryResult) {
$this->id = $queryResult['id'];
$this->fileName = $queryResult['fileName'];
$this->systemFilename = $queryResult['systemFilename'];
$this->fileType = $queryResult['fileType'];
$this->ts = $queryResult['time'];
$this->getSystemUrl();
$this->getOriginalUrl();
return $this;
}
// Display a single file
public static function display($systemFilename) {
$fileQuery = DB::sql('SELECT * FROM hm_files WHERE systemFilename LIKE "' . $systemFilename . '"');
if (count($fileQuery) > 0) {
$file = new file();
$file->gearUp($fileQuery[0]);
$mime = $file->getMime();
header('Content-Disposition: inline; filename="' . $file->fileName . '"');
header('Content-type: ' . $mime);
readfile($file->getOriginalUrl());
} else {
return false;
}
}
// Build a zip of files
// You can create direct download by setting $directDownload on true.
// Important : we don't use the classic ZipArchive class of PHP. When we zip large files it produces errors.
// We use the pclzip class. Doc: http://www.phpconcept.net/pclzip/
public static function serveZip($idsArray, $token, $directDownload = true) {
if (count($idsArray) > 0) {
$rootPath = F3::get('rootPath');
$zipPath = $rootPath . '/zips/archive-' . $token . '.zip';
$zipper = new pclzip($zipPath);
foreach ($idsArray as $id) {
$file = file::fetch($id);
$filePath = $file->getFilePath();
$filesArray = array(
array(PCLZIP_ATT_FILE_NAME => $filePath,
PCLZIP_ATT_FILE_NEW_FULL_NAME => $file->fileName)
);
$zipper->add($filesArray, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_ALL_PATH);
}
// We set the cookie to track the end of zipping
setcookie('multiUp', $token);
// If this is a direct download we serve the zip in the browser and then destroy the zipfile on the server
if ($directDownload) {
$zipContent = file_get_contents($zipPath);
header('Content-Disposition: attachment; filename="archive.zip"');
header('Content-type: application/zip');
echo $zipContent;
unlink($zipPath);
}
}
}
// Get info for a single file
public static function fetch($id) {
$fileQuery = DB::sql('SELECT * FROM hm_files WHERE id = ' . $id);
if (count($fileQuery) > 0) {
$file = new file();
$file->gearUp($fileQuery[0]);
return $file;
} else {
return false;
}
}
// Fetch all files in the database
public static function fetchAll() {
$files = array();
$filesId = DB::sql('SELECT id FROM hm_files ORDER BY time DESC');
foreach ($filesId as $fileId) {
$file = file::fetch($fileId['id']);
if ($file) {
$files[] = $file;
}
}
return $files;
}
// Creates families for file extensions
// Not used in this version. Might be usefull to create icons
private function setKnownExtensions() {
$fileTypes = array();
// DOCUMENTS
$fileTypes['pdf'] = 'pdf';
// PLAIN TEXT
$fileTypes['txt'] = 'text';
$fileTypes['rtf'] = 'text';
$fileTypes['as'] = 'text';
$fileTypes['xml'] = 'text';
$fileTypes['html'] = 'text';
$fileTypes['htm'] = 'text';
$fileTypes['js'] = 'text';
$fileTypes['php'] = 'text';
$fileTypes['asp'] = 'text';
$fileTypes['py'] = 'text';
$fileTypes['sql'] = 'text';
$fileTypes['css'] = 'text';
// ARCHIVES
$fileTypes['zip'] = 'archive';
$fileTypes['rar'] = 'archive';
$fileTypes['7zip'] = 'archive';
$fileTypes['gzip'] = 'archive';
$fileTypes['gz'] = 'archive';
$fileTypes['tgz'] = 'archive';
$fileTypes['ace'] = 'archive';
$fileTypes['arc'] = 'archive';
// EXCEL
$fileTypes['xls'] = 'excel';
$fileTypes['xlsx'] = 'excel';
$fileTypes['xlsm'] = 'excel';
$fileTypes['ods'] = 'excel';
$fileTypes['ots'] = 'excel';
$fileTypes['csv'] = 'excel';
$fileTypes['numbers'] = 'excel';
// WORD
$fileTypes['doc'] = 'word';
$fileTypes['docx'] = 'word';
$fileTypes['odt'] = 'word';
$fileTypes['ott'] = 'word';
$fileTypes['pages'] = 'word';
// POWERPOINT
$fileTypes['ppt'] = 'powerpoint';
$fileTypes['pptx'] = 'powerpoint';
$fileTypes['odp'] = 'powerpoint';
$fileTypes['otp'] = 'powerpoint';
$fileTypes['key'] = 'powerpoint';
// IMAGES
$fileTypes['png'] = 'image';
$fileTypes['gif'] = 'image';
$fileTypes['jpg'] = 'image';
$fileTypes['jpeg'] = 'image';
// UNCOMMON IMAGEs
$fileTypes['svg'] = 'rareimage';
$fileTypes['svgz'] = 'rareimage';
$fileTypes['jpf'] = 'rareimage';
$fileTypes['bmp'] = 'rareimage';
$fileTypes['eps'] = 'rareimage';
$fileTypes['tif'] = 'rareimage';
$fileTypes['tiff'] = 'rareimage';
$fileTypes['raw'] = 'rareimage';
$fileTypes['pbm'] = 'rareimage';
$fileTypes['tga'] = 'rareimage';
$fileTypes['cdr'] = 'rareimage';
// "WORKING" IMAGES
$fileTypes['psd'] = 'photoshop';
$fileTypes['psb'] = 'photoshop';
$fileTypes['ai'] = 'illustrator';
$fileTypes['ait'] = 'illustrator';
$fileTypes['fxg'] = 'illustrator';
$fileTypes['cgm'] = 'illustrator';
$fileTypes['indd'] = 'indesign';
$fileTypes['idml'] = 'indesign';
$fileTypes['fla'] = 'flash';
$fileTypes['swf'] = 'flash';
$fileTypes['xfl'] = 'flash';
$fileTypes['prproj'] = 'premiere';
$fileTypes['aep'] = 'aftereffect';
// 3D
$fileTypes['3ds'] = '3d';
$fileTypes['dwg'] = '3d';
$fileTypes['dxf'] = '3d';
$fileTypes['max'] = '3d';
// SOUND / MUSIC
$fileTypes['mp3'] = 'music';
$fileTypes['wav'] = 'music';
$fileTypes['flac'] = 'music';
$fileTypes['aac'] = 'music';
$fileTypes['aiff'] = 'music';
$fileTypes['aif'] = 'music';
$fileTypes['aifc'] = 'music';
$fileTypes['wma'] = 'music';
$fileTypes['au'] = 'music';
$fileTypes['snd'] = 'music';
$fileTypes['aa3'] = 'music';
$fileTypes['oma'] = 'music';
$fileTypes['at3'] = 'music';
$fileTypes['m3u'] = 'music';
$fileTypes['amr'] = 'music';
$fileTypes['cda'] = 'music';
//VIDEO
$fileTypes['avi'] = 'video';
$fileTypes['flv'] = 'video';
$fileTypes['m4v'] = 'video';
$fileTypes['mkv'] = 'video';
$fileTypes['mov'] = 'video';
$fileTypes['mpeg'] = 'video';
$fileTypes['mpg'] = 'video';
$fileTypes['mpe'] = 'video';
$fileTypes['mp4'] = 'video';
$fileTypes['3gp'] = 'video';
$fileTypes['aep'] = 'video';
$this->knownExtensions = $fileTypes;
}
}
?>
It worked fine on managed servers that have CPanel thats why i suspect my PHP.ini file? (i installed the server myself)
If it is the .ini file, what should i look for?
The script changes the file names on purpose, to guarantee they are always unique. This prevents a file from getting overwritten if someone uploads a file with the same file name. If you really want to retain the original name, you can change this line:
$targetFile = str_replace('//', '/', $uploadUrl) . $this->systemFilename;
to this:
$targetFile = str_replace('//', '/', $uploadUrl) . $this->fileName;
Note that although the script assigns a unique name to each uploaded file, it still retains the original name in the database table as shown here:
DB::sql('INSERT INTO hm_files (fileName, systemFilename, fileType, time) VALUES ("' . $this->fileName . '", "' . $this->systemFilename . '", "' . $this->fileType . '", ' . $this->ts . ')');