php upload isset and rename file if it's exist - php

I know, there are many solutions for this question, but unfortunately I couldn't solve it, Here is my upload code:
public static function upload(&$file, $destinationDir = "", $destinationName = "", $secure = true)
{
$ret = false;
if (isset($file['tmp_name']) && isset($file['name']))
{
if ($destinationName == '')
{
$destinationName = $file['name'];
}
$destinationFile = $destinationDir . '/' . $destinationName;
if (move_uploaded_file($file['tmp_name'], $destinationFile))
{
if ($secure)
{
chmod($destinationFile, 0644); // without execution permissions if it is possible
}
$ret = true;
}
}
return $ret;
}
1: How can I rename file while uploading to server ?
2: If file name is exist then how to rename it automatically?
Thanks in advance

Use file_exists for this case :
public static function upload(&$file, $destinationDir = "", $destinationName = "", $secure = true){
$ret = false;
if(isset($file['tmp_name']) && isset($file['name'])){
if ($destinationName == ''){
$destinationName = md5($file['name']);
}
$destinationFile = $destinationDir.'/'.$destinationName;
if(file_exists($destinationFile)){
// Change the destination file name if it exists
$destinationFile = $destinationDir.'/'.md5($destinationName.rand());
}
if (move_uploaded_file($file['tmp_name'], $destinationFile)){
if($secure){
chmod($destinationFile, 0644); // without execution permissions if it is possible
}
$ret = true;
}
}
Note:
move_uploaded_file — Moves an uploaded file to a new location
structured like this
bool move_uploaded_file ( string $filename , string $destination )
in $destination parameter you give the name of your new uploaded file. Name your file to something that unique. Whatever !, so don't worry about this

Related

symfony post api is taking too much time to load

I have a api, which will upload the images of the users to server.
It will take the images in base64 format and send that to server. But the problem is for some user it will take long time, and for some user it works well.
I am not getting why this is happening. But the destination directory is a having 700GB of data.
code for uploading :
`
$file will be having base64 format of image
$this->file = $file;
if ($this->id && !empty($this->path) && !is_null($file)) {
$this->storeFilenameForRemove();
}
if ($file instanceof File) {
if (isset($this->path)) {
$this->temp = $this->path;
$this->path = null;
} else {
$this->path = 'initial';
}
} else if (gettype($file) == 'string') {
if (preg_match('/data:(\w+)\/(\w+);base64,/i', $file, $matches)) {
if ($matches) {
$file = preg_replace('/data:(\w+)\/(\w+);base64,/i', '', $file);
$tmpFile = Array();
$tmpFile['data'] = base64_decode( str_replace(' ', '+', $file) );
if ($matches[1] === 'image') {
$tmpFile['name'] = uniqid().'.png';
} else {
$tmpFile['name'] = uniqid().'.'.$matches[2];
}
$tmpFile['handle'] = fopen( $this->getUploadRootDir().'/'.$tmpFile['name'], 'w' );
// inject the raw image data into the new file
fwrite( $tmpFile['handle'], $tmpFile['data'] );
fclose( $tmpFile['handle'] );
$this->path = $tmpFile['name'];
}
}
} else {
$this->file = $file;
}`
I'm not sure if executing a preg_match on a base64 encoded string is a good idea, while I'm not sure that fixes all of your problems regarding speed I'm positive that implementing a different check for base64 encoded strings would improve the speed.
Replace the following:
if (preg_match('/data:(\w+)\/(\w+);base64,/i', $file, $matches)) {
with this
if ( base64_encode(base64_decode($file)) === $file){

How to remove sanitize from Opencart downloads

I am developing a module for my client to upload and browse file in Opencart.
when I am uploading file from my back-end server I am getting the output as file.zip.xyzasdf. Where I just want to remove this .xyzasdf
Can any one suggest me how to remove sanitize from the following code...
public function upload() {
$this->load->language('catalog/download');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'catalog/download')) {
$json['error'] = $this->language->get('error_permission');
}
if (!$json) {
if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
// Sanitize the filename
$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
// Validate the filename length
if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
$json['error'] = $this->language->get('error_filename');
}
// Allowed file extension types
$allowed = array();
$extension_allowed = preg_replace('~\r?\n~', "\n", $this->config->get('config_file_ext_allowed'));
$filetypes = explode("\n", $extension_allowed);
foreach ($filetypes as $filetype) {
$allowed[] = trim($filetype);
}
if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Allowed file mime types
$allowed = array();
$mime_allowed = preg_replace('~\r?\n~', "\n", $this->config->get('config_file_mime_allowed'));
$filetypes = explode("\n", $mime_allowed);
foreach ($filetypes as $filetype) {
$allowed[] = trim($filetype);
}
if (!in_array($this->request->files['file']['type'], $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Check to see if any PHP files are trying to be uploaded
$content = file_get_contents($this->request->files['file']['tmp_name']);
if (preg_match('/\<\?php/i', $content)) {
$json['error'] = $this->language->get('error_filetype');
}
// Return any upload error
if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
} else {
$json['error'] = $this->language->get('error_upload');
}
}
if (!$json) {
$file = $filename . '.' . token(32);
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_FOLDER . $file);
$json['filename'] = $file;
$json['mask'] = $filename;
$json['success'] = $this->language->get('text_upload');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
Any help would be greatly appreciated...
Thanks
Removing the random string that is added to the filename is simple. Just change
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD . $file);
to:
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD . $filename);
But keep in mind that this will bring problems.
OpenCart saves the random string in the database at the time of file upload, so it will later use it to identify the file.
If you delete this feature, the uploaded files in the admin panel will not be available.

