I'm attempting to move an uploaded image (from Android) that is to be renamed via the PHP below in the second example so that their names cannot conflict. The original example below uploads files correctly but can have naming conflicts. The error that I'm experiencing is that the move_uploaded_files function fails, which I'm unsure as to why. The directory appears the same but I could be wrong and the problem is that image is never moved from the temp directory. Above all else, I think this is just a directory issue since the original example works. Please let me know if you need more information. The example I'm going by is located here: How to rename uploaded file before saving it into a directory?
Original:
$uploaddir = './appphotos/';
$absPath = 'https://'.$_SERVER['HTTP_HOST'].'/complaint_desk/appphotos/';
$file = basename($_FILES['userfile']['name']);
$uploadFile = $file;
$newName = $uploaddir . $uploadFile;
New Attempt:
$temp = explode(".",$_FILES["userfile"]["name"]);
echo json_encode($temp);
$newfilename = rand(1,99999) . '.' .end($temp);
echo json_encode($newfilename);
$uploadFile = move_uploaded_file($_FILES["userfile"]["name"], "/var/www/complaint_desk/appphotos/" . $newfilename); echo json_encode($uploadFile);
You should use the function as follow:
if(move_uploaded_file($_FILES["userfile"]["tmp_name"], "./appphotos/" . $newfilename)) {
echo json_encode($uploadFile); // why do you want to encode it?
} else {
echo 'File failed to move';
}
Always check the result of move_uploaded_file(). Also, the file is located at $_FILES["userfile"]["tmp_name"] before moving.
Also, $absPath is incorrect. It shouldn't start with http protocol. It should look like /var/www/complaint_desk/appphotos/ or C:/complaint_desk/appphotos/.
Related
I don't know if this has been asked before, please pardon in advance.
I created an image compression web app using the tinyPNG API, and it works as intended - that is users can upload an image file and it is compressed and saved in the server.
But then I create a download functionality for the user to download/save the compressed image.
On clicking the download link it throws up an error:
can’t find the file at http://localhost/var/www/html/imgtest/uploads/67403938_10219921906785196_7063388762713096192_n_1574687362.jpg.
Even though the compressed image is in the server.
Please help!!!
MY CODE:
require_once("vendor/autoload.php");
//makes PHP execute faster
set_time_limit(0);
//API key
\Tinify\setKey("API_KEY_HERE");
//Main code
if (isset($_POST['submit'])) {
//supported image formats.
$supported_image = array('image/jpg', 'image/jpeg', 'image/png');
foreach($_FILES['images']['name'] as $key=>$val){
$file_name = $_FILES['images']['name'][$key];
// get file extension
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
// get filename without extension
$filenamewithoutextension = pathinfo($file_name, PATHINFO_FILENAME);
if (in_array($_FILES['images']['type'][$key], $supported_image)) {
if (!file_exists(getcwd(). '/uploads')) {
$oldmask = umask(0);
mkdir(getcwd(). '/uploads', 0777, true);
umask($oldmask);
}
$filename_to_store = $filenamewithoutextension. '_' .time(). '.' .$ext;
move_uploaded_file($_FILES['images']['tmp_name'][$key], getcwd(). '/uploads/' .$filename_to_store);
$compress_file = getcwd(). '/uploads/' .$filename_to_store;
// optimize image using TinyPNG
try {
$source = \Tinify\fromFile(getcwd(). '/uploads/' .$filename_to_store);
$source->toFile(getcwd(). '/uploads/' .$filename_to_store);
//The code to show a modal for downloading the converted file.
} catch(Exception $e) {
echo $e->getMessage();
exit;
}
}
}
echo "<a href=".$compress_file." download>Download</a>";
}
?>```
The problem in your code is, that you create the link with $compress_file that contains absolute path to the file.
/var/www/html/imgtest/uploads/67403938_10219921906785196_7063388762713096192_n_1574687362.jpg
So when the link is clickend and the url is resolved in browser the result is
http://localhost/var/www/html/imgtest/uploads/67403938_10219921906785196_7063388762713096192_n_1574687362.jpg.
So if the localhost domain is pointed to /var/www/html/imgtest/ than the server is looking for the file in this path which doesn't exist:
/var/www/html/imgtest/var/www/html/imgtest/uploads/...
When you are generating the path to the compressed file you should put it's url into other variable where you wouldn't prepend the current directory.
$compress_file_url = '/uploads/' .$filename_to_store;
$compress_file = getcwd(). $compress_file_url;
Then you should use the $compress_file_url instead of $compress_file when creating a link
echo "<a href=\"$compress_file_url\" download>Download</a>";
This should work assuming your localhost domain is pointed to /var/www/html/imgtest. If your localhost domain is pointed to /var/www/html you might need to prepend $compress_file_url with /imgtest before it's used to create a link.
$compress_file_url = '/uploads/' .$filename_to_store;
$compress_file = getcwd(). $compress_file_url;
$compress_file_url = '/imgtest' . $compress_file_url;
I was wondering if someone with more experience than me could take a quick second to have a look over my php script for uploading a file to my server.
I had a simple php script that uploaded my image the root of my server when I called the script in my code like so:
http://server.foo.com/images/uploadToDirectory.php
Now I'm trying to amend it so that I can put the name of a folder at the end with the following call:
http://server.foo.com/images/uploadToDirectory.php?dir=test_folder
But for some reason my image is only getting sent to the root of the server. I've checked the logic of my c# code so I think it must be something to do with my php script. Could someone please have a look over it and tell me if I'm doing something silly with my code?
<?
$_SESSION['directory'] = $_POST['directory'];
$uploaddir = './'.$_SESSION['directory'];
$file = basename($_FILES['file']['name']);
$uploadfile = $uploaddir . $file;
print_r($_FILES);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "http://server.ip.address/images/{$file}";
}
else
{
echo "Didn't Work!!!!";
}
?>
Please note, I know this is probably a really bad way for me to go about doing what I want to do, but it's the way I've implemented it. My knowledge of PHP isn't very good.
For comparison here is the code to load to the root of the server:
<?
$uploaddir = './';
$file = basename($_FILES['file']['name']);
$uploadfile = $uploaddir . $file;
print_r($_FILES);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "http://server.ip.address/images/{$file}";
}
else
{
echo "Didn't Work!!!!";
}
?>
Ok so.. if you invoke your script like this:
http://server.foo.com/images/uploadToDirectory.php?dir=test_folder
Then your script should be:
$uploaddir = './'.$_GET["dir"];
That would collect your URL GET variable "dir".
I'm using uploadify on a project, and I've got the php script renaming a single file, but I'm unsure how to repeat the process if more than one file is uploaded at a time?
My php script is below...
$targetFolder = '/img/uploads'; // Relative to the root
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$fileParts = pathinfo($_FILES['Filedata']['name']);
$unique_hash = hash_hmac("md5", file_get_contents($_FILES['Filedata']['name']), SALT);
$targetFile = rtrim($targetPath,'/') . '/' . $unique_hash .'-'.$_POST['userId'].'.'. $fileParts['extension'];
#$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo '1';
} else {
echo 'Invalid file type.';
}
}
When you use ajax, you can send a request for every file just one by one then you wont have to use a foreach or you send the form at once and use the code below here.
When you send all file together you will be using in your form something like this: name=userfile[] so you can foreach the files like this:
foreach ($_FILES as $file)
{
$uploadfile = $uploaddir . basename($file['name']);
if (!move_uploaded_file($file["tmp_name"], $uploadfile))
{
echo set_e('error','Image ['.$i.'] not uploaded','');
}
}
Have you tried to do more than one? Uploadify uses jQuery ajax to process the files? It might look simultaneous but it processes one file at a time via ajax. It will call your upload.php as many times as there are files in the queue. So if your function works for one file, it will for the rest. You just need to make sure it's writing a unique filename in the directory every time the function is called whic it looks like it does. Uploadify handles looping through each file name then calls your upload script.
http://www.uploadify.com/demos/
Look at the network console with Chrome or Firebug and upload a bunch of pictures with on the demo. you'll see the upload.php script is called for each file.
FYI,
I used to use uploadify but I changed to PLUPLOAD http://www.plupload.com/. Supports multiple uploads too but better documented and easier to use with great api's.
Here is my code:
if ($_FILES['music']['name'] != '')
{
$file_name = time() . $_FILES['music']['name'];
copy($_FILES['music']['tmp_name'], "music/" . $file_name);
}
else
{
$file_name = "";
}
I want to upload audio file. the file name is insert into database. but its not insert into folder.
try move_uploaded_file instead. You may want to check file size limits too.
I think you want to use move_uploaded_file(), not copy
I guess the folder in which you are trying to copy the uploaded file is not the one you expect. Possibly this is what you need:
copy($_FILES['music']['tmp_name'], __DIR__ . "/music/" . $file_name);
By the way move_uploaded_file() works faster and safer than copy().
i have this script but i want to rename the file:
<?php
$fieldname = $_REQUEST['fieldname'];
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES[$fieldname]['name']);
if (move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadfile)) {
//i want to rename the file before i can upload it
echo $uploadfile; // "success"
}
else {
echo "error";
}
?>
how can i rename the file before i upload it to uploads/ directory!!
What ever you pass as the 2nd parameter to move_uploaded_file will be used as the file name.
The move_uploaded_file function does exactly that. When you are moving the uploaded file from the temporary location to the uploads/ directory, you can change the name of it.
move_uploaded_file($_FILES[$fieldname]['tmp_name'], 'uploads/whatever-i-want');
Just specify a different target name in $uploadfile.