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 }} >
Related
I have a four image field in my form for different use. When I try to upload images on two fields image_oneand image_two sometimes it uploads image_one and sometimes only image_two
My controller code:
if(Input::file('image_one'))
{
$image_one = $post->storePostPicture($request->file('image_one'));
if($image_one !== false) {
$post->image_one = $image_one;
$post->save();
}
}
if(Input::file('image_two'))
{
$image_two = $post->storePostPicture($request->file('image_two'));
if($image_two !== false) {
$post->image_two = $image_two;
$post->save();
}
}
And my storePostPicture function in model :
public function storePostPicture($image) {
if($image instanceof \Illuminate\Http\UploadedFile && $image->isValid() && $image->isReadable()) {
$filePath = 'public/images/user' . DIRECTORY_SEPARATOR . 'post';
if(!File::exists(storage_path('app' . DIRECTORY_SEPARATOR . $filePath))) {
File::makeDirectory(storage_path('app' . DIRECTORY_SEPARATOR . $filePath), 0755, true);
}
$imageName = sha1(time().time()) . ".". $image->getClientOriginalExtension();
if($image->storeAs($filePath, $imageName) !== false) {
$path = "/storage/images/user/post/";
return $path . DIRECTORY_SEPARATOR . $imageName;
}
}
return false;
}
What am I doing wrong?
In your migration table, make sure you have made all the image fields nullable:
$table->string('image_one')->nullable();
$table->string('image_two')->nullable();
...
Also, save your post model after collecting all the data.
if(Input::file('image_one'))
{
$image_one = $post->storePostPicture($request->file('image_one'));
if($image_one !== false) {
$post->image_one = $image_one;
}
}
if(Input::file('image_two'))
{
$image_two = $post->storePostPicture($request->file('image_two'));
if($image_two !== false) {
$post->image_two = $image_two;
}
}
$post->save(); //saving the post model here
<?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);
}
}
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've got 3 different classes (class Thumbnail in Thumbnail.php, class Upload in Upload.php and class ThumbnailUpload in ThumbnailUpload.php) all in the same namespace (PhotoProject). Currently, it will load an image, create a thumbnail and store both in selected directory, but it will not store the information requested into a database. If you look in the code snippet of blog_insert.php, once it gets to calling $loader->collectFilenames to be assigned to $names, nothing is ever stored in $names[]. I've did a var_dump, and $names is always empty. Any suggestions? Below are the code snippets.
class Upload {
protected $collectednames = [];
protected $typeCheckingOn = true;
protected $notTrusted = ['bin', 'cgi', 'exe', 'js'];
protected $newName;
protected $destination;
protected $max = 8388608;
protected $messages = [];
protected $permitted = [
'image/gif',
'image/png',
'image/jpg'
];
...
public function collectFilenames() {
return $this->collectednames;
}
blog_insert.php
<?php
use PhotoProject\ThumbnailUpload;
require_once '../includes/connection.php';
$conn = dbConnect();
if (isset($_POST['insert'])) {
$OK = false;
$stmt = $conn->stmt_init();
// if a file has been uploaded, process it
if(isset($_POST['upload_new']) && $_FILES['image']['error'] == 0) {
$imageOK = false;
require_once '../PhotoProject/ThumbnailUpload.php';
$loader = new ThumbnailUpload('path to store images');
$loader->setThumbDestination('path to store thumbnail');
$loader->upload();
$names = $loader->collectFilenames();
// $names will be an empty array if the upload failed
if ($names) {
$sql = 'INSERT INTO images (filename, caption) VALUES (?, ?)';
Class Thumbnail
<?php
namespace PhotoProject;
class Thumbnail {
protected $original;
protected $originalwidth;
protected $originalheight;
protected $basename;
protected $thumbwidth;
protected $thumbheight;
protected $maxSize = 350;
protected $canProcess = false;
protected $imageType;
protected $destination;
protected $suffix = '_thb';
protected $messages = [];
public function __construct($image) {
if (is_file($image) && is_readable($image)) {
$details = getimagesize($image);
} else {
$details = null;
$this->messages[] = "Cannot open $image.";
}
// if getimagesize() returns an array, it looks like an image
if (is_array($details)) {
$this->original = $image;
$this->originalwidth = $details[0];
$this->originalheight = $details[1];
$this->basename = pathinfo($image, PATHINFO_FILENAME);
// check the MIME type
$this->checkType($details['mime']);
} else {
$this->messages[] = "$image doesn't appear to be an image.";
}
}
public function setDestination($destination) {
if (is_dir($destination) && is_writable($destination)) {
// get last character
$last = substr($destination, -1);
// add a trailing slash if missing
if ($last == '/' || $last == '\\') {
$this->destination = $destination;
} else {
$this->destination = $destination . DIRECTORY_SEPARATOR;
}
} else {
$this->messages[] = "Cannot write to $destination.";
}
}
public function setMaxSize($size) {
if (is_numeric($size) && $size > 0) {
$this->maxSize = abs($size);
} else {
$this->messages[] = 'The value for setMaxSize() must be a positive number.';
$this->canProcess = false;
}
}
public function setSuffix($suffix) {
if (preg_match('/^\w+$/', $suffix)) {
if (strpos($suffix, '_') !== 0) {
$this->suffix = '_' . $suffix;
} else {
$this->suffix = $suffix;
}
} else {
$this->suffix = '';
}
}
public function create() {
if ($this->canProcess && $this->originalwidth != 0) {
$this->calculateSize($this->originalwidth, $this->originalheight);
$this->createThumbnail();
} elseif ($this->originalwidth == 0) {
$this->messages[] = 'Cannot determine size of ' . $this->original;
}
}
public function getMessages() {
return $this->messages;
}
protected function checkType($mime) {
$mimetypes = ['image/jpeg', 'image/png', 'image/gif'];
if (in_array($mime, $mimetypes)) {
$this->canProcess = true;
// extract the characters after 'image/'
$this->imageType = substr($mime, 6);
}
}
protected function calculateSize($width, $height) {
if ($width <= $this->maxSize && $height <= $this->maxSize) {
$ratio = 1;
} elseif ($width > $height) {
$ratio = $this->maxSize/$width;
} else {
$ratio = $this->maxSize/$height;
}
$this->thumbwidth = round($width * $ratio);
$this->thumbheight = round($height * $ratio);
}
protected function createImageResource() {
if ($this->imageType == 'jpeg') {
return imagecreatefromjpeg($this->original);
} elseif ($this->imageType == 'png') {
return imagecreatefrompng($this->original);
} elseif ($this->imageType == 'gif') {
return imagecreatefromgif($this->original);
}
}
protected function createThumbnail() {
$resource = $this->createImageResource();
$thumb = imagecreatetruecolor($this->thumbwidth, $this->thumbheight);
imagecopyresampled($thumb, $resource, 0, 0, 0, 0, $this->thumbwidth,
$this->thumbheight, $this->originalwidth, $this->originalheight);
$newname = $this->basename . $this->suffix;
if ($this->imageType == 'jpeg') {
$newname .= '.jpg';
$success = imagejpeg($thumb, $this->destination . $newname, 100);
} elseif ($this->imageType == 'png') {
$newname .= '.png';
$success = imagepng($thumb, $this->destination . $newname, 0);
} elseif ($this->imageType == 'gif') {
$newname .= '.gif';
$success = imagegif($thumb, $this->destination . $newname);
}
if ($success) {
$this->messages[] = "$newname created successfully.";
} else {
$this->messages[] = "Couldn't create a thumbnail for " .
basename($this->original);
}
imagedestroy($resource);
imagedestroy($thumb);
}
}
Class ThumbnailUpload
<?php
namespace PhotoProject;
use PhotoProject\Upload;
require_once 'Upload.php';
require_once 'Thumbnail.php';
class ThumbnailUpload extends Upload {
protected $thumbDestination;
protected $deleteOriginal;
protected $suffix = '_thb';
public function __construct($path, $deleteOriginal = false) {
parent::__construct($path);
$this->thumbDestination = $path;
$this->deleteOriginal = $deleteOriginal;
}
/*
** Setter method for the thumbnail destination
*/
public function setThumbDestination($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new \Exception("$path must be a valid, writable directory.");
}
$this->thumbDestination = $path;
}
public function setThumbSuffix($suffix) {
if (preg_match('/\w+/', $suffix)) {
if (strpos($suffix, '_') !== 0) {
$this->suffix = '_' . $suffix;
} else {
$this->suffix = $suffix;
}
} else {
$this->suffix = '';
}
}
public function allowAllTypes() {
$this->typeCheckingOn = true;
}
protected function createThumbnail($image) {
$thumb = new Thumbnail($image);
$thumb->setDestination($this->thumbDestination);
$thumb->setSuffix($this->suffix);
$thumb->create();
$messages = $thumb->getMessages();
$this->messages = array_merge($this->messages, $messages);
}
protected function moveFile($file) {
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'],
$this->destination . $filename);
if ($success) {
// add a message only if the original image is not deleted
if (!$this->deleteOriginal) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$this->messages[] = $result;
}
// create a thumbnail from the uploaded image
$this->createThumbnail($this->destination . $filename);
// delete the uploaded image if required
if ($this->deleteOriginal) {
unlink($this->destination . $filename);
}
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
Class Upload
<?php
namespace PhotoProject;
class Upload {
protected $collectednames = [];
protected $typeCheckingOn = true;
protected $notTrusted = ['bin', 'cgi', 'exe', 'js'];
protected $newName;
protected $renameDuplicates;
protected $destination;
protected $max = 8388608;
protected $messages = [];
protected $permitted = [
'image/gif',
'image/png',
'image/jpg'
];
public function __construct($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new \Exception("$path must be a valid, writable directory.");
}
$this->destination = $path;
}
public function setMaxSize($num) {
if (is_numeric($num) && $num > 0) {
$this->max = (int) $num;
}
}
public function allowAllTypes() {
$this->typeCheckingOn = false;
if (!$suffix) {
$this->suffix = ''; // empty string
}
}
public function upload($renameDuplicates = true) {
$this->renameDuplicates = $renameDuplicates;
$uploaded = current($_FILES);
if (is_array($uploaded['name'])) {
// deal with multiple uploads
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;
}
public function collectFilenames() {
return $this->collectednames;
}
public function getMaxSize() {
return number_format($this->max/1024, 1) . ' KB';
}
protected function checkFile($file) {
$accept = true;
if ($file['error'] != 0) {
$this->getErrorMessage($file);
// stop checking if no file submitted
if ($file['error'] == 4) {
return false;
} else {
$accept = false;
}
}
if (!$this->checkSize($file)) {
$accept = false;
}
if ($this->typeCheckingOn) {
if (!$this->checkType($file)) {
$accept = false;
}
}
if ($accept) {
$this->checkName($file);
}
return $accept;
return true;
}
protected function checkName($file) {
$this->newName = null;
$nospaces = str_replace(' ', '_', $file['name']);
if ($nospaces != $file['name']) {
$this->newName = $nospaces;
}
$extension = pathinfo($nospaces, PATHINFO_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)) {
// rename file
$basename = pathinfo($name, PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
do {
$this->newName = $basename . '_' . $i++;
if (!empty($extension)) {
$this->newName .= ".$extension";
}
} while (in_array($this->newName, $existing));
}
}
}
protected function getErrorMessage($file) {
switch($file['error']) {
case 1:
case 2:
$this->messages[] = $file['name'] . ' is too big: (max: ' .
$this->getMaxSize() . ').';
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['error'] == 1 || $file['error'] == 2 ) {
return false;
} elseif ($file['size'] == 0) {
$this->messages[] = $file['name'] . ' is an empty file.';
return false;
} elseif ($file['size'] > $this->max) {
$this->messages[] = $file['name'] . ' exceeds the maximum size
for a file (' . $this->getMaxSize() . ').';
return false;
} else {
return true;
}
}
protected function checkType($file) {
if (in_array($file['type'], $this->permitted)) {
return true;
} else {
if (!empty($file['type'])) {
$this->messages[] = $file['name'] . ' is not permitted type of file.';
return false;
}
}
}
protected function moveFile($file) {
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'],
$this->destination . $filename);
if ($success) {
// add the amended filename to the array of uploaded files
$this->filenames[] = $filename;
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
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();