PHP Form - File upload not working [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Trying to allow file upload along with a form that is otherwise working. I cut out the relevant form/input/processing rules. Hopefully someone who is more than ankle-deep in PHP (as I am) can point me in the right direction?
<form name="form-quote" id="form-quote" enctype="multipart/form-data" action="<?php echo $_SERVER['../WPTheme/REQUEST_URI' . '#form-quote'] ?>" method="POST">
<div class="form_labels">
<p><label for="fileupload">Upload File (optional):</label></p>
</div>
<div class="form_inputs">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
<p><input type="file" name="fileupload" id="fileupload" accept=".pdf, .txt, .rtf, .doc, .docx, .xls, .xlsx" style="margin-bottom:2px;"/>
<span style="color:#777;">(pdf, txt, rtf, doc, docx, xls, xlsx, <5MB)</span></p>
</div>
<input type="hidden" name="formtype" id="formtype-quote" value="quote">
<div class="form_labels submit">
<p> </p>
</div>
<div class="form_inputs">
<input type="submit" value="Submit" name="action" class="btn-red" >
</div>
</form>
<?php
//$formerrors is set to false unless one of the validation rules for the OTHER fields fails - no validation on the file upload, although I would like to trim & sanitize it if possible.
if (!($formerrors) && isset($_POST['fileupload'])):
$tmp_name = $_FILES["fileupload"]["temp_name"];
$uploadfilename = $_FILES["fileupload"]["name"];
$savedate = date("mdy-Hms");
$newfilename = "/wp-content/uploads_forms/" . $savedate . "_" . $uploadfilename;
$uploadurl = 'http://' . $_SERVER['SERVER_NAME'] . $newfilename;
if (move_uploaded_file($tmp_name, $newfilename)):
$msg = "File uploaded.";
else:
$msg = "Sorry, your file could not be uploaded." . $_FILES['file']['error'];
$formerrors = true;
endif; //move uploaded file
endif;
?>
Thanks to Alexander's answer below, I was able to modify my validator to work and to achieve my original goals (check for null, and give files unique names before uploading). Here's my "final draft," which is working now.
//Check form errors, check file name not null, rename file with unique identifier to avoid overwriting existing files with same name
if (!($formerrors)) {
$tmp_file = $_FILES["fileupload"]["tmp_name"];
if ($tmp_file != "") {
$savedate = date("mdy-Hms");
$target_dir = "wp-content/uploads/";
$target_file = $target_dir . $savedate . '_' . $_FILES["fileupload"]["name"];
if (move_uploaded_file($tmp_file, $target_file)) {
$msg = "File uploaded.";
} else {
$msg = "Sorry, your file could not be uploaded.";
$formerrors = true;
}//move successful
}//end null check
}//end form errors check

The code you are using above is Javascript. In case you depend on that please change the tags of the post. If not here is a possibility for a PHP-Uploadscript:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileupload"]["name"]);
if (move_uploaded_file($_FILES["fileupload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileupload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
SOURCE: http://www.w3schools.com/php/php_file_upload.asp
EDIT: The script above has be placed in the file receiving the POST from the form.

The code you posted is a big mess!
Let's try to clarify some basic points...
File-upload mechanism
For file-upload to work you must have a <form> with action attribute addressing the script where you'll check and use the uploaded file.
This script may be the same as the one where the <form> is generated, assumed you take care of the pitfalls that come with this situation.
At a first general glance your current code seems to correspond to the latter case.
But your form action looks weird:
action="<?php echo $_SERVER['../WPTheme/REQUEST_URI' . '#form-quote'] ?>"
As a first intent, if you want to address the same page where you already are, you can simply omit action attribute.
Here you seem to explicitely try the same, adding the precision of #form-quote, but:
This #form-quote has no effect here, since such a hash is made to target a <a>, while it's currently affected to your <form>.
The other part of the url you build is a non-sense mixing REQUEST_URI (which is the name of one of the $_SERVER members) with the hard-core expression of a path in your context.
Anyway all the above doesn't matter, because this end with $_SERVER[...something which is not a known $_SERVER member...], so it actually returns NULL, and somewhat ironically it has the same effect as if you didn't specify action at all!
PHP in a SO snippet
So ou put your code in a snippet, but SO snippets work only with HTML, CSS, and Javascript, so you can't expect it allows to demonstrate how your code is working or not.
Note that at this step, despite the errors mentioned above, we didn't point something which would make your code to fail.
And in your question you didn't mention how it fails!
Uploaded file processing
So looking at your PHP code part, I first note this statement:
$tmp_name = $_FILES["fileupload"]["temp_name"];
where you're looking for temp_name, while the true involved key is tmp_name. This alone is enough to make your code to fail.
Furthermore looking at these two statements:
$uploadurl = 'http://' . $_SERVER['SERVER_NAME'] . $newfilename;
if (move_uploaded_file($tmp_name, $newfilename))
In the 1st one you use $newfilename as the complement of the url you're building, so obviously $newfilename can't target an absolute physical path.
It means that in the 2nd one you try to move_uploaded_file() to a wrong place!
Last point, you currently don't take care of possible errors before trying to use the uploaded file.
You should complete your primary condition like this:
if (!($formerrors) && isset($_POST['fileupload'])) && !$_FILES["fileupload"]["error"])
And if you effectively get some errors and have trouble to understand why, you should also look at this interesting PHP manual page.

Related

How to save data from HTML form to text file with node.js?

I want to download text from HTML form to .txt file on my PC. I have tried many ways but nothing works well:
require(fs) doesn't work with the browser, as far as I understand
require(browserify-fs) saves file in VIRTUAL MEMORY (as far as I understand), so it useless for me
last way I found - using PHP script(I found it in net), but it doesn't work, idk why. I have tried to fix it - nothing, I know nothing about PHP
program.php
<?PHP
$title = $_POST["channel0Title"];
$gain = $_POST["channel0Gain"];
$offset = $_POST["channel0Offset"];
$file = fopen('1.txt', 'w');
ftruncate($file, 0);
$content = $title. PHP_EOL .$gain. PHP_EOL .$offset;
fwrite($file , $content);
fclose($file );
die(header("Location: ".$_SERVER["HTTP_REFERER"]));
?>
main.html
<form action="public\scripts\program.php" method="post">
Channel 8 Title:<br><input type="text" name="channel0Title" value="Channel 7"><br>
Gain:<br><input type="text" name="channel0Gain" value="4.000"><br>
Offset:<br><input type="text" name="channel0Offset" value= "6.000"><br>
<input type="submit" id ="submitButton" value="Submit">
</form>
I have a error Cannot POST /public/scripts/program.php
Could you help me please why such a script doesn't work
Or maybe give advice on what language or framework should I use to simplify data transfer between client and server
Thank you in advance!
P.S. I use Node.js, so load program.php as a static file

How do I save form data to a text file?

I know this question has been asked before, but I'm trying to diagnose why this isn't working. I want to write form data into a .txt file using a post request. I don't know much PHP at all, as this is a quick program I'm patching together. Here's the code:
Javascript:
function submitdata() {
document.querySelector("#val").innerHTML = input.value + ": " + input1.value;
document.querySelector("#submitform").submit(); }
HTML:
<form style="display: none;" method="POST" name="myform" id="submitform">
<input id="val" name="val">
</form>
PHP:
<?php
if(isset($_POST['val']))
{
$data=$_POST['val'];
$fp = fopen('data.txt', 'a+');
fwrite($fp, $data);
fclose($fp);
}
?>
How does your browser know where to send the form data?
You need to specify the php file name in form action attribute.
Edit- added relevant point from comment below.
I have pointed out the obvious error based on what you have provided, but it might not be the only one. Other error is you are using innerHTML on an input element. So this may not set the value for #val (some browsers may set the value, some may not).

After redirect, how to display error messages coming from original file?

Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
Any help is certainly appreciated.Thank You
Also it's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
There's multiple ways of doing so. I personally would use AJAX. On a 'form submit', run a javascript function calling an AJAX request to a .php file to check the form information, all using post method. Calculate all the $_POST['variables'] checking for your defined errors. You would have an html element print the errors via AJAX request.
If there are 0 errors then in the request back return a string as so that your javascript function can look for if its ready to go. If ready to go, redirect the user to where ever you please.
AJAX is not hard and I only suggested the idea sense you put javascript in your tags.
Another method:
Having all your code on one .php file. When you submit the form to the same .php file check for the errors (at the top of the file). If $_POST['variables'] exist, which they do after you submit the form, you echo your errors in the needed places. If zero errors then you redirect the page.

console.log in php backend

I did also creating a different class. but still not working...
but if I place the '<script>console.log("message here");</script>' will work..
//index.html
assuming that this is a complete code.
<form action="post.php" method="post">
<input type="text" name="name" id="name"/>
<input type="submit" value="submit"/>
</form>
//post.php
<?PHP
if(isset($_POST['name'])){
echo "<script>console.log('".$_POST['name']."');</script>";
}
?>
my problem is , i cant use console.log in submitting a form. but if I did this in redirection It will work..
The Function under my class is ...
public function console($data) {
if(is_array($data) || is_object($data)) {
echo("<script>console.log('".json_encode($data)."');</script>");
} else {
echo("<script>console.log('".$data."');</script>");
}
}
It does not work within PHP because of the missing " around the String argument of console.log.
The output would've been
<script>console.log(name);</script>
instead of
<script>console.log("name");</script>
Solution
echo '<script>console.log("'.$_POST['name'].'");</script>';
If you are trying to debug or see the value that was posted from the front end to back end then you can simply use the chrome inspector.
Right click anywhere in browser and click inspect element.
click on network tab.
submit your form with desired values.
on the left click on the post.php.
Click on the headers on the right and scroll down to find Form Data.
You will have all your post variables listed there with respective values.
You seem to be trying to debug the $_POST variable, If thats the case, then Please note, that console.log() is a frontend debugging tool used in javascript, and has nothing to do with php.
Few good way of checking the content of variables in php.
1. print_r
This will output the content of a variable that can be an array, object or string in a nice human readable format.
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
2. var_dump
This will output the content of the variable with extra respective details like datatypes and length.
var_dump($_POST);
die();

HTML form: Letting a user Email you with a already made email

So, I want to make a help form that allows users to email me with my already made email instead of using theirs. So what I mean is a form that they can just Enter text, and click the submit button and it sends to me without the user having to do anything more.
What I've tried so far is:
<form action="MAILTO:xeroelixirmain#gmail.com" method="post" enctype="text/plain">
Username:<br>
<input type="text" name="name"><br>
Help comment:<br>
<input type="text" name="mail" value="50"><br>
<input type="submit" value="Send">
</form>
But on Safari (not sure about the other browsers) This opens a new window prompting for the user to fill out an email. How could I do this where it would just send it to my email without them having to write an email themselves, but instead just simply clicking send and having my email (xeroelixiry#gmail.com) preset for the user, so no window will pop up or anything.
To do that you need to have your site uploaded on a host that supports php. It can't be done with only client side scripting.
Html code:
<form id="form" method="post" action="sendMail.php">
<fieldset>
<label>name</label>
<input type="text" name="name"/>
<label>surname</label>
<input type="text" name="surname"/>
<label>e-mail</label>
<input type="text" name="mail"/>
</fieldset>
<fieldset>
<label>message</label>
<textarea name="msg" cols="85" rows="8"></textarea>
</fieldset>
<fieldset>
<input type="submit" value="send"/>
</fieldset>
</form>
PHP code:
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$contact = array('name' => $_POST['name'],
'surname' => $_POST['surname'],
'mail' => $_POST['mail'],
'msg' => $_POST['msg']
);
if ($contact['name'] != "" && $contact['surname'] != "" && $contact['mail'] != "" && $contact['msg'] != "") {
$name = $contact['name'];
$surname = $contact['surname'];
$mail = $contact['mail'];
$msg = $contact['msg'];
// message can be built as you want, you can use html and inline css in it.
$message = "name: ".$name."<br/>"."surname: ".$surname."<br/>".$msg;
$to = "your_mail#gmail.com";
$subject = "subject";
$headers = "From: " . $mail . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);
}
?>
You may need some backend support. Simple javascript + html can't do that because it didn't get connect to a smtp server and send email from that.
As you select php I suppose that's your backend. So you can use the PHP mail component and submit your form into one backend php page and translate the data from the form into the mail function. You can get more from the php doc -> http://www.php.net/manual/en/function.mail.php
To make it easier on you, I have provided an example of the PHP mail function. However, you are going to want to consider adding a few things such as... an input for the subject, which is always handy. Also, make your input area become a text area, I find it easier to write something that I am fully able to see vs. only being able to see a limited view of what I am currently writing.
$messageBody = $_POST['mail'];
$to = 'youremail#whateverworks.com';
mail($to, $_POST['subject'], $messageBody);
I think these are primarily the things you really need to focus on. Take into account you are able to house a fourth parameter, generally a CC, BCC, or a FROM section (in the manual, they refer to it as the 'headers' section), which could also be helpful for you unless you plan to have somebody write their name at the end of the message (probably not very good etiquette).
Now your form.. Well.. You can structure it annnyyywwaaayyy you want.. in fact.. there are multiple ways to skin a cat.. and to create a form.. Here is quick demo of a possibility of making your form a little bit better. And if you want a little bit more reasoning as to why I used an unordered list vs a table, here is a SO Question that can give you some pros and cons over what is better and so forth. My JsFiddle can also give you an idea of how to make the display of your form look... clean.
Also, look into how you want to validate your form... Do you want to do it via PHP, where it will require the user to hit the submit button before it will look through for any errors (maybe to check for a username or for an actual message, thus avoiding spam or unwanted emails) or maybe you want to try to incorporate some browser side scripting with JavaScript to automatically check for these things without even touching that submit button.
Regarding the database, I would advise validating and making sure that you are preventing SQL injections (I will not be the only person to bring this up), which will help protect your database if you plan to upload this message and keep it for a while.
There is much thought that must be placed into creating a form, whether it is the simple HTML code, all the way through MySQL or any database code you may be working with.
Last, please please please look at the manual. In fact, I learn more from the manual now then I do from looking at other people's code because it gives real, working examples to choose from. So visit this site to make your life a little bit easier.
This will allow you to get the values from HTML input text boxes and then pass these values to send Email.Hope it will help..
function BuildEmailBody()
{
var retBody;
retBody = document.getElementById("txtMessage").value;
return retBody;
}
function ProcessSubmition() {
var stringEmailBody = BuildEmailBody(); //the value of 'txtmessage' will asign to stringEmailbody
var stringTo = document.getElementById("txtEmail").value; //Email from textbox of id 'txtEmail'
var stringSubject = document.getElementById("txtSubject").value; //subject from textbox of id 'txtSubject'
window.location.href = "mailto:" + stringTo + "?subject=" + stringSubject + "&body=" + stringEmailBody;
}

Categories