uploading files to server php - php

I tested my code locally and everything works fine, I tried with 0777 and 0755 permissions on server for the folders and still the upload of a file is not working. My code is:
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '..\uploads';
if (!empty($_FILES)) {
foreach ($_FILES['file']['tmp_name'] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tempFile = $_FILES['file']['tmp_name'][$key]; //temporary file
$file_name = mt_rand(1000000,9999999); //generate the number for file name
$imageName = $file_name.'.' . pathinfo($_FILES['file']['name'][$key],PATHINFO_EXTENSION); // set the new file name
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; //target path where the image will be stored
$targetFile = $targetPath. $imageName; // set the target path and image, url
move_uploaded_file($tempFile,$targetFile); //move the uploaded file
echo 'BCK../uploads/'. $imageName;
}
}
}
I tried almost everything. And uploading is still not working. This .php script returns response like this:
BCK../uploads/5631131.jpg
So obviously there is a file, but it is not uploaded.
HTML code is:
<form action="action.php" enctype="multipart/form-data" class="dropzone" style="float:left; background-image: url(design.png); ">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
Any help or advice would be appreciated since I now tried everything and still no result.
response i get local:
tempFile C:\xampp\tmp\php89FF.tmp
file_name 4337681
imageName 4337681.jpg
targetPath C:\xampp\htdocs\designer\pk\../uploads\
targetFile C:\xampp\htdocs\designer\pk\../uploads\4337681.jpg
BCK../uploads/4337681.jpg
response i get on server:
tempFile /tmp/phpjs6s9x
file_name 5394604
imageName 5394604.jpg
targetPath /var/www/designer/pk\..\uploads\
targetFile /var/www/designer/pk\..\uploads\5394604.jpg
BCK../uploads/5394604.jpg

try to change this line:
$storeFolder = '..\uploads';
to this:
$storeFolder = '..' . $ds . 'uploads';

I tested your code and had to add a few things to make it work, which will most likely work for you as well.
method="post" was missing in:
<form action="action.php" enctype="multipart/form-data" class="dropzone" style="float:left; background-image: url(design.png); ">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
which is required when uploading files.
Also, missing square brackets for name="file" which should read as name="file[]" - It didn't work for me till I added it, because of the foreach argument.
foreach ($_FILES['file']['tmp_name'] as $key => $error)
The brackets are required when using a foreach and multiple files, so that it's treated as an array.
Your form should now read as:
<form action="action.php" method="post" enctype="multipart/form-data" class="dropzone" style="float:left; background-image: url(design.png); ">
<div class="fallback">
<input name="file[]" type="file" multiple />
<input type="submit" name="submit" value="Upload">
</div>
</form>
I added <input type="submit" name="submit" value="Upload"> since I didn't see it in your posted code.
You also could change $storeFolder = '..\uploads'; to $storeFolder = '../uploads'; with a / instead of \ but that might not make a difference, yet on some systems it does; I've seen it happen before.

You need to make create your target path folders if not created and consider not creating them if already exist. You need also to make sure that, the destination folder is writable. use "docroot" for referring to the root folder on your server. You can use something like this
if($_FILES )
{
$user_id=$_GET['user_id'];
$device_id=$_GET['device_id'];
$backup_id=$_GET['backup_id'];
$images_folder='images';
$target_path=DOCROOT.$user_id.'\\'.$device_id.'\\'.$backup_id.'\\'.$images_folder.'\\';
if ( ! is_dir($target_path) OR ! is_writable($target_path))
{
mkdir($target_path, 0777, TRUE);
}
$target_path = $target_path .$_FILES['uploadedfile']['size']. basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{
$image_path=$target_path;
$image_size=$_FILES['uploadedfile']['size'];
$image = ORM::factory('image');
$image=$image->new_image($_GET['backup_id'],$image_path,$image_size,$_GET['mobile_path'],file_get_contents($_FILES['uploadedthumb']['tmp_name']));
echo "Server: Image: ".basename( $_FILES['uploadedfile']['name']).", uploaded successfully";
}
else
{
echo "Server: Error";
}
}
else
{
echo "no file attached";
}

Related

How to get a input from user to use as url path directory in php

