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.
Related
So i want my page to show the image whose path I am getting from the mysql database and displaying on the same screen. This is my code, I have tried everything, please let me know where I'm going wrong.
while ($row = mysqli_fetch_array($return_data)) {
echo "ID:".$row['demo_id']."<br>";
echo "Name: ".$row['demo_name']."<br>";
echo "Version: ".$row['demo_version']."<br>";
echo "Details: ".$row['demo_details']."<br>";
echo "File Link: ".$row['file']."<br>";
$new = $row['file'];
echo '<img src = \"$new\"/>';
}
mysqli_free_result($return_data);
echo "Data retrieved successfully!"."<br>";
?>
<img src = "<?php echo $new?>">
echo "File Link: " returns me the whole path of the uploaded file.
How do I render the image at that path in the same page?
neither of the image tags are working. Thanks in advance!
edit
File Link: C:/Apache24/htdocs/demo_webpages_project/neweruploads/footer.jpg
this is the path I get as an output.
Basically this is the folder where I have uploaded the image from another php file
<?php
//this module is used to temporarily store the uploaded file to the server
$target_dir = "random/"; //we randomly assign a value to the upload target directory
$target_file = $target_dir . basename($_FILES["image_file"]["name"]); /*here ["name"] is the original name of the file before it was updated
target file is assigned this name by appending it to the $targer_dir
now target_file is the uploaded file name along with the path*/
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);/*this returns various kind of info about the path for eg Directory, Basename
in our case it returns extension of the file*/
//this sub module is to check whether the file is really an image file
if(isset($_POST["submit"])) { //isset is used to confirm whether the value has actually being submitted
$check = getimagesize($_FILES["image_file"]["tmp_name"]);/*here ["tmp_name"] is the location of temporary file on server
getimagesize confirms image format by returning dimensions etc*/
if($check !== false) {
echo "A file is of an image format<br>";
}
else {
echo "The file is not an image!<br>";
}
}
//Test module to upload files to a destination directory and check whether they have been uploaded or not
if (is_uploaded_file($_FILES['image_file']['tmp_name']) && $_FILES['image_file']['error']==0) { /*code to check two things: 1. whether the file exists in the temp memory 2. whether the file has any error*/
$path = 'C:\Apache24\htdocs\demo_webpages_project\neweruploads\\' . $_FILES['image_file']['name']; /*this sets the destination directory(along with expected file name)*/
if (!file_exists($path)) { //if the file does not exists at that path
if (move_uploaded_file($_FILES['image_file']['tmp_name'], $path)) { //use the php file move function to move it
echo "The file was uploaded successfully."; //success
}
else {
echo "The file was not uploaded successfully."; //failure
}
}
else {
echo "File already exists. Please upload another file."; //detects existence of file with exact same name
}
}
else {
echo "The file was not uploaded successfully."; //if any problem with original uploading
echo "(Error Code:" . $_FILES['image_file']['error'] . ")";
}
?>
Does this help?
edit 2
http://localhost:8080/demo_webpages_project/download.php?project_name=footer&version=&submit=Search
this is my local directory path.
the solution you provided is allowing me to read images which are in the demo_webpages_project folder pointing directly there), not to neweruploads folder
If your uploaded files are stored in the neweruploads subdirectory, then replace this code:
$new = $row['file'];
echo '<img src = \"$new\"/>';
By this one :
$new = basename( $row['file'] ); // GET FILE NAME ONLY, GET RID OF PATH.
echo '<img src = \"neweruploads/$new\"/>'; // FILENAME WITH UPLOAD PATH.
▲
Need to insert uploaded file into respected folder
Here i am creating folder based on unique id.
I am not able to insert file into the folder.
when file is uploaded both file and folder are stored separately.
if ($file_check_error == 0){
if(move_uploaded_file($file['tmp_name'],$upload_directory.$path)){
echo"inside 2"."<br>";
echo"Your File Successfully Uploaded";
}
$path_user = '/home/devestctrl/public_html/wp-content/plugins/est_collaboration/Files/'.$send_id;
if (!file_exists($path_user)) {
if (mkdir( $path_user,0766,false )) {
$path_move = $path_user."/".$path;
echo $path_user;
rename($path,$path_move);
echo "Success+++++++++++";
}
else{
echo $path;
echo "Failure+++++++++++";
}
}
}
$send id is unique id.
Please let me know where i have gone wrong?
You are messing up your logic. First you move your uploaded file
if (move_uploaded_file($file['tmp_name'], $upload_directory.$path)) {
and only than you try to create new directory
if (mkdir($path_user,0766,false )) {
and only if current user never uploaded anything you rename file moving it to other dir
rename($path,$path_move);
Correct logic:
Format uploaded file path $path = $upload_directory.DIRECTORY_SEPARATOR.$send_id
Check if dir exists file_exists($path)
If not exists, create it mkdir($path, 0766, false)
Upload file move_uploaded_file($file['tmp_name'], $path)
E.g.:
$path = $upload_directory.DIRECTORY_SEPARATOR.$send_id;
if (!file_exists($path)) {
mkdir($path, 0766, false);
}
move_uploaded_file($file['tmp_name'], $path);
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 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.
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".