I am using code for an to upload files as seen below:
$uploaddir = "./images/";
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
The code works to upload the image but I want to be able to post the filename to an SQL database afterwords.
I need to get the filename I uploaded and make it a variable called $filename so i can then use:
$image = $_POST[$filename];
I've tried using this to make it a variable
$filename = $_FILES['userfile']['name'];
All I get is an error saying undefined index : image.jpg on the $_POST and I'm uncertain why. Its listing the image filename in the error so why cant it upload it.
You can only access $_POST[$filename] if you're posting an input with the name "image.jpg", which I guess you aren't.
You've already got the filename from the $_FILES array, so why not use it again?
$image = basename($_FILES['userfile']['name']);
... or use the $filename variable that you've already got (can't see where this is defined in your example, but it obviously contains "image.jpg")
Note: the name part of $_FILES['input_name'] arrays contains the original filename of the uploaded file. That's all you need.
Related
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/.
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".
what im trying to do here, get the current file and then upload it,find the extension of the file and rename it! and echo the result!! but it seems wrong, and i dnt know which part!! :((
$fieldname = $_REQUEST['fieldname'];
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES[$fieldname]['name']);
if (move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadfile)) {
//find the extension
$extension= pathinfo($uploadfile);
//rename the file
rename ($uploadfile, "newfile.".$extenion['extension']."");
echo "uploads/newfile.'".$extension['extension']."'"; // "success"
}
I think you should do something like this:
$fieldname = $_POST['fieldname']; // don't use $_REQUEST
$extension = pathinfo($_FILES[$fieldname]['name'], PATHINFO_EXTENSION);
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . 'newfile.'.$extension;
if (move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadfile)) {
// success
}
move_uploaded_file already "renames" the file, there is no need to call rename manually. Just make it in a single operation.
You probably also noticed that I've passed PATHINFO_EXTENSION to pathinfo, since you need only the extension and not the complete path information.
Lastly, I used $_POST instead of $_REQUEST. You shouldn't use $_REQUEST unless you really know what you are doing. This could lead to unexpected variables tampering from cookies or session, per example.
$fieldname = $_POST['fieldname']; #its never going to be a GET! ..not sure y u need this though, the file field should hold the array key, but anyway...
#get the extension by removing everything before the last dot
$extension = preg_replace('#.+\.#', '', $_FILES[$fieldname]['name']);
$newname = "newfile.".$extension;
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . $newname;
if (move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadfile)) {
echo "$uploadfile"; // "success"
}
Untested, but the logic is mo straight to the point.
You should use the new filename as the second argument to move_uploaded_file:
$fieldname = $_REQUEST['fieldname'];
$tmpfile = $_FILES[$fieldname]['tmp_name'];
$info = pathinfo($tmpfile);
$filename = 'newfile.' . $info['extension'];
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . $filename;
if(move_uploaded_file($tmpfile, $uploadfile)) {
echo $uploadfile;
}
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.
Dear friends, this is a script which simply upload file and insert filename into database, why is this not working ? It's just upload the file and send filename to db even after validation . Please help
<?php
//file validation starts
//split filename into array and substract full stop from the last part
$tmp = explode('.', $_FILES['photo']['name']);
$fileext= $tmp[count($tmp)-1];
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(in_array($fileext, $allowedexts)){
return true;
}else{
$form_error= "Upload file was not supported<br />";
header('Location: apply.php?form_error=' .urlencode($form_error));
}
//file validation ends
//upload dir for pics
$uploaddir = './uploads/';
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile);
// $photo value is goin to db
$photo = $upload_filename;
function send_error($error = 'Unknown error accured')
{
header('Location: apply.php?form_error=' .urlencode($error));
exit; //!!!!!!
}
//file validation starts
//split filename into array and substract full stop from the last part
$fileext = end(explode('.', $_FILES['photo']['name'])); //Ricky Dang | end()
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(!in_array($fileext, $allowedexts))
{
}
//upload dir for pics
$uploaddir = './uploads/';
if(!is_dir($uploaddir))
{
send_error("Upload Directory Error");
}
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
if(!file_exists($uploadfile ))
{
send_error("File already exists!");
}
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
if(move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile))
{
send_error('Upload Failed, cannot move file!');
}
// $photo value is goin to db
$photo = $upload_filename;
This is a cleared up version to yours, give that a go and see if you get any errors
You can find the extension of file by using this code also.
$tmp = end(explode('.', $_FILES['photo']['name']));
now $tmp got the extension of file.
Why not use PHP's built-in functions to extract the extension from the filename?
$fileext = pathinfo($_FILES['photo']['name'],PATHINFO_EXTENSION);
And if the file extension is valid, you're returning from the function without doing anything further, if it's invalid you're setting the header, but the code logic will continue to your file processing
You blindly assume the file upload succeeded, but there's many reasons for it to fail, which is why PHP provides ['error'] in the $_FILES array:
if ($_FILES['photo']['error'] === UPLOAD_ERR_OK) {
// uploaded properly, handle it here...
} else {
die("File upload error, code #" . $_FILES['photo']['error']);
}
The error codes are defined here.