Error during uploading a file with php - php

Ok, I used google over the last 2 days and didn't got what is wrong with my code. First it seemed that I used the wrong path but the official "Hilfe Center" (like helping center or so) from 1&1 said that this must be the right path "e:\Kunden\Homepages\11\d12345678\www\UploadTest" (obviously you have to adapt it to your path, which i got throught phpinfo() )
so I'm using the following code:
<form action=\"upload.php\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"file\" name=\"datei\"><br>
<input style=\"position:absolute;left:5px\" type=\"submit\" value=\"Hochladen\">
</form>
on the site where you upload the file and
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = "e:\\Kunden\\Homepages\\11\\d12345678\\www\\UploadTest";
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.'); // if we upload large file then we get error.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.'); // if we have no enough permission then got error.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)){
// if everything is fine then we upload file and go to somewhere else
header ('location: whereeveryouwantogo.php');
} else {
echo 'There was an error during the file upload. Please try again.';
}
on the site where the php script is running (upload.php). I got the code on another thread here and wanted to use it for troubleshooting. Later I'm going back to my own code.
I am now at the last error:
'There was an error during the file upload. Please try again.';
I just want to upload .txt files that are later used on a news based site. Thx for any helps in advance!

I think the problem is name of the input or name of the files variable.
$files=$_FILES['datei']['tmp_name'];

Related

Permission issues viewing photos uploaded with php

I'm following a tutorial for uploading image files using php on udemy. I can choose an image and upload it to a folder without any problems.
When I click on the image after it has been uploaded to the folder, windows photo viewer says: "photo.png It appears that you don't have permission to view this file. Check the permissions and try again".
When I checked permissions it said "You must have read permissions to view the properties of this file".
I used the chmod function set to 0755, which allows the owner to read and write, and lets everyone else read it. I tried changing the chmod codes but it didn't help.
I'm thinking it has something to do with my server permissions, but can't find any solution on google. My images are uploaded to Abyss Web Server.
Here is the code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function upload_file() {
//setup
$tmp_name = $_FILES['file']['tmp_name'];
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES['file']['name']);
$max_file_size = 5000000; //5mb
$allowed_file_types = array('application/pdf; charset=binary');
$allowed_image_types = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
//check if image type is allowed
$image_check = getimagesize($tmp_name);
if(! in_array($image_check[2], $allowed_image_types)) {
//if not allowed image check if allowed file type
exec('file -bi' . $tmp_name, $file_check);
if(! in_array($file_check[0], $allowed_file_types)) {
return 'This file type is not allowed';
}
}
//check if file already exists
if(file_exists($target_file)) {
return 'Sorry that file already exists';
}
//check file size
if(file_exists($target_file)) {
return 'Sorry this file is too big';
}
//store the file
if(move_uploaded_file($tmp_name, $target_file)) {
chmod($target_file, 0644);
return 'Your file was uploaded';
}
else {
return 'There was a problem storing your file. Try again?';
}
}
if(! empty($_FILES)) {
echo upload_file();
}
?>
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file">
<input type="submit" Value="upload">
</form>
Since loading the file using a custom made HTML page specifically for testing motives does show the image correctly, then it's most likely a hotlink protection issue. (This was found out after a few comments to the question).
In cPanel, for example, there is a tool to manage this feature and it revolves around the usage of a file called .htaccess. This file is used for a lot of things in the web development world.
Some people don't like their copyrighted images to be accessed, so one way to avoid inexperienced people (let's say, "people in userland") from doing that is to enable this protection. This works for any given file extension that you set it up to.
One way to address this issue is to go to cPanel and disable (or modify accordingly) the Hotlink Protection feature. Another way, is to find the .htaccess file that is causing the issue, which requires understanding the way it works and the syntax it uses.

How PHP uploading Documents Works with posting document on the same page of Website?

