Image upload with zend framework - php

I am new to the zend framework. I need to create a user registration with image upload. I have done that. My registration controller and upload controller works. Currently all images are uploading to uploads/user-images/ in public folder. But my actual requirement is, I have to create a specific folder for each user based on their user ID and need to upload their photos to that folder. Also, I need to store that image path in a DB as actualname_current_Timestamp_width_height.extension, but I don't know how to do this. Here I am including my controller codes:
<?php
/**
* PhotoController class file
*
* This file contains a class for PhotoController
*
* #category Zend
* #package Zend_Controller
*
*/
class PhotoController extends Daddara_Controller_BaseController
{
public $session;
function init()
{
parent::init();
$this->view->headScript()->appendFile('/resources/js/upload.js');
$this->view->headScript()->appendFile('/resources/js/jquery.min.js');
$this->view->headScript()->appendFile('/resources/js/jquery.wallform.js');
$this->view->headScript()->appendFile('/resources/js/modernizr.custom.js');
// $this->view->headScript()->appendFile('/resources/js/lightbox/jquery-1.10.2.min.js');
// $this->view->headScript()->appendFile('/resources/js/lightbox/lightbox-2.6.min.js');
}
function indexAction()
{
$this->_forward('upload');
}
/**
* Upload Action action
*
*/
public function uploadAction()
{
$path = "uploads/user-images/";
$shortPath = "uploads/user-images/resize/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$em = $this->getEntityManager();
//User Id
$userId = $em->getRepository("Models\User")->findOneBy(array('id' => $this->currentUser->id));
//Registration Id
$registrationId = $em->getRepository("Models\Registration")->findOneBy(array('user' => $this->currentUser->id));
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if($this->getRequest()->isPost()){
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
//echo $ext;exit;
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $ext), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
if($ext=="jpg" || $ext=="jpeg" )
{
$uploadedfile = $path.$actual_image_name;
$src = imagecreatefromjpeg($uploadedfile);
}
else if($ext=="png")
{
$uploadedfile = $path.$actual_image_name;
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=160;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = "uploads/user-images/resize/". $actual_image_name;
imagejpeg($tmp,$filename,100);
$photos = new Models\ProfilePhotos();
$photos->setUser($userId)
->setRegistration($registrationId)
->setPhoto($path.$actual_image_name)
->setShortImage($shortPath.$actual_image_name)
->setAddedOn();
$em->persist($photos);
$em->flush();
echo "<img src='/uploads/user-images/resize/".$actual_image_name."' class='preview'>";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
}
}
public function listAction()
{
$em = $this->getEntityManager();
$photo = $em->getRepository('Models\ProfilePhotos')->findBy(array('user' => $this->currentUser->id));
//print_r($image);exit;
$this->view->photo = $photo;
}
/**
* delete function
*/
function deleteAction()
{
$deleteId = $this->getRequest()->getParam('id');
if(empty($deleteId)){
throw new Zend_Controller_Exception("Page not found", 404);
}
$em = $this->getEntityManager();
$del = $em->find("Models\ProfilePhotos", $deleteId);
$em->remove($del);
$em->flush();
$this->addMessage('Data Deleted Successfully "');
$this->_redirect('/photo/list');
}
}

You can create a folder with the command mkdir():
if(mkdir(APPLICATION_PATH . '/public/uploads/' . $userId)){
//dir created
}
You can move a file with copy() and unlink():
if(copy(APPLICATION_PATH . '/public/uploads/' .$filename,
APPLICATION_PATH . '/public/uploads/' .$userId .'/' .$newfilename)) {
unlink(APPLICATION_PATH . '/public/uploads/' . $filename);
}

I have tried something like the following code and thats worked for me. Now i can upload images to a purticular folder for each user based on their user id. Hope this will help someone else.. :-)
$path = "uploads/user-images/";
$em = $this->getEntityManager();
//User Id
$userId = $em->getRepository("Models\User")->findOneBy(array('id' => $this->currentUser->id));
$user_path = "$path".$userId->getId()."/";
if (!file_exists($user_path)) mkdir($user_path, 0777);

Related

Restrict ".php" File upload

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();

Upload a file using Symfony2 and a simple form

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 }} >

php session id changing for no reason

