I am trying to have a form wherein people can submit files to be uploaded and subsequently linked into a mySQL database.
In the html/php file:
<form enctype=”multipart/form-data” action="process_file.php" method="post" >
<!-- First/Last Name input boxes -->
<p>
<label for="fileUpload" id="fileUploadLabel">Proposal File (5MB Maximum):</label>
<input type="file" name="fileUpload[]" id="fileUpload" />
</p>
<input type="submit" name="submit" id="submit" />
</form>
And the process_file.php file:
<?php
require("../../include/utility.php");
if($_SERVER["REQUEST_METHOD"]=="POST") {
print_r($_FILES);
$dbconn = connectToDB();
// Get and clean the data.
$fname = cleanInput($_POST["fname"]);
$lname = cleanInput($_POST["lname"]);
$new_filename = str_replace(' ','', basename($_FILES['fileupload']['name']));
$imageFileType = pathinfo($_FILES['fileUpload']['name'],PATHINFO_EXTENSION);
printf("File name: $new_filename <br />\n");
$target_dir = "../proposals/2016";
$target_file = $target_dir . $lname . "_" . $fname . "_proposal" . $imageFileType;
printf("File Type is: $imageFileType <br />\n");
}
/* [REDACTED] */
?>
The print_r($files) always gives me "array()". I've looked around online over the weekend and quite a bit of today to no avail.
I've checked the enctype, I've checked the spelling, the capitilization, adding/removing the "[]" and anything else I could think of.
I know it works with the server's settings since others on the same exact server have been able to get this to work.
Does anyone have an idea as to why this is not working? (I can provide more out of the [REDACTED] section, but since $_FILES is empty the code doesn't work anyways.
Going through your code:
”multipart/form-data” - Those curly quotes are choking your script.
Those should have been regular " quotes:
"multipart/form-data"
Then your file input holds this name attribute name="fileUpload[]" yet, you're using $_FILES['fileupload'] where the array is in complete lowercase.
Arrays are case-sensitive and should have read as $_FILES['fileUpload'].
I also noticed that and if 2016 is a folder, this $target_file = $target_dir . $lname will translate to 2016FILE.xxx instead of probable intended 2016/FILE.xxx.
So if that's the case, then you need to add a trailing slash to it proposals/2016/.
Make sure that all folders have proper permissions to be written to.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Related
As for an assignment I created a filter that modifies a Config that's connected to an API which prints out Order files. The web application has the option to save the modified Orderlist with a date and number added to it.
I've been asked to add a feature that allows my task giver to remove the order files he wishes to delete. I've asked a question before how I could remove a file through a file input, but this doesn't seem to be efficient considering it'll be eventually thrown in a private server. Now the best idea was to include the directory and print it out in a list, allowing the user to select the file they wish to remove.
With a lot of looking around I tried to find something that suited my resolve to this as best as I could and stumbled on this. It does print out an array and show checkboxes, but the file names(example Order file 26-1-2021 version 1.xml) are not displayed right next to the checkboxes. - My second question: How do I delete the order file you specifically checked through the submit button?
my code
<?php
$dir = '..\api-ivolved\s_orderlist';
$files1 = scandir($dir, 1);
foreach ($files1 as $filename => $n) {
echo "<input type=\"checkbox\" name=\"files[]\" value=".$filename."/>";
}
if (isset($_POST['delete'])){
unlink( /* Value here */ );
}
?>
<form class="deleteFile" method="get" enctype="multipart/form-data">
<input type="submit" id="delete" value="Delete file"/>
</form>
It appears you are checking $_POST for the delete flag rather than $_GET. Because your form submits using "get", this will cause it to never detect the delete checkbox. I've added a corresponding "delete" field/checkbox within your form to reference the field you are checking for.
For displaying the filenames besides the textbox, you will need to output this separately. I've added this after the checkbox itself, followed by a line break.
I've also "buffered" your input fields so that they get outputted inside of the form tags (rather than before).
Try something like this:
<?php
$dir = '..\api-ivolved\s_orderlist';
$files1 = scandir($dir, 1);
// We need to output the fields AFTER the opening form field. We "buffer" them for now and output them later.
$fields = "":
foreach ($files1 as $filename => $n) {
// Output the filename beside the textbox.
$fields .= "<input type=\"checkbox\" name=\"files[]\" value=".$filename."/>" . htmlspecialchars($filename) . "<br />";
}
if (isset($_GET['delete'])){
// Make sure files are checked/marked for deletion.
if (!empty($_GET['files'])) {
// Loop through each file and delete
foreach ($_GET['files'] as $file) {
unlink($file);
}
}
}
?>
<form class="deleteFile" method="get" enctype="multipart/form-data">
<?php echo $fields; ?>
<br />
<strong> Delete checked files? </strong> <input type="checkbox" name="delete" value="1"/><br />
<input type="submit" id="delete" value="Delete file"/>
</form>
It's worth noting to make sure that you have robust permissions checking in your application, since a simple link will cause a file to be deleted. This can technically cause a CSRF vulnerability (a special type of vulnerability that would allow someone to create a image/link on another website with a full link to do unwanted business). To prevent this, look into adding CSRF tokens to check links in your script (various robust guides exist online for this sort of thing) :)
The question posed is a little different to the original so I hope the following helps you resolve your confusion.
<?php
$dir=__DIR__ . '/api/s_orderlist';
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST[ 'files' ] ) ){
ob_clean();
#process supplied files array - delete each file found. Fail silently
$files=$_POST['files'];
foreach( $files as $file ){
$filepath=sprintf('%s/%s',$dir,$file);
if( file_exists( $filepath ) )#unlink( $filepath );
}
#redirect back to the same page using GET to avoid POSTing again if page is reloaded.
exit( header( sprintf('Location: %s', $_SERVER['SCRIPT_NAME'] ) ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<form method='post'>
<?php
# find the files in target directory
$col=glob( $dir . '/*.*' );
#iterate through files, create checkbox for each file
foreach( $col as $file ){
printf(
'<label style="width:100%%;display:block;padding:0.5rem">
<input type="checkbox" name="files[]" value="%1$s" />%1$s
</label>',
basename( $file )
);
}
?>
<input type='submit' />
</form>
</body>
</html>
I wrote a small PHP-Script for posting comments on my Website. Unfortunately it doesnt work. When i hit the Post-Button, the Page is reloading, but my Form dissapears and the content of comments.html is not shown...
Here is my code:
<?php
if($_POST)
{
$name = $_POST('name');
$content = $_POST('commentContent');
$handle = fopen("comments.html","a");
fwrite($handle,"<b>" . $name . "</b>:<br>" . $content . "<br>");
fclose($handle);
}
?>
<form action = "" method = "POST">
Kommentare: <textarea rows = "10" cols = "30" name = "commentContent"></textarea><br>
Name: <input type = "text" name = "name"><br>
<input type = "submit" value = "Post!"><br>
</form>
<?php include "comments.html"; ?>
I have set the Permissions 777 for the file "comments.html" for testing and its in the same folder as my other php and html files. I am using HTTPS by LetsEncrypt, just for case thats relevant.
I would be very happy for any ideas. :)
Have a nice evening!
That's because the syntax is $_POST['var'] (a superglobal) using square brackets and not $_POST('var') with parentheses.
The manuals on superglobals, forms and error reporting would have been of use.
http://php.net/manual/en/language.variables.superglobals.php
http://php.net/manual/en/tutorial.forms.php
http://php.net/manual/en/function.error-reporting.php
You should also check if any inputs are empty.
http://php.net/manual/en/function.empty.php
if($_POST) isn't enough.
I am trying to enter some data into a database and upload an image to a specific directory. I am using the following script which is a modified version of the top voted answer to this question: How to store file name in database, with other info while uploading image to server using PHP?
require($_SERVER['DOCUMENT_ROOT']."/settings/functions.php");
// This is the directory where images will be saved
$target = $_SERVER['DOCUMENT_ROOT']."/safetyarticles/images/";
$target = $target . basename( $_FILES['article_img']['name']);
date_default_timezone_set("America/Chicago");
// This gets all the other information from the form
$article_name = $_POST['article_title'];
$article_date = date("m/d/Y");
$article_creator = $_POST['article_creator'];
$article_views = "0";
$article_content = $_POST['article_content'];
$article_content_2 = $_POST['article_content_2'];
$article_img = ($_FILES['article_img']['name']);
$article_credit = $_POST['article_credit'];
// Connect to database
$conn = getConnected("safetyArticles");
// moves the image
if(move_uploaded_file($_FILES['article_img']['tmp_name'], $target))
{
// if upload is a success query data into db
mysqli_query($conn, "INSERT INTO currentArticles (article_name, article_date, article_creator, article_content, article_content_2, article_img, article_credit)
VALUES ('$article_name', '$article_date', '$article_creator', '$article_views', '$article_content', '$article_content_2', '$article_img', '$article_credit')") ;
echo "The file ". basename( $_FILES['article_img']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
I have successfully connected to my database since my getConnected() function contains error handling for if the connection fails.
For some reason I keep getting the Sorry, there was a problem uploading your file. error from the bottom of the script.
Am I missing something? All I did was change some minor lines here and there such as how the database connects, and the variables. I also moved the query to only happen if the file uploads.
I'm not sure what I'm missing.
Is it also possible to modify this current script to rename the image to whatever the value of $article_name is? For example if the article name is "This Is The First Article" then the image would be this-is-the-first-article.jpg?
My HTML form is:
<form method="post" action="http://example.com/admin/articleCreate.php" enctype='multipart/form-data'>
<input type="text" name="article_title" placeholder="What Is The Name Of This Article?" id="article_title_input">
<textarea name="article_content" placeholder="Write The Top Half Of Your Article Here." id="article_content_input"></textarea>
<input type="file" name="article_img" placeholder="If The Article Has An Image, Upload It Here." id="article_img_input">
<textarea name="article_content_2" placeholder="Write The Bottom Half Of Your Article Here." id="article_content_2_input"></textarea>
<input type="text" name="article_creator" placeholder="Who Is Writing This Article?" id="article_creator_input">
<input type="text" name="article_credit" placeholder="If This Article Is Copied, What Website Was It Taken From?" id="article_credit_input">
<input type="submit" value="Submit">
</form>
And I did var_dump(is_uploaded_file($_FILES['article_img']['tmp_name'])); and it's returnign true.
Sidenote edit: This being before you edited your question with only one of them being renamed. https://stackoverflow.com/revisions/36367407/4
$_FILES['photo']
$_FILES['uploadedfile']
are two different file arrays and you're using name="article_img" as the name attribute.
You need to use the same one for all of them.
Error reporting http://php.net/manual/en/function.error-reporting.php would have told you about it.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional edit:
$target = $target . basename( $_FILES['photo']['name']);
if that's your real edit, still the wrong array name.
I think the problem is in this line:
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
Change it to this:
if(move_uploaded_file($_FILES['article_img']['tmp_name'], $target))
Your html has:
<input type="file" name="article_img" placeholder="If The Article Has An Image, Upload It Here." id="article_img_input">
And your php is waiting for $_FILES['photo']['tmp_name']
Change your html file input to:
<input type="file" name="photo" placeholder="If The Article Has An Image, Upload It Here." id="article_img_input">
I am trying to upload a file from a php form.
I have verified the target location with my ISP as being "/home/hulamyxr/public_html/POD/"
I get the below error when executing the page:
Warning: move_uploaded_file(/home/hulamyxr/public_html/POD/ 1511.pdf) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/hulamyxr/public_html/hauliers/include/capturelocal2.php on line 124
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpyp3ERS' to '/home/hulamyxr/public_html/POD/ 1511.pdf' in /home/hulamyxr/public_html/hauliers/include/capturelocal2.php on line 124
POD Successfully uploaded for delivery 1511. filename: :
My Form Code
<form enctype="multipart/form-data" method="post" action="capturelocal2.php">
<input type=file size=6 name=ref1pod id=ref1pod>
</form>
My PHP Code to upload the file
$ref1 = $_POST[ref1]; //this is the name I want the file to be
$ref1pod = $_POST[ref1pod]; // this is the name of the input field in the form
move_uploaded_file($_FILES["ref1pod"]["tmp_name"],
"/home/hulamyxr/public_html/POD/ " . ($ref1.".pdf"));
Any assistance will be greatly appreciated.
Thanks and Regards,
Ryan Smith
There is an error in your code:
You need to change your move_uploaded_file funciton. There is an extra space i think which is causing the problem:
move_uploaded_file($_FILES["ref1pod"]["tmp_name"],"/home/hulamyxr/public_html/POD/" .($ref1.".pdf"));
Also i am not sure where is the
$ref1 = $_POST[ref1]; //this is the name I want the file to be
$ref1pod = $_POST[ref1pod];
coming from .There is no such values in your form. Did you upload only the form with upload only. Also be sure to put quotes around attribute values in your form and post value.
Is ref1 and ref1pod are constants. If you din't put quotes PHP will take it as constants. If they are not constants change to:
$ref1 = $_POST['ref1']; //this is the name I want the file to be
$ref1pod = $_POST['ref1pod'];
Also in your form, put quotes:
<form enctype="multipart/form-data" method="post" action="capturelocal2.php">
<input type="file" size="6" name="ref1pod" id="ref1pod"/>
</form>
Be sure you set permissions to your upload folder .
Hope this helps you :)
Check folder names, they should be case sensitive, and also check if POD folder has 777 rights(CHMOD)
Agreed with Phil, remove the space between string and file name
"/home/hulamyxr/public_html/POD/ " . ($ref1.".pdf"));
^
|
and you can also try the following :
$ref1 = $_POST[ref1];
$file_name = $_SERVER['DOCUMENT_ROOT'] . '/POD/' . $ref1 . '.pdf';
move_uploaded_file($_FILES['ref1pod']['tmp_name'], $file_name);
Please try following code.
<?php
if(isset($_REQUEST['upload'])) {
$filename = $_FILES['ref1pod']['tmp_name'];
if (file_exists($_SERVER['DOCUMENT_ROOT']."/POD/".$_FILES["ref1pod"]["name"]))
{
echo $_FILES["ref1pod"]["name"] . " Already Exists. ";
}
else {
$path = $_SERVER['DOCUMENT_ROOT']."/POD/".$_FILES['ref1pod']['name'];
move_uploaded_file($filename,$path);
}
}
?>
<form enctype="multipart/form-data" method="post" action="">
<input type=file size=6 name=ref1pod id=ref1pod>
<input type="submit" name="upload" value="upload" />
</form>
http://patelmilap.wordpress.com/2012/01/30/php-file-upload/
For some reason my PDF upload form is failing consistently, I have this code:
<?php
if($_POST["submit"] == "Add PDF to Comm and Special Projects")
{
$addsubp = $_POST["addsubp"];
$addsubp_name = $_POST["addsubp_name"];
$commuploadedfile = $_FILES['uploadedfile']['name'];
$sqldoc = "INSERT INTO projects_links (pid, display_name, link) VALUES ('".$addsubp."','".$addsubp_name."','".$commuploadedfile."')";
mysql_query($sqldoc) or die(mysql_error());
echo "<BR>";
$target_path = "D:\\Hosting\\69903\\html\\pdfs\\comm\\";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "<br>The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded<br>";
} else{
echo "<br>There was an error uploading the file, please try again.<br>";
}
}
?>
<form method="post">
Add PDF to Project for Committees and Special Projects <br>Choose Project<select name="addsubp"><?php
$query = "SELECT
projects.*
FROM
projects";
$showresult = mysql_query($query);
$csp_c = 1;
while($buyarray = mysql_fetch_assoc($showresult))
{
echo "<option value=".$buyarray['id'].">".$buyarray["pname"]."</option>";
}
?></select><br>
Choose Display Name for PDF <input type="text" name="addsubp_name" /> <Br>
Choose PDF: <input name="uploadedfile" type="file" /> <Br>
<input type="submit" value="Add PDF to Comm and Special Projects" name="submit" />
</form>
I have made sure that the application has write privileges to the "comm" directory. I have godaddy and used the file manager to make sure of that. I have had problems with permissions in this project before, so I know this isn't case. It keeps printing
There was an error uploading the file, please try again.
It doesn't attempt to upload any PDF at all, what am I doing wrong?
thanks!
You may have permissions issues, but for file uploads your form tag should contain the proper enctype attribute.
<form enctype="multipart/form-data" method="POST">
and defining a file size limit is also a good idea:
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
try checking the Upload error message: http://php.net/manual/en/features.file-upload.errors.php
Your code is blindly assuming the file upload succeeded. At bare minimum you should have something like
if ($_FILES['uploadedfile']['error'] === UPLOAD_ERR_OK) {
... handle the upload
}
Your code is vulnerable to SQL injection. You do not escape any of the 3 values you're inserting into the database
You're creating the database record before making sure the file was successfully moved into the target directory. What happens if the file can't be written for any reason (as it is now with your problem)? The database will say it's there, file system will say it isn't
You're not checking for file collisions. If two seperate uploads send "file.txt", the second upload will overwrite the first one.
You're storing the files with the user-supplied name, which is under user control. If this file is web-accessible, anyone with access to your upload form can upload anything they want (e.g. a php file) and the server will happily execute it for them.