I have been playing with various php upload examples to get a feel of how it works.
Before my database is in place, I want to understand why when I click my "post comment" button on my form that it goes to another page showing my whole php code. (is this due to database not made yet?)
I also think that I am not understanding the line of code: "$upload_path ="
I put the directory path of the folder containing my text document. From what I have been reading it said it has to be a directory and usually only has examples of just "\files\" or "\uploads\" which doesn't make sense to me.
Also what does:
$filename . '" title="Your File">here</a>'; // It worked.
line of code mean or does?
I want my upload to post to my website. In other words, click upload button and the document displays below the form on the same page.
I have a html form inside a html document and then I have a separate php document.
HTML:
<form id="comments" action="upload.php" method="POST" enctype="multipart/form-data">
Comment: <input type="text" name="comment">
<br>
Text Document: <input type="file" name="documentfile" />
<br>
<input type="submit" name="submit" value="Post comment" class="button">
</form>
PHP:
<?php
$allowed_filetypes = array('.text'); // types of files to use
$max_size = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = '\\ps....\ps.....\w...\Data\Aly...\HTML\TechSite - Copy\TechSite - Copy\files';
$filename = $_FILES['documentfile']['name']; // Get the name of the file and extension.
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get file extension
// Check if the filetype is allowed, if not tell user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Check filesize, if too large tell user.
if(filesize($_FILES['documentfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to path, if not tell user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['documentfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file <a href="' . $upload_path .
$filename . '" title="Your File">here</a>'; // It worked.
else
echo 'There was an error during the file upload. Please try again.';
?>
Once again: I played with examples I found for the php file because I am learning as I go with it. Please let me know if there is something in the php file that doesn't make sense and explain if possible. I'm wanting to understand if my php will be ok once my database is in place. I'd appreciate it!

Upload error - file is not writable

I want to upload multiple files to the server.
As far as I can see files are not writable.
What can I do so my code can actually work and upload files.
PHP:
if(isset($_FILES ['uploaded_files']))
{
foreach($_FILES['uploaded_files']['name'] as $key=>$value)
{
if(is_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key]) && $_FILES['uploaded_files']['error'][$key] == 0)
{
$filename = $_FILES['uploaded_files']['name'][$key];
if (is_writable($filename)) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
if(move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], '../images/gallery'. $filename))
{
//code
}
else
{
die ('There was a problem uploading the pictures.');
}
}
else
{
die ('There is a problem with the uploading system.');
}
}
}
HTML:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" id="input_clone_id" name="input_clone_id" value="'.$row['id'].'"/>
<input type="hidden" id="input_clone_var" name="input_clone_var" value="V"/>
<input type="file" name="uploaded_files[]" id="input_clone" multiple="multiple" /><br />
<input type="submit" style="margin-left:0" value="Upload Files" />
</form>
I see two problems with this. The first is a security issue and the second is probably what is causing your problem
You have a security problem here:
$filename = $_FILES['uploaded_files']['name'][$key];
...
if(move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], '../images/gallery'. $filename))
...
Problem a: Since $filename comes from the $_FILES array, it CANNOT be trusted. The user told your site what the name of their file was and put it there. They could feed you some bogus filename that could cause your script to fail in interesting ways. You need to sanitize that filename before using it in any way.
Problem b: By allowing the user to specify the filename, they could potentially overwrite other files in your "images/gallery" directory simply by specifying a conflicting filename. The way to avoid this is to use a database, generate a unique identifier for the uploaded file, store the file under that unique name, and in the database keep a record of the original filename and other information. That way you always know what the original filename was and you don't have the chance of someone trying to overwrite files in that directory.
Writing problem:*
Your "check for writable" statement is wrong. The filename that comes back is the one that the user used when submitting. This will not point to any point on your filesystem...it points to a spot on theirs (sometimes) which you cannot see. What you need to check is that your "../images/gallery" directory is writable rather than $filename. If that fails, you need to do either "chmod -R 777 gallery" while in the images folder if you have command line access or give it world write access through whatever FTP client you are using if you are using FTP to talk to your server.
So, what you should have instead for that check is:
if (is_writable("../images/gallery")) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
After doing that, if your script comes back and says "the file is writable", it should have been able to copy the file into your images/gallery folder (remember to not use the name of the file the user gave you). If not, perhaps you don't have permissions to move uploaded files.
As for the location of uploaded files, I think sometimes they are deleted after the script execution ends sometimes, but if not, you can echo the 'tmp_name' of the file and if you go to that directory you should find it sitting there. That would be just a verification test to make sure the file was actually getting to your server. So long as you have write permissions (that what chmod 777 does) on the directory you are moving the uploaded file to, you should be able to copy it there.
You are checking to see if a file that you recently uploaded, but not yet saved is writable, I don't think such a file will ever be writable.
Better remove that if, or just check if the folder you are uploading to is writable.
Other than that, I checked your code and it works.

Wordpress Custom Plugin - PHP file uploader in Top-Level Admin Menu - Page not found 404