I'm currently using Valum's File Uploader on Wamp and everything had been going smoothly until now. Inside the uploader's php file I made it save the uploaded file to the current user's folder by reading from the session data to get the current user. However, it is creating a new session everytime I call it for some unknown reason. I have checked the cookies and they return the correct session. I also checked the session_id() and it also returns the correct session. However, it always creates a new session for some reason. I even explicitly set the session id with the session_id() function. However, none of this works for some reason. It's returning the correct id but it doesn't save to the correct id. Anyone know why this is happening?
Below is the modified Uploader.php code.
<?php
//if (!empty($_COOKIE['PHPSESSID'])){
session_id($_COOKIE['PHPSESSID']);
session_start();
//}
if(isset($_SESSION['id'])){
/**
* Handle file uploads via XMLHttpRequest
*/
class qqUploadedFileXhr {
/**
* Save the file to the specified path
* #return boolean TRUE on success
*/
function save($path) {
$input = fopen("php://input", "r");
$temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp);
fclose($input);
if ($realSize != $this->getSize()){
return false;
}
$target = fopen($path, "w");
fseek($temp, 0, SEEK_SET);
stream_copy_to_stream($temp, $target);
fclose($target);
return true;
}
function getName() {
return $_GET['qqfile'];
}
function getSize() {
if (isset($_SERVER["CONTENT_LENGTH"])){
return (int)$_SERVER["CONTENT_LENGTH"];
} else {
throw new Exception('Getting content length is not supported.');
}
}
}
/**
* Handle file uploads via regular form post (uses the $_FILES array)
*/
class qqUploadedFileForm {
/**
* Save the file to the specified path
* #return boolean TRUE on success
*/
function save($path) {
if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)){
return false;
}
return true;
}
function getName() {
return $_FILES['qqfile']['name'];
}
function getSize() {
return $_FILES['qqfile']['size'];
}
}
class qqFileUploader {
private $allowedExtensions = array();
private $sizeLimit = 10485760;
private $file;
function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){
$allowedExtensions = array_map("strtolower", $allowedExtensions);
$this->allowedExtensions = $allowedExtensions;
$this->sizeLimit = $sizeLimit;
$this->checkServerSettings();
if (isset($_GET['qqfile'])) {
$this->file = new qqUploadedFileXhr();
} elseif (isset($_FILES['qqfile'])) {
$this->file = new qqUploadedFileForm();
} else {
$this->file = false;
}
}
private function checkServerSettings(){
$postSize = $this->toBytes(ini_get('post_max_size'));
$uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
$size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
die("{'error':'increase post_max_size and upload_max_filesize to $size - Upload size: $uploadSize, postSize: $postSize, sizeLimit: $this->sizeLimit'}");
}
}
private function toBytes($str){
$val = trim($str);
$last = strtolower($str[strlen($str)-1]);
switch($last) {
case 'g': $val *= 1024;
case 'm': $val *= 1024;
case 'k': $val *= 1024;
}
return $val;
}
/**
* Returns array('success'=>true) or array('error'=>'error message')
*/
function handleUpload($uploadDirectory, $replaceOldFile = FALSE){
if (!is_writable($uploadDirectory)){
return array('error' => "Server error. Upload directory isn't writable.");
}
if (!$this->file){
return array('error' => 'No files were uploaded.');
}
$size = $this->file->getSize();
if ($size == 0) {
return array('error' => 'File is empty');
}
if ($size > $this->sizeLimit) {
return array('error' => 'File is too large');
}
$pathinfo = pathinfo($this->file->getName());
$filename = $pathinfo['filename'];
//$filename = md5(uniqid());
$ext = $pathinfo['extension'];
if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
$these = implode(', ', $this->allowedExtensions);
return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
}
if(!$replaceOldFile){
/// don't overwrite previous files that were uploaded
while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
$filename .= rand(10, 99);
}
}
if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){
return array('success'=>true,'file'=>$filename . '.' . $ext);
} else {
return array('error'=> 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered');
}
}
}
// list of valid extensions, ex. array("jpeg", "xml", "bmp")
$allowedExtensions = array();
// max file size in bytes
$sizeLimit = 8 * 1024 * 1024;
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload("../users/".$_SESSION['id']."/uploads/");
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
}else{
echo json_encode(array('error'=>session_id()));
//echo '{"error":"You are not logged in. Please log in to upload files."}';
}
?>
Update
I now see something a bit unusual. It seems like it's copying the session and leaving behind the old session file - just like what session_regnerate_id() does. However, I don't have that anywhere in my code.
I had the same problem, and in my case inserting this line...
ini_set('session.use_strict_mode', 0);
...right before session_start() solved it.

files arent creating aswell as folder structures not generating

