By way of partial explanation, my mind-set is strongly procedural, since I've been programming that way since the 60s
I'm working in PHP and trying to get my head around form handling starting with an interactive 404 error form. What I want in minimal pseudo-code is:
do {
OK = true;
display_form;
ask for optional name
ask for optional email address
ask for optional comments
on – submit{
sanitise input
validate input (which could be no input since all is optional)
if one or more inputs invalid set OK = false
}
} while (OK == false)
assemble email to webmaster using $_SERVER superglobals as well as input
send using mail function
Someone "helpfully" added curlies after the while AND at the end -- they really don't belong there -- the idea was that I wanted execution to "drop through" to those two statements only after the DO -- WHILE completed
The mail assembly could be in a separate file, or not
While this is a semi-specific problem, I'm working on the assumption that, if I can get this to work, then getting a database update working will be easier.
It seems to me that my whole conceptual algorithm is incorrect, and until I sort that I'm nowhere. I've been banging at this for a a couple of days – Google pointed at a number of semi-relevant answers here, so I'm giving it a go. The W3C examples clearly show the response code running even when there are problems with the input, which is not what I want.
The main switch you need to make here is probably the one to a request-response model of execution. You can't do a literal do..while, since you will need to send a response back to the client. The next iteration of that will be triggered by a new request to PHP, which begins again from the beginning and doesn't remember any previous state.
So, in pseudo code, it works like this:
if is POST request:
validate input, populate error variables
if input is valid:
send email with data
redirect to different page or display "thanks"
form start
for $field in fields:
output HTML for $field
maybe highlight if error
maybe set value to POSTed value to retain data
form end
So, upon the first page visit, it won't be a POST request and falls straight through to the form part. There won't be any errors or existing data, so the plain form will be output. When the form is submitted, the same code runs again and now enters the if is POST branch. If any values are invalid, it will fall through to the form again, which now can also output any error messages and existing submitted values. Only when all values are valid, will the server send an email and exit this "loop" by redirecting to another page, or maybe just outputting a "Thank you" note.
If you properly separate that into an MVC architecture, you'd have these components:
Model
data validation
email sending
View
outputs the form HTML
Controller
one for handling GET requests, just invoking the view
one for handling POST requests, essentially doing:
errors = model.validate(data)
if no errors:
model.send_email(data)
redirect()
else:
view.display_form(data, errors)
some form of router invoking the right controller based on the request URL and method
These could all be separate functions, or classes, or methods, or just files.
Below is the final code for the page. It's a basic 404 error page that may be of use to someone. And it should answer the requests that I supply the code that I was working with
It includes three files that I've not supplied:
top.php and footer.php and functions.php
top produces the HTML head statements including meta codes and also including top level banners and menu, as well as establishing the basic page format.
footer-- using the server superglobal just before the footer include, the page can provide a code update date for the page. And a consistent name and registration number for our organisation
functions.php supplies a bunch of reused functions. There are a couple of little (fairly obvious) functions in used in this code:
spacer outputs code to create an empty cell in a table.
spanCol creates a column spanning cell in a table, with the specified text and
specified tag open and close
The full page is at http://www.vfmc.org.au/notfound.php -- please don't send me too much junk email.
Code for the guts is here - I don't claim that it's brilliant, but it works thanks to help from here:
<?php
$pageTitle = "File Not Found";
$authorName = "Don Gingrich";
$styleSheet = "./css/mainstyle.css";
include_once 'top.php';
require_once "functions.php";
$indicesServer = array(
'PHP_SELF',
'HTTP_REFERER',
'SCRIPT_FILENAME',
'SCRIPT_NAME',
'REQUEST_URI',
'ORIG_PATH_INFO'
);
if (isset($_SERVER['HTTP_REFERER'])) {
$refering = $_SERVER['HTTP_REFERER'];
} else {
$refering = NULL;
}
$requested = $_SERVER['REQUEST_URI'];
// $refering = $_SERVER['HTTP_REFERER'];
if ($refering == NULL || $refering == " ") {
$refering = "referrer field was blank\n - may be due to mis-typing address\n";
}
/* basic "sanitise input" function */
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function send_webmaster_email($name, $email, $comment, $requested, $refering)
{
global $sent;
$subject = "File not Found: $requested";
$txt = "Trying to access $requested from $refering\n" . "Visitor comments follow:\n" . $comment;
if ($name != "") {
$txt .= "\n\tReporting person's name is: $name\n";
}
if ($email != "") {
$txt .= "\n\tReporting person's email is: $email\n";
}
$to = "webmaster#vfmc.org.au";
$additional_headers = "From: webmaster#vfmc.org.au\r\n";
mail($to, $subject, $txt, $additional_headers);
$sent = true;
}
// define variables and set to empty values
$nameErr = $emailErr = "";
$name = $email = $comment = "";
$myError = false;
global $sent;
$sent = false;
/********************************************************
* Processing code follows -- Only executed after POST
*
*******************************************************/
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$requested = $_POST['requested'];
$refering = $_POST['refering'];
$requested = test_input($requested);
$refering = test_input($refering);
$myError = false;
if ($_POST["button"] == "Submit") {
if (empty($_POST["name"])) {
$name = "";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z -]*$/", $name)) {
$myError = true;
$nameErr = "Only letters, hyphen, and white space allowed";
}
}
if (empty($_POST["email"])) {
$email = "";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$myError = true;
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comments"])) {
$comment = "";
} else {
$comment = test_input($_POST["comments"]);
}
if ($myError == false) {
send_webmaster_email($name, $email, $comment, $requested, $refering);
}
}
}
echo "\n";
echo "<h2>File Not Found</h2>\n";
echo "<br>\n";
echo "<br>\n";
if ($sent == true ){
echo "<h5>Email sent to Webmaster, Thank you</h5>\n";
echo "<br>Use the menu to the left or the back button<br>\n";
echo "to return to the VFMC site<br>\n";
} else {
echo " Unfortunately the file that you have asked for is unavailable.\n";
echo "<br>\n";
echo "<br>\n";
echo "This may mean that the Webmaster has forgotten to load it or the link to it is broken in some way.<br>\n";
echo "Or, if you typed a page in the browser address bar, you may have mis-typed, remember that everything<br>\n";
echo "after the <b>www.vfmc.org.au/</b> is CaSeSensitive -- FiresideFiddlers, is spelled as written.<br>\n";
echo " <br>\n";
echo " <br>\n";
echo "<h6>Please tell the webmaster by sending a message:</h6>\n";
echo " <br>\n";
echo " <br>\n";
$myFile = htmlspecialchars($_SERVER['PHP_SELF']);
echo " <form action= \"$myFile\" method=\"post\">\n";
echo "<input type=\"hidden\" name=\"refering\" value=\"$refering\" />\n";
echo "<input type=\"hidden\" name=\"requested\" value=\"$requested\" />\n";
echo " <table border=\"0\" cellpadding=\"8\" cellspacing=\"8\">\n";
echo " <colgroup>\n";
echo " <col width = auto>\n";
echo " <col width = auto>\n";
echo " <col width = auto>\n";
echo " </colgroup>\n";
echo " <tr>\n";
spanCol("3", "Your name and email address are optional,<br> but the webmaster will be unable to respond <br>directly without them", "h5");
echo " <tr>\n";
echo " <td><label for=\"tswname\">Name</label>:</td>\n";
echo " <td><input type=\"text\" name=\"name\" id=\"tswname\" size=\"25\" /></td>\n";
echo " <td>\t";
if ($nameErr == "") {
echo "(Optional)\n";
} else {
echo "<span class=\"error\">*" . $nameErr . "</span>\n";
}
echo "</td></tr>\n";
echo " <tr>\n";
echo " <td>\n";
echo " <label for=\"tswemail\">Email address</label>:</td>\n";
echo " <td>\n";
echo " <input type=\"text\" id=\"tswemail\" name=\"email\" size=\"25\" />\n";
echo " </td>\n";
echo " <td>\n";
if ($emailErr == "") {
echo "(Optional)\n";
} else {
echo "<span class=\"error\">*" . $emailErr . "</span>\n";
}
echo "</td></tr>\n";
echo " <tr>\n";
echo " <td>\n";
echo " <label for=\"tswcomments\">Comments</label></td>\n";
echo " <td colspan=\"2\">\n";
echo " <textarea rows=\"15\" cols=\"45\" name=\"comments\" id=\"tswcomments\"></textarea>\n";
echo " </td>\n";
echo " </tr>\n";
echo " <tr>\n";
echo " <td align=\"center\" colspan=\"2\">\n";
echo " <input type=\"submit\" name=\"button\" value=\"Submit\" /><br>\n";
echo " </td>\n";
echo " </tr>\n";
echo " </table>\n";
echo " </form>\n";
}
echo " <br>\n";
echo " <br>\n";
echo " <br>\n";
echo " <br>\n";
echo "</td>\n";
echo "</tr>\n";
$filename = $_SERVER['SCRIPT_NAME'];
require_once "footer-code.php";
?>
</tbody>
</table> <!--PWK-EDIT END FOOTER-->
</body>
</html>
I have asked this question before I made changes to my code and my image upload is not working at all I have checked username password, and Root they are all correct. my code will not show any errors I dont know what to do anymore can someone please help me? I have changed my connection for security reasons
<?php
$con = mysqli_connect("localhost", "torcdesi_jone45", "password", "torcdesi_amazing");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query_image = 'INSERT INTO shirt_table (images3)
values( "' . $_FILES['file3']['name'] . '")';
?>
<?php
include("configur.php");
if($_POST) {
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file3"]["error"] > 0) {
// if there is error in file uploading
echo "Return Code: " . $_FILES["file3"]["error"] . "<br />";
} else {
// check if file already exit in "images" folder.
if (file_exists("shirtimgs/" . $_FILES["file3"]["name"])) {
} else {
//move_uploaded_file function will upload your image.
if(move_uploaded_file($_FILES["file3"]["tmp_name"],"shirtimgs/" . $_FILES["file3"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into shirt_table";
if(mysqli_query($link, $query_image)) {
echo "Stored in: " . "shirtimgs/" . $_FILES["file3"]["name"];
} else {
echo'';
}
}
}
}
}
?>
As I stated in comments, your form is missing a proper enctype to handle files.
This I know, since I saw your other question that did not contain it in the form.
<form enctype="multipart/form-data" action="__URL__" method="POST">
As per the manual:
http://php.net/manual/en/features.file-upload.post-method.php
I'm trying to add a basic new-grabber for a site I'm making and cannot figure out for the life of me what is causing this error. The file I'm grabbing is a plain-text file, completely accessible.
I've seen it posted before and the OP is calling something like:
$var = $data[str] instead of $var = $data['src']
But I am not calling anything with "code" in the name.
I receive this error upon running my code:
HTTP request failed. Error 8 on line 123: Use of undefined constant
code - assumed 'code' in file /usr/local/lib/php/head.php
Here is my entire file below:
<?
$e_news = file_get_contents("http://cinemattson.com/templates/flickfeed/news.txt");
if (!$e_news === true) {
$error = error_get_last();
echo "HTTP request failed. Error " . $error['type'] . " on line " . $error['line'] . ": " . $error['message'] . " in file " . $error['file'] . "<br>";
} else {
echo "Everything went better than expected";
}
if ($e_news === true) {
$news = explode("|", $e_news);?>
<h4>News - <? echo (!empty($news) ? $news[1] : "v0.0.1");?> <small><? echo (!empty($news) ? $news[0] : "5/22/2016");?></small></h4>
<p><? echo (!empty($news) ? $news[2] : "Loading news failed, or there is currently no news.");?></p>
<?
} else {
echo "<h4>News failed to load</h4>";
}
?>
Do you guys know what I'm missing or doing wrong here?
As already suggested by #John Stirling, "the issue is elsewhere".
More precisely the reported Error 8 on line 123... etc is related to an error that happened previously, elsewhere.
And your current code is responsible to make this error appear now because you wrote:
$e_news = file_get_contents("http://cinemattson.com/templates/flickfeed/news.txt");
if (!$e_news === true) {
$error = error_get_last();
This way, the following happens:
Each time file_get_contents() is successfull, $e_news gets its content.
Then $e_news === true is FALSE (even if this content is empty, because you used ===), and if (!$e_news === true) is always TRUE.
So there is no error now, and your error_get_last() gets the trace of the last error that previously happened, elsewhere...
In fact, for your code to work as expected you should rather do something like this:
$e_news = file_get_contents("http://cinemattson.com/templates/flickfeed/news.txt");
if ($e_news === false) {
$error = error_get_last();
echo "HTTP request failed. Error " . $error['type'] . " on line " . $error['line'] . ": " . $error['message'] . " in file " . $error['file'] . "<br>";
echo "<h4>News failed to load</h4>";
} else {
echo "Everything went better than expected";
$news = explode("|", $e_news);?>
<h4>News - <? echo (!empty($news) ? $news[1] : "v0.0.1");?> <small><? echo (!empty($news) ? $news[0] : "5/22/2016");?></small></h4>
<p><? echo (!empty($news) ? $news[2] : "Loading news failed, or there is currently no news.");?></p>
<?
}
I am trying to allow an image to be uploaded with a form. I have code that makes sure that the user has entered valid information into the form. If invalid information is submitted, the user is asked to correct the errors and submit the form again. I am using the post data to populate the form fields so that the user does not have to enter the information again and is able to just edit the information they have already entered. It seems that the $_POST is receiving the file information but it will change to displaying "No file selected." rather than the name of the file. What is the problem here? Below are some excerpts of my code
//Set field values as posted data.
if ($_FILES["Image"]["error"] > 0)
{
echo "Error: " . $_FILES["Image"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["Image"]["name"] . "<br>";
echo "Type: " . $_FILES["Image"]["type"] . "<br>";
echo "Size: " . ($_FILES["Image"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["Image"]["tmp_name"];
}
$Name = $_POST['Name'];
$Image = $_FILES["Image"];
And the form:
<td><input type="file" name="Image" value="<?php echo($_FILES["Image"]["name"]); ?>"></td>
i'm using this code to upload and attach an image through a form, and send it to a mail (as html not as smtp).
once i enter this (the code) page in the web, i can see the output just fine, i can click the "choose file" and choose a file from some directory.
but, i can see as well right away when enterind the page the echo "invalid file" probably because an image didn't upload yet by me, but the code runs and not waiting for me to choose something.
am i missing some triger that will submit my choise and than send it?
when configuring it to be sent as an html like i did, does $mail->Send() is enough and when the code reaches to that command the mail with the attach will be sent?? or i need some other triger to send it?
thank you,
<?php
include_once("functions.php");
// Process
$action = isset($_POST["action"]) ? $_POST["action"] : "";
if (empty($action))
{
$output = "<form action='#'>
<h1>header: </h1>
<label for='image'>upload: </label>
<input type='file' id='image' name='image' maxlength=50 >";
}
echo $output;
$image = $_POST["image"];
uploadImage($image);
require("class.phpmailer.php");
$Email_to = "some#gmail.com"; // the one that recieves the email
$email_from = "someone#someone.net";
$dir = "uploads/$filename";
chmod("uploads",0777);
function uploadImage($image){
if ((($_FILES["image"]["type"] == "image/gif")
|| ($_FILES["image"]["type"] == "image/jpeg")
|| ($_FILES["image"]["type"] == "image/pjpeg")
|| ($_FILES["image"]["type"] == "image/jpg")
|| ($_FILES["image"]["type"] == "image/png"))
&& ($_FILES["image"]["size"] < 2097152)
&& (strlen($_FILES["image"]["name"]) < 51)){
if ($_FILES["image"]["error"] > 0){
echo "Return Code: " . $_FILES["image"]["error"];
}
else{
echo "Upload: " . $_FILES["image"]["name"] . "<br />";
echo "Type: " . $_FILES["image"]["type"] . "<br />";
echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br />";
if (file_exists("images/" . $_FILES["image"]["name"])){
echo $_FILES["image"]["name"] . " already exists. ";
}
else{
move_uploaded_file($_FILES["image"]["tmp_name"],
"images/" . $_FILES["image"]["name"]);
}
}
}else{
echo "Invalid file";
}
$filename = $_FILES["image"]["type"];
$dir = "uploads/$filename";
chmod("uploads",0777);
$success = copy($_FILES[images][tmp_name], $dir);
if ($success) {
echo " Files Uploaded Successfully<BR>";
SendIt();
}
}
function SendIt() {
//
global $attachments,$Email_to,$Email_msg,$email_subject,$email_from;
//
$mail = new PHPMailer();
//$mail->IsSMTP();// send via SMTP
//$mail->Host = "localhost"; // SMTP servers
//$mail->SMTPAuth = false; // turn on/off SMTP authentication
$mail->From = $email_from;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
$mail->WordWrap = 50;// set word wrap
//now Attach all files submitted
$mail->AddAttachment("uploads"."/".$_FILES["image"]["type"]);
//
$mail->IsHTML(true);// send as HTML
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
}
?>
You should only be firing the uploadImage function when there IS an $action:
...previous code...
if (empty($action))
{
?>
<form action=''>
<h1>header: </h1>
<label for='image'>upload: </label>
<input type='file' id='image' name='image' maxlength=50 >
</form>
<?php
exit; // stop the upload script running
}
$image = $_POST["image"];
uploadImage($image);
require("class.phpmailer.php");
... rest of the code ...