Can I rename an image that is uploaded using CKFinder?
Do you use the PHP version of CKFinder? If so, the following might help.
When uploading files, you can automatically remove spaces, characters with accents, and such. Set "ForceAscii" to "true" in the config.php file:
$config['ForceAscii'] = true;
The code for the "ForceAscii" setting is found starting on line 59 in this file:
ckfinder\core\connector\php\php5\CommandHandler\FileUpload.php
if ($_config->forceAscii()) {
$sFileName = CKFinder_Connector_Utils_FileSystem::convertToAscii($sFileName);
}
To rename the file as it's uploaded, you could add your own code to the "ForceAscii" code.
To add some Static text to the beginning or the end:
if ($_config->forceAscii()) {
$sFileName = CKFinder_Connector_Utils_FileSystem::convertToAscii($sFileName);
$sFileName .= "YourTextHere"; // Append your text
$sFileName = "YourTextHere" . $sFileName; // Prepend your text
}
Just before the force ascii code is a string replace, you could add your own version of a string replace if that would meet your goals.
$sFileName = str_replace(array(":", "*", "?", "|", "/"), "_", $sUnsafeFileName);
If the text used for the rename will vary, you'll need to provide a lot more details:
Will the text vary depending on which user is uploading the file?
Will it vary for each image, regardless of who uploads it?
What will determine the actual text that is used (based on username?).
The latest version, 2.1 allows the user to upload multiple files at one time. This could affect the approach you take.
If you provide additional information, I'll see if I can come up with a better answer.
Is this meant to allow the end user to rename their images?
It is possible for the user to rename an image as follows:
When they are looking at the images in the file browser window, they would right click on an image.
"Rename" is one of the options in the context menu.
EDIT: The latest version of CKFinder (2.1) has a config setting that is placed in the config.js file:
config.showContextMenuArrow = true;
this setting allows the user to access the context menu by clicking on an arrow that appears in the corner of the image.
Be Well,
Joe
Related
I have a website where users upload mp3 files and get a link. All the files are upload from a form to the database table. But the problem is that some of the files being uploaded do not contain .mp3 extensions I think this is because of the devices users have they save audio files with just name.
here is an example url to the file :
www.example.com/images/my_audio
As you can see .mp3 extension is missing.
And I want this link to appear like this (with a default .mp3 extension)
www.example.com/images/my_audio.mp3
How can I validate the image name during upload and add an extension if it is without extension?
I tried with str_replace()
str_replace(" ",",".mp3",$file);
But it does not seem to work.
Any idea?
You can use this:
if(preg_match('/mp3/',$file))
{
echo 'It has extension';
}
else
{
$file .= '.mp3';
}
If you want a one-liner you could always use
preg_replace("/(.+)(?<!\.mp3)$/i", "$1.mp3", $file_name);
First argument to preg_replace says
Grab any text (.+), as long as the
Text immediately before the end of the line (EOL = $) is not .mp3: (?<!\.mp3)
At this point there are two possibilities. Depending on if the user had an .mp3 extension at the end of the file name, either we've found something that matches the two criteria above, or we haven't:
If you do have something of the form of XYZ.mp3 it just gets returned as-is, which is the desired behaviour. This is because it failed criteria #2 and did not get grabbed.
Otherwise, the second argument to preg_replace says we take the text we grabbed ($1), and append .mp3.
The word on the street is true though. You really should verify that the file data is in fact an mp3.
You might want to look at the pathinfo() function, which can give you the various pieces of the filename.
We all know, this is a very important issue for many web developers. They want to protect direct access or direct readability to their confidential images. The folder that contains all the images is open and anyone can visit that folder, but I want to do something that can protect my image contents, means, if an unauthorised guy looks for an image he may get the image by visiting the appropriate folder but the contents will be invisible or difficult to understand. I think if I get a solution here, many guys will be helped from this question. Writing .htaccess isn't always a stable choice. So, after brainstorming I found some ways how I can protect image contents from direct access. I want to use Imagick with PHP to perform any kind of image editing.
Adding and removing a layer: After uploading, add a layer to make contents of the image invisible. So, if anyone reaches the folder you've stored the images will be meaningless as he will see the layer not the image content. Then remove the layer and show to them who have proper rights.
Converting the image to another format: Convert the image to any format like .txt, .exe, .bin, .avi or any other format so that without editing, the image won't be visible. Convert back to show it to the authorised user.
Image grid: Divide the image into some grids, say, if the image is medium 100 grids and change the position of the grids to make the contents unclear. To do this, we can name each grid like 1, 2, 3 and so on, then change the position to $position - 20. So the grid of position 25 will go to 5, 100 will go to 80, 1 will go to 81 and so on. Reverse the same way to display to the authorised users.
It is never possible to protect completely but we can make it harder. I don't know which of the three is possible with Imagick and which is not. Please tell me if you know. Thanks in advance.
You can put these images in a different folder outside of the public_html (so nobody can access them). Then via script, if a user is logged in, you get the image file content and then change the header. If a user is not logged, you can display a random image or showing a default image.
for example, the public html folder is: /var/www your image folder can be: /registered_user/images/
Then in your PHP script you can write:
<?php
if(!userLogged() || !isset($_GET['image'])) {
header('Location: /');
die();
}
$path = '/registered_user/images/';
$file = clean($_GET['image']); // you can create a clean function that only get valid character for files
$filename = $path . $file;
if(!file_exists($filename)) {
$filename = '/var/www/images/bogus.jpg';
}
$imageInfo = getimagesize($filename);
header ('Content-length: ' . filesize($filename));
header ('Content-type: ' . $imageInfo['mime']);
readfile ($filename);
The following problem I can't really wrap my mind around, so really if you guys can't be bothered to supply the entire code some tips leading in the right direction would be great!
So, I have a script where users can upload images to a server. PHP takes care of validating the file and saving it using a new filename in another folder, neither known by the client. Now, the client should be able to see the uploaded image, in html simply:
style="background-image:url('testimagegif.gif');
But preferably the client should not be able to see the path nor the file name of the image saved on the server. I know about using header('Content-type: ... for forcing the client browser to download files, but I do not see how this, nor any similar solution could be applied to this case. Same goes for readfile. If I use it the browser simply downloads the image, not placing it in the html.
You should probably be moving the files into a publicly readable folder on your webserver if you want to serve them.
Otherwise, you'll need something like readfile()
There are two options for this, you could use the data protocol, which would embed the whole image into the URL of the background ( this isn't recommended if the image is bigger than a few kb. ) or you can use a script to present the image by encoding or recording a unique key for the image, eg bg.php?id=4323-34442-3432-4532 which checks a db for the id to retrieve the file path then echoes the content with the right content type.
Some examples;
based on the Data URI wikipedia page
Data URI Method
Assuming a function like this;
function data_uri($fileID) {
$fRecord = mysql_fetch_array(
mysql_select("SELECT filePath, mimeType from fileTable WHERE fileID = " $fileID . ";")
);
$contents = file_get_contents($fRecord['filePath']);
$base64 = base64_encode($contents);
return "data:$fRecord['mimeType'];base64,$base64";
}
Then in your html/php page you'd have the following snippet
style="background-image:url('<?php echo data_uri($fileID);?>'
PHP Image Dump
Assuming a function like this;
// Given a filename and a mimetype; dump the contents to the screen
function showDocumentContent($fileID){
$fRecord = mysql_fetch_array(
mysql_select("SELECT filePath, mimeType from fileTable WHERE fileID = " $fileID . ";")
);
header( 'Content-Encoding: none', true );
header( 'Content-Type: ' . $fRecord['mimeType'], true );
echo readfile( $fRecord['filePath'] );
}
Then in your html page you'd have this;
style="background-image:url('image.php?fileID=123')
In the first case, images larger than a few KB will result in equally large HTML pages, and may not be supported in browsers consistently. In the second case, you'd effectively have created a php script that is pretending to be an image. In both cases, the real path to the binary files on your server is abstracted away by storing a mapping in a database.
If you store the paths to the files somewhere like a database or a file, you can use readfile() to output the file once you retrieve the path.
Combine that with the content-type header, and set the background-image URL to the PHP script with the correct query string like so:
style="background-image:url('script.php?img=30382');"
You must expose some path to the client, because their browser has to access the file. You can use your webserver config to serve at an indirected location, or serve the image with PHP and have the real path in a call to readfile()
I am using plupload to do an upload of multiple files to my server. Using this, there is a parameter 'url : 'upload.php'. upload.php catches the files as they are received, and might recombine them if they get chunked. Once the full file is received, it sends a response back to the original page, displaying a green checkbox icon.
I have added some code to this page, after all the main code to manipulate the photos I have uploaded. My plan is to create three copies of my full size image, lg, med, and small. I got this part working, but then decided to first rename the original file to match my naming scheme.
I now get a corrupted renamed file, and thus my three smaller images also get corrupted.
//get the original file info
$filepath = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
$filepathinfo = pathinfo($filepath.$fileName);//fileName is used previously in the file
//rename original file to a unique name
$finding_id = 'xyz';
$file_name_new = uniqid($client_id . '-' . $finding_id . '-', true); //doesn't include extension
//rename($filepath.$fileName, $filepath.$file_name_new.'.'.$ext);
//copy($filepath.$fileName, $filepath.$file_name_new.'.'.$ext);
As is, I get my one file, or how ever many I uploaded, byte size matches original exactly, and name stays the same (except for removal of certain characters).
If I uncomment only the rename function, I actually get two files. The byte sizes total the original photo. The larger file displays with a section of gray at the bottom. The smaller file doesn't display at all.
If I uncomment only the copy function, I get an exact renamed copy of my original file, my original file, and another file, the same size and corruption as the larger file doing a rename.
Any ideas? Seems like it should be pretty straightforward.
if the file was currently uploaded by HTTP POST use move_uploaded_file
if you fopen() somewhere in this request the same file make sure to call fclose()
I forgot I had the chunking feature turned on. Must have turned it on to test something. For whatever reason, when the script was running the last chunk of the file hadn't been fully appended yet. Thanks for all the input anyway!
Are you writing to the file yourself? If so, the problem might be that you're missing a call to fflush or fclose. (The last chunk of the file not getting written and the file no longer being there when PHP gets round to writing it. This shouldn't happen if you're using Linux or some other Unix, but I could envisage it on Windows.)
For an image file (JPEG) that has been uploaded to the server via a PHP script (to a directory such as http://www.somedomain.com/images, is it a good idea to allow the client to get the image's direct address (such as http://www.somedomain.com/images/someimage.jpg and paste it into a WYWSIWYG text editor (such as TinyMCE)?
I am wondering if there is a preferable method where the direct address is encrypted?
Please, if I should just link directly to the image, just say so.
Thanks!
Note: I have modified this question from my original. Please see revisions if you are curious, but I think I was asking the question incorrectly. My apologies to the people who already answered.
As long as you check correctly WHAT is being uploaded, it shouldn't be a problem. So please at least use getimagesize or a similar function to make sure it's an image that's being uploaded, AND make sure the extension on the file is correct so that it will never be run through the PHP interpreter - to prevent someone from uploading an image with a PHP script attached.
BTW Here's a nice whitepaper on uploads and security : http://www.scanit.be/uploads/php-file-upload.pdf
Depending on the CPU Constraints of your web-hosting service you can write a service to 'serve' the images to your users.
Here is some very BASIC code, it needs spiffing up and cleaning up for XSS/etc...
<?php
$basePath = "/path/to/my/image/store/not/web/accessible/";
$file = NULL;
if (isset($_GET['file']))
$file = $_GET['file'];
if ($file != NULL)
{
$path = $basePath . $file;
// $file needs to be checked for people
// trying to hack you, but for the sake of simplicity
// i've left it out
$mime = mime_content_type($path);
$size = filesize($path);
header("Content-Length: " . $size);
header("Content-Type: " . $mime);
header('Expires: 0');
readfile($path); // Outputs the file to the output buffer
}
?>
Obviously you can put whatever security checks in here you want. But this way your files are below the web dir, and you can apply logic to thier accesibility. This is typically used more for FILE vs. Images, but you can do the same thing here.
Images Accessed like this
http://www.mysite.com/image.php?file=hello.jpg
And you can use mod_rewrite to rewrite urls like this:
`http://www.mysite.com/images/hello.jpg
Into the first url.
I Cannot stress enough the need for further security checking in the above example, it was intended to show you how to serve a file to the user using PHP. Please don't copy & use this verbatim.
Wordpress uses direct links for images. The permalink function simply puts the image on a page along with metadata for comments, but the images' SRC attributes still link directly to the image.
why are you concerned about revealing your image location. Hotlinking?
if so you can prevent hotlinking with htaccess
http://altlab.com/htaccess_tutorial.html
Didn't you get your answer already?
Every site reveals image location to the browser. It's just the way web works.
Got any reason to "encrypt" original location?