Php upload file to server directory script - php

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".

Related

PHP substr not stripping file extension

Using the below php if I upload a .txt file named "example" the resulting uploaded file looks like
example.txt04-27-2020-1228
it is still has the extension .txt (which I want) but I am trying to get the file to read like this
example.04-27-2020-1228
Here is the code
<?php
$uploaddir = 'C:/xampp/htdocs/';
$uploadfile = $uploaddir . basename($_FILES['name']);
$withoutextension = substr($uploadfile, 0, strrpos($uploadfile, ".txt"));
$fileD = $uploaddir . $withoutextension.date('m-d-Y-Hi').".txt";
(move_uploaded_file($_FILES['file']['tmp_name'], $fileD))
?>
Any takers? Cheers.

Simple PHP Image Move

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/.

Convert $_Files['userfile']['name'] to variable

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.

finding the extension a file on upload?

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;
}

how i rename this file?

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.

Categories