i am working on a upload page for customers to upload some files into wordpress site. The point of doing that is get some numbers from users as variable and create the folder by using that variable. Here is my code, it actually creates a folder and puts the image inside the folder successfuly. What i want is if user inputs "5389" as number, than folder should be uploaded in "/wp-content/useruploads/5389/image.png"
here is my code
<?php /* Template Name: Create Custom Upload Path */ ?>
<?php
global $wp_filesystem;
WP_Filesystem();
$content_directory = $wp_filesystem->wp_content_dir() ;
$wp_filesystem->mkdir( $content_directory . 'useruploads' );
$target_dir_location = $content_directory . 'useruploads/';
if(isset($_POST["submittheform"]) && isset($_FILES['fileToUpload'])) {
$name_file = $_FILES['fileToUpload']['name'];
$tmp_name = $_FILES['fileToUpload']['tmp_name'];
if( move_uploaded_file( $tmp_name, $target_dir_location.$name_file ) ) {
echo "File was successfully uploaded";
} else {
echo "The file was not uploaded";
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submittheform">
</form>
i tried to have one more post method and get build number, then use it as variable but was not able to make it happen. any suggestions are appreciated

How to create an upload form with upload and custom filename in php?

Hi there I'm trying to create an upload form in php. Containing, upload input, text input (name to be given to the file that was uploaded), and submit button. However I don't know much about php, so I don't know how to actually link that what I had typed on the <input type="text"/> becomes the name of the file when uploaded. If someone can help ? Thanks.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Tu peux uploader ici ta video.</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<p>Upload your file</p>
<input type="file" name="uploaded_file"></input><br />
<input type="text" name="file-name"></input><br /> <!-- [ASK]: How to make this the file name of the uploaded file -->
<input type="submit" value="Upload"></input>
</form>
</body>
</html>
<?PHP
if(!empty($_FILES['uploaded_file']))
{
$path = "uploads/";
$path = $path . basename( $_FILES['uploaded_file']['name']);
​
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
?>
move_uploaded_file ( string $filename , string $destination ) takes filename which is the filename of the uploaded file and destination is the destination of the moved file. Note that destination directory must exist; move_uploaded_file() will not automatically create it. So lets get the name now...
$_FILES['uploaded_file']['tmp_name'] gives you the temporary filename of the file in which the uploaded file was stored on the server eg. C:\Users\USER\AppData\Local\Temp\phpD3C.tmp
while
$_FILES['uploaded_file']['name'] gives you the actual name which you need to extract the extension eg. myfile.jpg
To link that what you had typed on the , first get it via $_POST["file-name"], then concatenate with the extension. Use pathinfo to retrieve the original extension.
Change your code to become...
<!DOCTYPE html>
<html>
<head>
<title>Tu peux uploader ici ta video.</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<p>Upload your file</p>
<input type="file" name="uploaded_file"></input><br />
<input type="text" name="file-name"></input><br /> <!-- [ASK]: How to make this the file name of the uploaded file -->
<input type="submit" value="Upload"></input>
</form>
</body>
</html>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(!empty($_FILES['uploaded_file']))
{
$file_parts = pathinfo(basename( $_FILES['uploaded_file']['name'])); //access the actual name instead of tmp_name
//just pick the extension of the file_parts and concatenate it to your path
$path = 'images/';
$path = $path . $_POST["file-name"] . "." . $file_parts['extension'] ;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo "The file ". basename($path) ." has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
This should get you the desired name. So if you upload file dog.php and in the text field you have cow, the resulting name should be cow.php.
Result:

How to send file to $_FILE through html form?

Well pretty simple question.. But can't get it right for some reason.
What would be the html code to send a file to this?
move_uploaded_file($FILES["upload"]["tmpname"], $_POST["name"]);
Here's mine but when I used it and echo/vardump everything, I only have 'name' and not the file
<form action="uploader.php" method="post" id="myForm" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="upload" id="upload">
<input type="text" name="name" id="name">
<button name="submit" class="btn btn-primary" type="submit" value="submit">Upload File</button>
</form>
Thank you
i try to add a comment but i can't
first check if upload permission is on in php.ini
file_uploads = On
If it set to on check your upload directory which you added in uploader.php file and use if to check $_FILES['upload'] is empty
this is a simple code to uploader.php file
<?php
if(!empty($_FILES['upload']))
{
$path = "upload/"; /// directory to upload
$path = $path . basename( $_FILES['upload']['name']);
if(move_uploaded_file($_FILES['upload']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['upload']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}else {
echo 'No file selected to upload ';
}

upload a file using FTP and php

I can't Upload the file using php because i can't send the path i got from the html file to the function FTP_PUT because it only takes string "test.txt"
How Can i send the Path to this function
PHP FILE
$file = $_POST["file"];
// upload file
if (ftp_put($ftp_conn, $file, $file, FTP_BINARY))
{
echo "Successfully uploaded $file.";
}
else
{
echo "Error uploading $file.";
}
// close connection
ftp_close($ftp_conn);
HTML FILE
    
<div class="container">
 
          <div class="row">
            <div class="col-lg-12">
               <form class="well" action="Upload.php" method="post" >
                  <div class="form-group">
                    <label for="file">Select a file to upload</label>
                    <input type="file" name="file" id="file">
                   <!-- <p class="help-block">Only jpg,jpeg,png and gif file with maximum size of 1 MB is allowed.</p> -->
                  </div>
                  <input type="submit" class="btn btn-lg btn-primary" value="Upload">
                </form>
            </div>
          </div>
    </div>
Use $_FILES["file"]["tmp_name"] instead of $_POST["file"]
edit:
$file = $_FILES["file"]["tmp_name"];
$file_name = $_FILES["file"]["name"];
// upload file
if (ftp_put($ftp_conn, $file_name, $file, FTP_BINARY))
or move the uploaded file first:
$target_path = "uploads/".basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_path);
Change your form tag to :
<form class="well" action="Upload.php" method="post" enctype="multipart/form-data">
If you don't include
enctype="multipart/form-data"
Nothing will get uploaded!
Check that the path is correct... I don't know your file structure so I'm guessing you need the full path, try...
if (ftp_put($ftp_conn, getcwd().$file, $file, FTP_BINARY)

uploading different types of files mostly pdfs

I would like to upload different types of files pressumably pdfs to a certain directory I am currently trying to get this one script working that I found on snipplr but it is not working as I assumed it would, here is my code.
Never mind I had an extra comma in my code
UPDATE: I added some more code in comments below, I want to also add the filename to a field in a datatbase, currently the script I have breaks the page nothing loads I am not sure why since it seems to work on other pages I have.
<?php
if( isset($_POST['submit']) )
{
$target_path = "../downloads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name'])." has been uploaded";
/*
$title = basename( $_FILES['uploadedfile']['name']);
$sql = sprintf("INSERT INTO forms (title)VALUES('%s')",
mysql_real_escape_string($title)
);
$results = mysql_query($sql)or die(mysql_error());
*/
} else{
echo "There was an error uploading the file, please try again!";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<input type="file">
<input type="submit" name="submit" value="submit" />
</form>
Apart from the directory existing, file permissions, etc., you might want to give your input a name:
<input type="file" name="uploadedfile">

Categories