im having trouble trying to get the file to upload. the aim is it to create a directory struction based on the work id, but its not creating the folder or uploading the file but it is returning that it has succeeded but also failed, ive spent the past few day trying to fix it but to no avail, can anyone see what is wrong with it or point me in the right direction
<?php
/**
* Handle file uploads via XMLHttpRequest
*/
class qqUploadedFileXhr {
/**
* Save the file to the specified path
* #return boolean TRUE on success
*/
function save($path) {
$input = fopen("php://input", "r");
$temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp);
fclose($input);
if ($realSize != $this->getSize()) {
return false;
}
$target = fopen($path, "w");
fseek($temp, 0, SEEK_SET);
stream_copy_to_stream($temp, $target);
fclose($target);
return true;
}
function getName() {
return $_GET['qqfile'];
}
function getSize() {
if (isset($_SERVER["CONTENT_LENGTH"])) {
return (int) $_SERVER["CONTENT_LENGTH"];
} else {
throw new Exception('Getting content length is not supported.');
}
}
}
/**
* Handle file uploads via regular form post (uses the $_FILES array)
*/
class qqUploadedFileForm {
/**
* Save the file to the specified path
* #return boolean TRUE on success
*/
function save($path) {
if (!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)) {
return false;
}
return true;
}
function getName() {
return $_FILES['qqfile']['name'];
}
function getSize() {
return $_FILES['qqfile']['size'];
}
}
class qqFileUploader {
private $allowedExtensions = array();
private $sizeLimit = 10485760;
private $file;
function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760) {
$allowedExtensions = array_map("strtolower", $allowedExtensions);
$this->allowedExtensions = $allowedExtensions;
$this->sizeLimit = $sizeLimit;
$this->checkServerSettings();
if (isset($_GET['qqfile'])) {
$this->file = new qqUploadedFileXhr();
} elseif (isset($_FILES['qqfile'])) {
$this->file = new qqUploadedFileForm();
} else {
$this->file = false;
}
}
private function checkServerSettings() {
$postSize = $this->toBytes(ini_get('post_max_size'));
$uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit) {
$size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
die("{'error':'increase post_max_size and upload_max_filesize to $size'}");
}
}
private function toBytes($str) {
$val = trim($str);
$last = strtolower($str[strlen($str) - 1]);
switch ($last) {
case 'g': $val *= 1024;
case 'm': $val *= 1024;
case 'k': $val *= 1024;
}
return $val;
}
/**
* Returns array('success'=>true) or array('error'=>'error message')
*/
function handleUpload($uploadDirectory, $replaceOldFile = FALSE) {
if (!is_writable($uploadDirectory)) {
return array('error' => "Server error. Upload directory isn't writable.");
}
if (!$this->file) {
return array('error' => 'No files were uploaded.');
}
$size = $this->file->getSize();
if ($size == 0) {
return array('error' => 'File is empty');
}
if ($size > $this->sizeLimit) {
return array('error' => 'File is too large');
}
$pathinfo = pathinfo($this->file->getName());
$filename = $pathinfo['filename'];
//$filename = md5(uniqid());
$ext = $pathinfo['extension'];
if ($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)) {
$these = implode(', ', $this->allowedExtensions);
return array('error' => 'File has an invalid extension, it should be one of ' . $these . '.');
}
if (!$replaceOldFile) {
/// don't overwrite previous files that were uploaded
while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
$filename .= rand(10, 99);
}
}
if ($this->file->save($uploadDirectory . $filename . '.' . $ext)) {
return array('success' => true);
} else {
return array('error' => 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered');
}
}
}
// list of valid extensions, ex. array("jpeg", "xml", "bmp")
$allowedExtensions = array();
// max file size in bytes
$sizeLimit = 10 * 1024 * 1024;
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
//creates new folder if needed
$jid = $_GET['jobId'];
$fileType = $_GET['imgType'];
$dir = '\\JobData\\' . $jid . '\\' . $fileType . '\\' . '/n';
echo $dir;
//checks if directory exists if not creates it.
if (is_dir($dir)) {
$result = $uploader->handleUpload($dir);
} else {
if(!mkdir($dir,0,true))
{
die('Failed to create folders');
}
$result = $uploader->handleUpload($dir);
}
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
?>

PHP class for uploading files

