Create Thumbnail with SWFUpload - php

I am attempting a CMS photo gallery and need to create thumbnails at the end of my upload.php file. I have a function called create_square_image that works fine when run on the 'showphotos.php' page. However I don't want it to be run every time someone views the page. I have tried adding the following to SWFUpload...
// Process the file
/*
At this point we are ready to process the valid file. This sample code shows how to save the file. Other tasks
could be done such as creating an entry in a database or generating a thumbnail.
Depending on your server OS and needs you may need to set the Security Permissions on the file after it has
been saved.
*/
$thumb_save = "uploads/thumbs/thumb_" . $_FILES[$upload_name]["tmp_name"];
create_square_image($_FILES[$upload_name]["tmp_name"],$thumb_save,100);
if (!#move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
HandleError("File could not be saved.");
exit(0);
}
exit(0);
The create_square_image function uses this format:
create_square_image ( string $filename , string $destination, size )
I have tried it a few times and it will save the image but not the thumbnail.

Set the permissions on /uploads/thumbs/ to 777. You could also try specifying the absolute path to that location. To see your absolute path use this code: echo getcwd();

Related

hello I wanna use php_move_upload_file in order to move image from my temp folder to a permanent folder

hi this is the function that upload image inside temp location and save location to session for forther use
function uploadPhoto()
{
$rawImage = $_FILES['advPhoto'];
$uploader = new ImageUploader($rawImage);
$uploader->moveToProjectTempFolder();
//1 save the current image in sassion (save the attachment class inside seesion)
$uploader->saveInSession();
// $temperrary = $uploader->CurrentImgTemperraryLocation();
//2 send reponse the current image location
AjaxHelper::sendAjaxResponse("images/temp/" . $uploader->CurrentImgTemperraryLocation());
//create image tag and set the image source the "temp uploaded image path"
// done
//when the mail form is submitted
//loop through session array
//move the user uploaded/approved images to permanent folder
//save image information inside DB
}
here is the function that cause problem I wanna move the picture from temp folder to permanent location but the php_move_uploaded_file() doesn't work in my case I don't really know what is the problem please help me if you know what is the problem thnks .
function saveAdv()
{
$advTitle = $_POST['advTitle'];
$advContent = $_POST['advContent'];
if (!empty($advTitle) && !empty($advContent)) {
if (DataValidation::isOnlyPersianOrEnglish($advTitle) &&
DataValidation::isOnlyPersianOrEnglish($advContent)) {
DBconnection::insertRow('ADVERTISEMENT', ['title', 'Advertisement', 'advDate'],
[$advTitle, $advContent, date('y/m/d h:i:s')]);
// AjaxHelper::sendAjaxResponse("success");
$projectTemp = $_SESSION['ADVERTISEMENT']['Img'];
move_uploaded_file(
$projectTemp,
DOC_ROOT . "/images/advertisementImg/"
);
AjaxHelper::sendAjaxResponse($projectTemp);
}
} else {
AjaxHelper::sendErrorMessage(AjaxHelper::EMPTY_EMAIL_OR_PASSWORD);
}
}
I don't get any error I've already debuged many times but no warning and no errors at all and the location of the folders are completely correct and also there is no permission problems.
The move_uploaded_file() works pretty well at first step that I move image from system temp location to my project temp location, but doesn't work when I wanna move the image from project temp location to permanent location.
move_uploaded_file() is only for moving files which have just been uploaded in a POST request and are stored in the system temp location. As the documentation (https://php.net/manual/en/function.move-uploaded-file.php) states, it first checks whether the file is a valid upload file meaning that it was uploaded via PHP's HTTP POST upload mechanism (that's a direct quote from the docs). If it's not valid by that definition, it fails.
So, if you're trying to use move_uploaded_file() to copy files from other locations (not the system temp location) which have not been directly uploaded to that location in the current request, then it won't work. Use PHP's general file manipulation functionality for moving other files around, using the rename() function (see https://www.php.net/manual/en/function.rename.php for details).

Prevent users to download other files by changing the path in a url query

i have a download function receiving the filename by $_GET and i want to prevent users of downloading other files changing the path and accessing other files in the system.
method:
function actionDownload($arquivo) {
try {
$filepath = \Yii::getAlias('#webroot') . '/files/coordenadas/'. $arquivo;
if (file_exists($filepath)){
return \Yii::$app->getResponse()->sendFile(\Yii::getAlias('#webroot') . '/files/coordenadas/'. $arquivo, $arquivo);
}
}
catch (\Exception $exception) {
throw new NotFoundHttpException("Arquivo não encontrado");
}
}
the route to download the method:
http://example.com/converter-coordenadas/download?arquivo=geografica-utm-20200830171051.xlsx
if someone change the arquivo variable to another valid path it will be able to download other files. How prevent that, but keeping the function receiving the file name in a url param?
the situation that i have is:
the user upload a file through ajax
i convert this file and return the filename
create a download button with the link to the new file.
I don't have any other information to make a relation with the file, like an user id.
As #GetSet explained in the comments, the biggest problem is procedural. One way to do this correctly is as follows:
Upload the file to your server and save the reference in database (you already doing) and generate an unique ID for this file (or for this download). This ID will be saved in a database field, for example with the name: "donwload_id"
Then in the view (when you are creating the link for the download):
Html::a('Download', [Url::to('donwload-action'), 'download_id' => $model- >download_id]);
In your controller, You will know how to find the file by its unique identifier (download_id).
No one knows how you have generated this ID and therefore it is more difficult for anyone to be able to generate it again. Also you can limit the time available to download the file by setting an expiration date to the link.

php file exist not finding file

I'm having some trouble with deleting a file from a website using PHP.
I have some code which uploads a file, (which works) it then resizes, renames, changes image format and saves the uploaded image twice. (Once as the full size image, once as a thumbnail.)
This part works fine, no worries.
However, I'm writing some error checking code that will delete these uploaded images if the image formats do not match the files extension.
(For example, create a bmp file in mspaint and save it. close paint, reopen the bmp file in paint then click file, save as, then save it as a png.
What happens is paint will just change the extension and not the file format. Try opening that png with my php script and it will fail with an 'image not a valid png' error.
I have written a custom error function to inform the user that the image format is bad. (Because informing users why they have an issue is better than just telling them they have an issue.)
The below code will display the name of the file, which does exist, but will not pass the 'file_exists' check.
print( $imagename . ".jpg<br/>\n" ); // Displays 'images/filename.jpg'
if ( file_exists( $imagename.".jpg" ) ) { unlink( $imagename.".jpg" ); print( "Image deleted<br/>\n" ); }
I've tried pre-pending a "/", with no luck, and I'm not really sure why the file isn't being found?
Any hints? (And apologies for the huge block of text!)
Try adding this to your script:
print( getcwd() .'/'. $imagename . ".jpg<br/>\n" ); // Displays full path
This will tell you where PHP is looking for the file to delete. If it's different to where the file actually resides, then you need to give PHP the right path. There are lots of ways to achieve this, two basic examples are.
Use an absolute path: (works until you move your code)
$rootPath='/var/www/html/orsimilar/';
if ( file_exists( $rootPath. $imagename.".jpg" ) ) { unlink( $imagename.".jpg" ); print( "Image deleted<br/>\n" ); }
Or use a relative one:
$rootPath=__DIR__ . '/../pathtoimages';
if ( file_exists( $rootPath. $imagename.".jpg" ) ) { unlink( $imagename.".jpg" ); print( "Image deleted<br/>\n" ); }
Thanks everyone for your help.
Using getcwd() confirmed that it was looking in the correct location for the file, however the issue was on my part.
My code created the new blank image, then copies the source image to it, (which is the part it would fail at) then if there was a failure, it would then copy the blank images to the final location. At the point of failure, the files do not in fact exist for file_exists to find them"
I've now checked for failure and will not copy the file if there was an issue.
Again, thanks for your help but once again, PEBCAK!

FileManager For TinyMCE not getting variable

I am using TinyMCE as a WYSIWYG editor.
It is working perfectly, except for the image upload directory. I want each user to have their own directory in the images directory, but I cannot get it to work.
I am passing the user id in the URL and have tried adding the code to get it from the URL in the config.php file where the directories are defined, but the $user_id value remains empty.
Any assistance would be great.
The URL:
http://mydomain.co.za/index.php?user_id=1
The Code:
<?php
$user_id= htmlspecialchars($_GET["user_id"]);
// The URL that points to the upload folder on your site.
// Can be a relative or full URL (include the protocol and domain)
$imageURL = 'http://mydomain.co.za/images/'.$user_id;
// Full upload system path. Make sure you have write permissions to this folder
$uploadPath = '/home/username/public_html/editor/images/'.$user_id;
//We create the directory if it does not exist - you can remove this if you consider it a security risk
if(!is_dir($uploadPath)) {
mkdir($uploadPath,0755,true);
}
//Create thumb directory if doesn't exist
if(!is_dir($uploadPath . 'thumbnail')) {
mkdir($uploadPath . 'thumbnail',0755,true);
}
//Allowed extenstions
$allowedExtensions = array('jpg','gif','jpeg','bmp','tif','png');
//Maximum upload limit
$sizeLimit = 2 * 1024 * 1024;
function isAuth() {
//Perform your own authorization to make sure user is allowed to upload
return true;
}
Is it possible the reason is because it is not in the main php file?
Or Can I get the variable from the URL?
They suggested on their Instructions that I add $userId = Auth::getId(); but id returns an empty value. Plus I have no idea what that command is executing.
PLEASE NOTE:
the file management is being done by TinyMCE Image Uploader & Manager
UPDATE:
By adding the $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; echo $actual_link; I noticed by the time the $_GET command is rung the URL has changed to http://mydomain.co.za/tinymce/plugins/lioniteimages/connector/php/gallery.php, but in the browser URL bar, the URL is still the same with the variable.
Is there anyway to access that URL instead of the one i am getting?
I found the solution.
Simple enough, just created a session and the problem was solved.
I was able to get the variable from the session.

PHP - upload and overwrite a file (or upload and rename it)?

I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);

Categories