About File Manager PHP

please help me
May Describe This Code ?
part One :
if(isset($_GET['dir'])){
$currDir = $_GET['dir'];
}else {
$currDir = 'files';
}
if(substr($currDir, strlen($currDir) - 1) != "/") {
$currDir .= '/';
}
please this one too......................
Part Two............................
foreach (glob($currDir . '*') as $filename){
$fileFormat = '';
if (is_dir($filename)) {
$type = 'folder';
} else {
$type = 'file';
$dotPosition = strrpos($filename, ".");
if ($dotPosition !== false) {
$fileFormat = substr($filename, $dotPosition + 1);
}
}
Part 1:
It is checking and setting the variable for directory path. If path is not provided then default is set to "files". Last line makes sure that directory's path ends with "/".
Part 2:
This section is basically checking file extension and storing it in $fileFormat variable. This code could have been better.

PHP file upload is creating filenames starting with "PHP" and with .tmp extension

I am using PHP (Symfony2) in my project which has image upload feature. Inside controller:
if ($request->isXmlHttpRequest() && $request->isMethod('POST')) {
$index=(int)$request->request->get('index');
$image_file = $request->files->get('shop_bundle_managementbundle_posttype')['images'][$index]['file'];
$image= new Image();
$image->setFile($image_file);
$image->setSubDir('hg');
$image->upload();
$em->persist($image);
$em->flush();
}
I use a class UploadFileMover that handle the file upload. I didn't write the following code but as I understand, an MD5 hash will be created from the original file name and used as filename. But the instance of UploadedFile contains a file name like "PHP"+number.tmp, not the original as stored in computer filesystem.
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath,$relativePath)
{
$originalName = $file->getFilename();
$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);
}
}
This class is instanciated when an image is uploaded. In other words, I have an Entity Image that has a method upload. Inside entity class:
public function upload()
{
if (null === $this->getFile()) {
return;
}
$uploadFileMover = new UploadFileMover();
$this->path = $uploadFileMover->moveUploadedFile($this->file, self::getUploadDir(),$this->subDir);
$this->file = null;
}
I var_dumped the filename all across the different steps but I cannot figure out where it is transformed to PHP16653.tmp.
Can it be related to an APACHE related configuration? Your help is appreciated. I really did a lot of research for similar issue in the web to no avail.
The problem was created by the line:
$originalName = $file->getFilename();
Use:
$originalName = $file->getClientOriginalName();
instead.

How to rename automatically image file names while uploading?

Here's my upload function code:
function upload(&$file, $destinationDir = "", $destinationName = "", $secure = true){
$ret = false;
if (isset($file['tmp_name']) && isset($file['name'])){
if ($destinationName == ''){
$destinationName = $file['name'];
}
$destinationFile = $destinationDir . '/' . $destinationName;
if (move_uploaded_file($file['tmp_name'], $destinationFile)){
if ($secure){
chmod($destinationFile, 0644);
}
$ret = true;
}
}
return $ret;
}
This function can't rename file names automatically, if two files name are same, it will replace new image file to existing file.
How can I change this above function to rename files automatically while uploading to server?
Thank you very much
Get the extension:
//Get extension
$ext = pathinfo($file["name"], PATHINFO_EXTENSION);
Then change this line:
$destinationName = $file['name'];
to a combination of the sha1 hash of the file appended to the timestamp, with the extension:
$destinationName = sha1_file($file["tmp_name"]).time().".".$ext;
Use something like this:
$destionationFile = $destinationDir . '/' . $destinationName;
if(is_file($destinationFile))
{
$destinationName = basename($destinationName).'_'.hash('sha256', time().rand(9999, 999999)).'.'.pathinfo($destinationName)['extension'];
$destionationFile = $destinationDir . '/' . $destinationName;
}

Categories