I'm trying to upload file using this PHP class available at http://www.finalwebsites.com/snippets.php?id=7 (to view the codes for the class http://pastebin.com/sqbMw4sR)
And I've the following codes in the upload processing file
$max_size = 1024*100; // the max. size for uploading
$my_upload = new file_upload;
// upload directory
$my_upload->upload_dir = HOME_PATH."users/";
// allowed extensions
$my_upload->extensions = array(".png", ".jpeg", ".jpg", ".gif");
$my_upload->max_length_filename = 50;
$my_upload->rename_file = true;
$new_name = "testing" . time();
if(isset($Submit)) {
$my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
$my_upload->the_file = $_FILES['upload']['name'];
$my_upload->http_error = $_FILES['upload']['error'];
$my_upload->the_mime_type = $_FILES['upload']['type'];
// because only a checked checkboxes is true
$r = $_POST['replace'];
$my_upload->replace = (isset($r)) ? $r : "n";
// use this boolean to check for a valid filename
$a = $_POST['check'];
$my_upload->do_filename_check = (isset($a)) ? $a : "n";
if ($my_upload->upload($new_name)) {
// new name is an additional filename information,
//use this to rename the uploaded file
$full_path = $my_upload->upload_dir.$my_upload->file_copy;
// just some information about the uploaded file
$info = $my_upload->get_uploaded_file_info($full_path);
// ... or do something like insert the filename to the database
}
}
$error = $my_upload->show_error_string();
According to my understanding, the file should've been uploaded but it neither throws any error nor it is uploaded.
I'm calling this file using ajaxForm (jquery plugin http://malsup.com/jquery/form/#file-upload).
Can anyone please point out what is wrong here?
Here is a new Uploader class
Save the following block as Uploader.php
<?php
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $allowAll;
private $maxSize;
private $uploadName;
private $seqnence;
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);
}
}
?>
Now upload files using Uploader class.
Use following code . Code block is self explanatory .
<?php
$uploader = new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
if($uploader->uploadFile('txtFile')){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
?>
File uploaded to extension named folder in "upload" folder.
HTML:
<form method="post" action="test_act.php" enctype="multipart/form-data">
<div>
<span>Choose file</span>
<input type="file" name="fileToUpload" id="fileToUpload">
<br/>
<input type="submit" name="fupload" id="fupload">
</div>
</form>
test_act.php (Form Action)
<?php
include ("test_cls.php");
if(isset($_POST['fupload']))
{
$dirpath="upload";
$uploader = new Uploader();
$uploader->setExtensions(array('jpg','jpeg','png','gif','doc','docx')); //allowed extensions list//
$uploader->setMaxSize(1); //set max file size to be allowed in MB//
$uploader->setDir($dirpath);
if($uploader->uploadFile('fileToUpload')) //txtFile is the filebrowse element name //
{
$suc_file = $uploader->getUploadName(); //get uploaded file name, renames on upload//
echo $suc_file." successfully uploaded";
}
else //upload failed
echo $uploader->getMessage(); //get upload error message
}
?>
test_cls.php (class):
<?php
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $maxSize;
private $uploadName;
public $name='Uploader';
function setDir($path){
$this->destinationPath = $path;
}
function setMaxSize($sizeMB){
$this->maxSize = $sizeMB * (1024*1024);
}
function setExtensions($options){
$this->extensions = $options;
}
function setMessage($message){
$this->errorMessage = $message;
}
function getMessage(){
return $this->errorMessage;
}
function getUploadName(){
return $this->uploadName;
}
function uploadFile($fileBrowse){
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = pathinfo($name,PATHINFO_EXTENSION);
$this->uploadName= $name;
if(empty($name))
{
$this->setMessage("File not selected ");
}
else if($size>$this->maxSize)
{
$this->setMessage("Too large file !");
}
else if(in_array($ext,$this->extensions))
{
if(!is_dir($this->destinationPath))
mkdir($this->destinationPath);
if(!is_dir($this->destinationPath.'/'.$ext))
mkdir($this->destinationPath.'/'.$ext);
if(file_exists($this->destinationPath.'/'.$ext.'/'.$this->uploadName))
$this->setMessage("File already exists. !");
else if(!is_writable($this->destinationPath.'/'.$ext))
$this->setMessage("Destination is not writable !");
else
{
if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.'/'.$ext.'/'.$this->uploadName))
{
$result = true;
}
else
{
$this->setMessage("Upload failed , try later !");
}
}
}
else
{
$this->setMessage("Invalid file format !");
}
return $result;
}
function deleteUploaded($fileBrowse){
$name = $_FILES[$fileBrowse]["name"];
$ext = pathinfo($name,PATHINFO_EXTENSION);
unlink($this->destinationPath.'/'.$ext.'/'.$this->uploadName);
}
}
?>

Categories