This is my first Custom Wordpress Plugin that I really need to get done. Been at this ALL night long and can't figure out whats wrong... I'm assuming I'm missing something simple and basic with standard plugin coding.
I wrote a plugin that allows a Top-Level Menu item in the admin dashboard. Its a simple PHP upload form. All I want to do is let the client upload CSV files to a specific folder. I just tested the PHP code OUTSIDE of the wordpress framework and it works... But when I try and upload a file using the actual wordpress admin, I press submit and it doesnt upload the file it also sends me to a "page not found 404"... ON top of that when I activate the plugin on my production site it causes errors and some minor glitches... So I'm assuming I'm just missing some code I need in the plugin php file.
Here is the full code for my plugins main php file - minus the separate php file that handles all the "uploading code"
<?php
/*
Plugin Name: Points Uploader
*/
?>
<?php
add_action( 'admin_menu', 'sheets_plugin_menu' );
function sheets_plugin_menu() {
add_menu_page( 'Upload Points Sheets', 'Upload Points', 'manage_options', 'upload- points-sheets', 'sheets_plugin_page', '', 10);
}
function sheets_plugin_page() {
if ( !current_user_can( 'manage_options' ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
}
echo '<div class="wrap">';
echo '<h1>Upload Points Sheets</h1>';
?>
<form action="uploader.php" method="post" enctype="multipart/form-data">
<label for="file">Select a file:</label> <input type="file" name="userfile" id="file">
<br />
<button>Upload File</button>
</form>
<?php
echo '</div>';
}
?>
So what do I need to add to this php page to make it a more "standard" operating plugin? When I press the submit button its like I'm missing a "wordpress send" code, and it just 404's, I don't know how to make it operate within the Admin screen field. Thank you for any help you can offer, I'm really stumped here. ;)
...ok just in case its needed here is the uploader.php file. Just a sample code I found on the net to test things out.
<?php
// Configuration - Your Options
$allowed_filetypes = array('.csv'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = './upload/'; // The place the files will be uploaded to (currently a 'files' directory).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file here'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed :(.
?>
Being fairly new to using custom uploaders in WordPress, I don't know how much help I will be. but I do know one thing: it's probably 404-ing because your form action is "uploader.php". That's not gonna fly (unless your uploader.php file is located in the root directory of your server) - WordPress doesn't play nicely with relative paths. I'm pretty sure you need to use something like plugin_dir_url() . '/uploader.php' or plugin_dir_path() . '/uploader.php'
You also have to keep in mind that some servers are really picky about whether you use the server path or http path when it comes to uploading files. Many times, when I'm uploading, I have to be sure I'm using the server path to the folder I'm putting the file into (you have a relative path there again = "./upload/". In some cases, it only like the http path. So it's a lot of trial and error (for me anyway) as far as that goes.
Like I said, don't know if it helps much, but maybe it's just a simple switch from relative to absolute paths?

unclear regarding uploading of csv file in php

So I want to:
upload a csv file which will contain a list of student numbers, one to each line (392232, per line).
populate an array with the student numbers (as i already have a process in place of looking up ids from an array of student numbers and storing etc if they were to add students manually)
I have been lookin at a tutorial found here.
however I am slightly confused with this:
if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){...
where does he establish 'tmp_name' from?
anyway, if somebody could explain how I should be going about this I would appreciate the help.
many thanks,
EDIT: added progress of where it is not working.
if(isset($_POST['csv_submit'])){
if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){
//upload directory
$upload_dir = "/ece70141/csv_files/";
//create file name
$file_path = $upload_dir . $_FILES['csv_file']['name'];
//move uploaded file to upload dir
// GETTING THE ERROR BELOW.
if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) {
//error moving upload file
echo "Error moving file upload";
}
print_r($_FILES['csv_file']);
//delete csv file
unlink($file_path);
}
}
$_FILES is a magic superglobal similar to $_POST. It's an array of every file that's been uploaded in the last request, and where that file is stored (tmp_name).
tmp_name is basically generated by the web server to let PHP know where they've stored the file.
You have the following items available to you in each element of the $_FILES array:
name (Original Name of the file)
type (MIME Type of the file, ie. text/plain)
tmp_name (Path to the uploaded files' temporary location)
error (Error occurred when uploading, 0 when no error)
size (Size of the uploaded file, in bytes)
From what I can see in your code, this will work perfectly fine and as discussed in comments, I think the issue lies in your HTML.
The tutorial that you linked to has an incorrect <form ..> tag definition. For file uploads, you're required to set the enctype attribute, below is what it should look like:
<form action="" method="post" enctype="multipart/form-data">

Categories