How to use the php 'include' function in 'echo'ed content? - php

I have a process.php file for processing a comment/message form. If there is an error during the processing, the incorrect form content is echoed and shown as a web page named process.php to the viewer for correction and resubmitting.
The problem is that I need the echoed content to contain various <?php include("xxxx.php");?> elements so that it matches the rest of my site. But this seems to make the page fall over (showing blank page with no content). I've been told that I should use either include("xxxx.php"); or echo file_get_contents("xxxx.php"); from within the echoed content, but neither displays the intended content.
Any help in these issues would be greatly appreciated.
Code: (some items xxxxx for security)
<?php
// Information to be modified
$your_email = "xxxxxxxx#xxxxx.xx.xx"; // email address to which the form data will be sent
$subject = "Contact message"; // subject of the email that is sent
$thanks_page = "thankyou.htm"; // path to the thank you page following successful form submission
$contact_page = "mail_form_styled.php"; // path to the HTML contact page where the form appears
// Nothing needs to be modified below this line
if (!isset($_POST['submit'])) {
header( "Location: $contact_page" );
}
if (isset($_POST["submit"])) {
$nam = $_POST["name"];
$ema = trim($_POST["email"]);
$com = $_POST["comments"];
$spa = $_POST["spam"];
if (get_magic_quotes_gpc()) {
$nam = stripslashes($nam);
$ema = stripslashes($ema);
$com = stripslashes($com);
}
$error_msg=array();
if (empty($nam) || !preg_match("~^[a-z\-'\s]{1,60}$~i", $nam)) {
$error_msg[] = "The name field must contain only letters, spaces, dashes ( - ) and single quotes ( ' )";
}
if (empty($ema) || !filter_var($ema, FILTER_VALIDATE_EMAIL)) {
$error_msg[] = "Your email must have a valid format, such as name#mailhost.com";
}
$limit = 1000;
if (empty($com) || !preg_match("/^[0-9A-Za-z\/-\s'\(\)!\?\.,]+$/", $com) || (strlen($com) > $limit)) {
$error_msg[] = "The Comments field must contain only letters, digits, spaces and basic punctuation ( ' - , . ), and has a limit of 1000 characters. Website addresses can not be included.";
}
if (!empty($spa) && !($spa == "4" || $spa == "four")) {
echo "You failed the spam test!";
exit ();
}
// Assuming there's an error, refresh the page with error list and repeat the form
if ($error_msg) {
echo '<!DOCTYPE html>
<html lang="en">
<!-- Begin head items -->
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1">
<meta name="description" content="The Dark Fortress contact form. Use it to get in touch…" />
<link href="../styles/screen.css" rel="stylesheet" type="text/css" media="screen" />
<link rel="alternate" type="application/rss+xml"
title="thedarkfortress Command Briefing"
href="http://feeds.feedburner.com/ThedarkfortressCommandBriefing" />
<title>O dear! | The Dark Fortress</title>
<style type="text/css">
.hide {display:none;}
</style>
</head>
<!-- Begin body items -->
<body>
<div id="container">
<!-- Begin header items -->
echo file_get_contents("../components/header.php");
<!-- Begin main content items -->
<div id="content-container">
<!-- Begin content items -->
<div id="content">
<h1>O dear!</h1>
<p>Unfortunately, your message could not be sent. The form as you filled it out is displayed below. Make sure each field completed, and please also address any issues listed below:</p>
<ul class="err">';
foreach ($error_msg as $err) {
echo '<li>'.$err.'/li>';
}
echo '</ul>
<form method="post" action="', $_SERVER['PHP_SELF'], '">
<label for="name">Name</label>
<input name="name" type="text" size="40" maxlength="60" id="name" value="'; if (isset($_POST["name"])) {echo $nam;}; echo '">
<label for="email">Email Address</label>
<input name="email" type="email" size="40" maxlength="60" id="email" value="'; if (isset($_POST["email"])) {echo $ema;}; echo '">
<label for="comm">Comments</label>
<textarea name="comments" rows="7" cols="50" id="comm">'; if (isset($_POST["comments"])) {echo $com;}; echo '</textarea>
<div class="hide">
<label for="spam">What is six plus four?</label>
<input name="spam" type="text" size="4" id="spam">
</div>
<input type="submit" name="submit" value="Send" class="button orange send" />
</form>
<div class="divider"><hr /></div>
<p><img src="../main_assets/isiah_page_sig_flat.png" alt="Isiah signature" /></p>
<p><strong>Chronicler Isiah,</strong> the 4th Battle Company, Dark Angels.</p>
</div>
<!-- Begin left nav items -->
<div id="leftnav">
echo file_get_contents("../components/hq_leftnav.php");
</div>
</div>
</div>
<!-- Begin footer items -->
echo file_get_contents("../components/footer.php");
<!-- Begin google analytics tracker items -->
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("xxxxxx"); pageTracker._trackPageview();
</script>
</body>
</html>';
exit();
}
$email_body =
"Name of sender: $nam\n\n" .
"Email of sender: $ema\n\n" .
"COMMENTS:\n\n" .
"$com" ;
// Assuming there's no error, send the email and redirect to Thank You page
if (isset($_REQUEST['comments']) && !$error_msg) {
mail ($your_email, $subject, $email_body, "From: $nam <$ema>" . "\r\n" . "Reply-To: $nam <$ema>");
header ("Location: $thanks_page");
exit();
}
}

You'd simply use CSS as you normally would...
<?php
// index.php
?>
<!doctype html>
<html>
<head>
<style type="text/css">
.myClass {
color: #f00;
}
</style>
</head>
<body>
<?php
include('myFile.php');
?>
</body>
</html>
<?php
// included myFile.php
echo '<p class="myClass">Echoed content!</p>';
If you're ending up with a blank page with no content then you potentially have errors in your PHP. Ensure error reporting is enabled and you'll be able to see what's going wrong.

Related

HTML Form sends GET instead of POST (XAMPP, Apache, localhost)

I've looked up other questions with possible solutions to my problem, but they don't seem to work for me.
According to the Network console in Firefox, my contact form sends GET when I set the method to POST.
I have checked my HTML code for errors, but can't find any; no unclosed forms, divs, etc. I've checked the syntax for my php, too.
I also tried setting the submit button to <button type="submit" formmethod="post" formaction="form-to-email.php" name="submit" class="button">Und los</button>'but it doesn't help, either.
EDIT: Here's my complete HTML code for this page:
<!DOCTYPE html>
<html lang="" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="placeholder">
<meta name="keywords" content="placeholder">
<meta name="author" content="placeholder">
<title>MADesign.</title>
<link rel="author" href="robots.txt" />
<link rel="author" href="humans.txt" />
<!-- CSS -->
<link rel="stylesheet" href="css/maincss.css">
</head>
<body>
<div id="holder">
<!-- page header -->
<div class="bg-image-small">
<div id="main_menu">
<header id="page_header">
<img src="images/mad-logo-300px.png" alt="mad logo" id="mad-logo">
</header>
<!-- END page header -->
<!-- main navigation -->
<nav id="main-nav">
<ul>
<li>home</li>
<li>link1</li>
<li>link2</li>
<li>link3</li>
<li>kontakt</li>
<li>impressum</li>
</ul>
</nav><!-- END main navigation -->
</div><!-- END main menu -->
</div><!-- END background image -->
<!-- main content -->
<main>
<!-- contact form -->
<form id="my-form" name="myForm" action="/form-to-email.php" method="post">
<h2>Let's get in touch.</h2>
<p>Schick mir eine Email an abc#placeholder.de oder nutze mein Kontaktformular.</p>
<div class="gender">
<input type="radio" name="titles" value="male" id="mr"
<?php if($titles == "male") echo "checked" ?>>
<label for="titles">Herr</label>
<input type="radio" name="titles" value="female" id="mrs"
<?php if($titles == "female") echo "checked" ?>>
<label for="titles">Frau</label>
<input type="radio" name="titles" value="nonbinary" id="mx"
<?php if($titles == "nonbinary") echo "checked" ?>>
<label for="titles">Hallo</label>
<input type="radio" name="titles" value="person" id="person"
<?php if($titles == "person") echo "checked" ?>>
<label for="titles">Person</label>
<div class="errormsg">
<?php echo $errors['titles']; ?>
</div>
</div>
<div class="form-block">
<label for="usrname">Name:</label><br>
<input type="text" name="usrname" id="usrname" class="styleinput" size="20" maxlength="30" value="<?php echo htmlspecialchars($usrname) ?>">
<div class="errormsg">
<?php echo $errors['usrname']; ?>
</div>
</div>
<div class="form-block">
<label for="email">Email:</label><br>
<input type="text" name="email" id="email" class="styleinput" size="20" maxlength="30" value="<?php echo htmlspecialchars($email) ?>">
<div class="errormsg">
<?php echo $errors['email']; ?>
</div>
</div>
<div class="user-input form-block">
<label for="user-input">Nachricht:</label><br>
<textarea class="styleinput" id="message-me" name="usrmsg" rows="4" cols="50" value="<?php echo htmlspecialchars($usrmsg) ?>"></textarea>
<div class="errormsg">
<?php echo $errors['usrmsg']; ?>
</div>
</div>
<button type="submit" formmethod="post" formaction="/form-to-email.php" name="submit" class="button">Und los</button>
<input type="reset" name="reset" class="button" value="Nochmal neu..." onclick="emptyMsg()">
<div id="message"></div>
</form>
<!-- END contact form -->
</main>
<!-- END main content -->
<!-- footer -->
<footer>
<p>&copy2019 placeholder</p>
</footer><!-- END footer-->
</div><!-- END holder -->
<!-- JavaScript and jQuery -->
<script src="https://code.jquery.com/jquery-3.4.0.min.js" integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg=" crossorigin="anonymous"></script>
<script src="js/mainjs.js"></script>
</body>
</html>
This is the PHP (saved in the same directory as kontakt.php):
<?php
$titles = $usrmsg = $usrname = $email = "";
$errors = array("email"=>"", "usrname"=>"", "usrmsg"=>"", "titles"=>"");
if(isset($_POST["submit"])){
//check Email
if(empty($_POST["email"])){
$errors["email"] = "Bitte Email Adresse angeben.";
} else {
$email = $_POST["email"];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors["email"] = "Die Email Adresse sollte gültig sein.";
}
}
//check name
if(empty($_POST["usrname"])){
$errors["usrname"] = "Wie heißt du?";
} else {
$usrname = $_POST["usrname"];
$usrname = filter_var($usrname, FILTER_SANITIZE_STRING);
if(!preg_match("/^[a-zA-Z\s]+$/", $usrname)){
$errors["usrname"] = "Sorry! Der Name darf nur Buchstaben und Leerzeichen enthalten.";
}
}
//check message
if(empty($_POST["usrmsg"])){
$errors["usrmsg"] = "Hier sollte etwas Text stehen. Muss ja nicht viel sein.";
} else {
$usrmsg = $_POST["usrmsg"];
$usrmsg = filter_var($usrmsg, FILTER_SANITIZE_STRING);
}
//check titles
$titles = $_POST["titles"];
if ($titles==NULL) {
$errors["titles"] = "Welche Ansprache darf ich verwenden?";
}
}
?>
EDIT: Here's the JS for client-side form validation (it's not a finished version, some validations are still missing/may get changed, but so far it's working as it should):
var myForm = document.forms.myForm;
var message = document.getElementById('message');
myForm.onsubmit = function() {
//get IDs for the title
var mr = document.getElementById('mr');
var mrs = document.getElementById('mrs');
var mx = document.getElementById('mx');
var pers = document.getElementById('person');
//get ID for the textarea
var usrInput = document.getElementById('message-me');
if (myForm.usrname.value == "") {
message.innerHTML = "Moment! Wie heißt du?"
return false;
} else if (usrInput.value == "") {
message.innerHTML = "Das Nachrichtenfeld sollte nicht leer sein..."
return false;
} else if (email.value == "") {
message.innerHTML = "Wie lautet deine Email Adresse?"
return false;
} else if (usrInput.value.length < 10) {
//check min length of textarea
message.innerHTML = "Die Nachricht sollte etwas länger sein..."
return false;
} else if (!mr.checked &&
!mrs.checked &&
!mx.checked &&
!pers.checked) {
message.innerHTML = "Welche Ansprache darf ich verwenden?"
return false;
} else {
message.innerHTML = "";
return true;
}
I'm using XAMPP (Apache) to test this via localhost.
How can I get the form to send POST, not GET? Did I overlook syntax errors, typos or are there errors with my variables that I can't find? Thx for any input.
This happens sometimes. I don't think I am experienced enough to give you a perfect solution but here's a bunch of try outs you can implement:
Try to write the "post" keyword in capitals (like "POST").
Sometimes the xampp server does not reflect changes even after you save and refresh. Try refreshing with (ctrl+F5). This imposes a hard refresh causing the xampp server to reload all the resourses.
Try restarting the xampp server.
Please revert if anything was helpful....

PHP code getting printed as it is [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 5 years ago.
I have just started learning PHP and was trying to create a responsive contact form using PHP.
But the problem is that my PHP code gets printed as it is on the web page as it is and not in the required format as I need it.
Here's my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Contact Us</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/start/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-
ui.min.js"></script>
</head>
<body>
<!-- <img src="call.jpg" id="background"> -->
<div id="container-fluid">
<div class="row">
<div class="col-sm-offset-1 col-sm-10 contactform">
<h1>Contact Us:</h1>
<?php
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$message = $_REQUEST["message"];
$submit = $_REQUEST["submit"];
$to = "abc1996#xyz.com";
$var = rand(1,1000);
$subject = 'Complaint Registered. Complaint No.: '. echo "$var";
if($submit)
{
if(!$name)
$errors = $errors."<p><strong>Name missing!</strong></p>";
else
$name = filter_var($name,FILTER_SANITIZE_STRING);
if(!$email)
$errors = $errors."<p><strong>Email missing!</strong></p>";
else
{
$name = filter_var($email,FILTER_SANITIZE_STRING);
if(!filter_var($email,FILTER_VALIDATE_EMAIL))
{
$errors = $errors."Please give a valid Email-Address!";
}
}
if(!$message)
{
$errors = $errors."<p><strong>Message box can't be empty!</strong></p>";
}
else
{
$message = filter_var($message,FILTER_SANITIZE_STRING);
}
if($errors)
{
$finalmsg = "<div class='alert alert-danger'> ".$errors "</div>";
}
else
{
$date = date('d MM YY');
$content = "Hi $name. Thank you for your complaint. Your complaint has been registered on $date and your complaint number is: $var";
if(mail($to, $subject, $content))
{
$finalmsg = '<div class="alert alert-success">Your mail has been sent and we will REQUEST back to you asap</div>';
}
else
{
$finalmsg = '<div class="alert alert-warning">Error Sending Mail. Try again later!</div>';
}
}
echo $finalmsg;
}
?>
<form action="" method="post">
<div class="form-group">
<label for="name">Name &#42: </label>
<input type="text" name="name" id="name" placeholder="Enter your Name " class="form-control">
</div>
<div class="form-group">
<label for="email">Email &#42:</label>
<input type="email" name="email" id="email" placeholder="Enter your Email " class="form-control">
</div>
<div class="form-group">
<label for="message">Message &#42:</label>
<textarea id="message" name="message" class="form-control" rows="5"></textarea>
</div>
<input type="submit" name="submit" class="btn btn-success btn-lg" value="Send Message" id="submit">
</form>
</div>
</div>
</div>
</body>
Also, it would be great if you help me in generating a random number and use it in my code. I have tried it in my code, please tell me whether it is correct or not.
Thank You
Is this page served by a web server and does it have a .php extension?
PHP is a preprocessor which means that it needs to be run by a web server. Try WAMP (Windows) or MAMP (for Mac), rename your file to .php and retry.

How to put a delete button under each post in my blog/website?

I am wanting to put a delete button, so people can delete their post if they want on my simple blog website. I am just a little unsure how to do it. I guess I need to put a value=delete input field on my posting_wall but not sure where to go from there. Thank you in advnace if you can help me.
Form
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/index.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<link type="text/css" rel="stylesheet" href="../css/header.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
$('form').submit(function (e) {
var value;
// "message" pattern : from 3 to 150 alphanumerical chars
value = $('[name="message"]').val();
if (!/^[-\.a-zA-Z\s0-9]{3,150}$/.test(value)) {
alert('Sorry, only alphanumerical characters are allowed and 3-150 character limit".');
e.preventDefault();
return;
}
// "name" pattern : at least 1 digit
value = $('[name="name"]').val();
if (!/\d+/.test(value)) {
alert('Wrong value for "name".');
e.preventDefault();
return;
}
});
});
</script>
</head>
<body>
<?php include 'header.php' ?>
<form action="posting_wall.php" method="get">
<div id="container">
Name:<input type="text" name="name" pattern="[A-Za-z0-9]{3,15}" title="Letters and numbers only, length 3 to 15" required autofocus><br>
E-mail: <input type="email" name="email" maxlength="20" required><br>
Post:<br>
<textarea rows="15" cols="50" name='message'></textarea>
</div>
Date this event took place: <input type="text" name='date' id="datepicker" > <br>
<input type="reset" value="Reset">
<input type="submit">
</form>
<p>Posting Wall</p>
<div id="time">
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs
echo 'The time at which you are posting is:'. date('h:i Y-m-d') ."\n";
?>
</div>
<?php include 'footer.php' ?>
</body>
</html>
Posting Wall Page (where I want the delete button under each post)
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/post.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
</head>
<body>
<h1>Daily Dorm News <br></h1>
<h2> Your Daily Dorm News Posts </h2>
<div id="container"> <?php if ( isset($_GET['name']) and preg_match("/^[A-Za-z0-9]+$/", $_GET['name']) ) {
echo $_GET['name'];
} else {
echo "You entered an invalid name!\n";
}
?><br>
Your email address is: <?php if ( isset($_GET['email']) and preg_match("/.+#.+\..+/i", $_GET['email']) ) {
echo $_GET['email'];
} else {
echo "You didn't enter a proper email address!\n";
}
?><br>
You Posted : <?php if ( isset($_GET['message']) and preg_match("/^[-\.a-zA-Z\s0-9]+$/", $_GET['message']) ) {
echo $_GET['message'];
} else {
echo "The message is not valid! The message box was blank or you entered invalid symbols!\n";
}
?>
<br>
This event happened :<?php echo $_GET["date"]; ?><br>
</div>
<?php
/* [INFO/CS 1300 Project 3] index.php
* Main page for our app.
* Shows all previous posts and highlights the current user's post, if any.
* Includes a link to form.php if user wishes to create and submit a post.
*/
require('wall_database.php');
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
$is_valid_post = true;
// Checking if a form was submitted
if (isset($_REQUEST['name'])){
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
// Saving the current post, if a form was submitted
$post_fields = array();
$post_fields['name'] = $name;
$post_fields['email'] = $email;
$post_fields['message'] = $message;
$post_fields['date'] = $date;
$success_flag = saveCurrentPost($post_fields);
}
//Fetching all posts from the database
$posts_array = getAllPosts();
?>
<?php
if(isset($name)) {
echo "<h3>Thanks ".$name." for submitting your post.</h3>";
}
?>
<p id="received">Here are all the posts we have received.</p>
<div id="logo">Dont Forget to tell you’re friends about Daily Dorm Post! <br>
The only Dorm News Website on campus!</div>
<ul id="posts_list">
<?php
// Looping through all the posts in posts_array
$counter = 1;
foreach(array_reverse($posts_array) as $post){
$alreadyPosted = false;
$name = $post['name'];
$email = $post['email'];
$message = $post['message'];
$date = $post['date'];
if ($counter % 2==1)
$li_class = "float-left";
else
$li_class = "float-right";
if ($name == $_GET['name']) {
$alreadyPosted = true;
}
echo '<div class=post';
if ($alreadyPosted) {
echo ' id="highlight"';
}
echo '>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' email is: '.$email.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' wrote '.$message.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>This event occured on '.$date.'</span></h3></li>';
echo '</div>';
}
?>
</ul>
</div>
<p id="submit">Would you like to submit another post?</p>
<?php include 'footer.php' ?>
</body>
</html>
create a delete button or make
<script>
function confirm(){
var responce = confirm("Are you sure want to delete?");
if (responce==true)
{
return true;
}
else
{
return false;
}
}
</script>
<a onclick="confirm()" href="delete_post.php?id=1>">Delete</a>

Using Strip Tags and check for empty fields PHP

So i have a form here, and I want on the to do some php so that if the field is empty, it will say once you submit the form after it loads to the post page, that sorry you entered no date. I also want to add strip tags, however I am unsure how, if they go on the posting_wall or if they go in the form.php? I want to use strip all tags.
I believe the empty validation was if(!empty(($date)) { echo "sorry you did not enter a date"; } but i could not get it to work.
Thank you in advance if you can help me with this. I will post the form.php and the posting wall below.
Form.php
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/index.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<link type="text/css" rel="stylesheet" href="../css/header.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
$('form').submit(function (e) {
var value;
// "message" pattern : from 3 to 150 alphanumerical chars
value = $('[name="message"]').val();
if (!/^[-\.a-zA-Z\s0-9]{3,150}$/.test(value)) {
alert('Sorry, only alphanumerical characters are allowed and 3-150 character limit".');
e.preventDefault();
return;
}
// "name" pattern : at least 1 digit
value = $('[name="name"]').val();
if (!/\d+/.test(value)) {
alert('Wrong value for "name".');
e.preventDefault();
return;
}
});
});
</script>
</head>
<body>
<?php include 'header.php' ?>
<form action="index.php" method="get">
<div id="container">
Username:*<input type="text" name="name" pattern="{3,15}" title="Letters and numbers only, length 3 to 15" required autofocus><br>
E-mail:* <input type="email" name="email" maxlength="20" required><br>
Post:*<br>
<textarea rows="15" cols="50" name='message'></textarea>
</div>
Date this event took place: <input type="text" name='date' id="datepicker" > <br>
Your favorite website is: <input type="text" name="website">
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br>
<input type="reset" value="Reset">
<input type="submit">
</form>
<p> Fields with * next to them are required </p>
<p>Posting Wall</p>
<div id="time">
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs
echo 'The time at which you are posting is:'. date('h:i Y-m-d') ."\n";
?>
</div>
<?php include 'footer.php' ?>
</body>
</html>
Posting wall
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/post.css" />
<link type="text/css" rel="stylesheet" href="../css/heaader.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
</head>
<body>
<h1>Daily Dorm News </h1>
<h2> You're best place for the latest dorm news from campus </h2>
<div id="container"> <?php if ( isset($_GET['name']) and preg_match("/^[A-Za-z0-9]+$/", $_GET['name']) ) {
echo $_GET['name'];
} else {
echo "You entered an invalid name!\n";
}
?><br>
Your email address is: <?php if ( isset($_GET['email']) and preg_match("/.+#.+\..+/i", $_GET['email']) ) {
echo $_GET['email'];
} else {
echo "You didn't enter a proper email address!\n";
}
?><br>
You Posted : <?php if ( isset($_GET['message']) and preg_match("/^[-\.a-zA-Z\s0-9]+$/", $_GET['message']) ) {
echo $_GET['message'];
} else {
echo "The message is not valid! The message box was blank or you entered invalid symbols!\n";
}
?>
This event happened :<?php echo $_GET["date"]; ?><br>
Your gender is:<?php echo $_GET["gender"]; ?><br>
Your favorite website is: <?php echo $_GET["website"]; ?><br>
</div>
<?php
/* [INFO/CS 1300 Project 3] index.php
* Main page for our app.
* Shows all previous posts and highlights the current user's post, if any.
* Includes a link to form.php if user wishes to create and submit a post.
*/
require('wall_database.php');
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
$gender = strip_tags($_REQUEST['gender']);
$website = strip_tags($_REQUEST['website']);
$is_valid_post = true;
// Checking if a form was submitted
if (isset($_REQUEST['name'])){
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
$gender = strip_tags($_REQUEST['gender']);
$website = strip_tags($_REQUEST['website']);
// Saving the current post, if a form was submitted
$post_fields = array();
$post_fields['name'] = $name;
$post_fields['email'] = $email;
$post_fields['message'] = $message;
$post_fields['date'] = $date;
$post_fields['gender'] = $gender;
$post_fields['website'] = $website;
$success_flag = saveCurrentPost($post_fields);
}
//Fetching all posts from the database
$posts_array = getAllPosts();
?>
<?php
if(isset($name)) {
echo "<h3>Thanks ".$name." for submitting your post.</h3>";
}
?>
<div id="logo"> Don't forget to tell all you're friends about Daily Dorm News! <br> The only dorm news website on campus!</div>
<p id="received">Here are all the posts we have received.</p>
<ul id="posts_list">
<?php
// Looping through all the posts in posts_array
$counter = 1;
foreach(array_reverse($posts_array) as $post){
$alreadyPosted = false;
$name = $post['name'];
$email = $post['email'];
$message = $post['message'];
$date = $post['date'];
$gender = $post['gender'];
$website = $post['website'];
if ($counter % 2==1)
$li_class = "float-left";
else
$li_class = "float-right";
if ($name == $_GET['name']) {
$alreadyPosted = true;
}
echo '<div class=post';
if ($alreadyPosted) {
echo ' id="highlight"';
}
echo '>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' email is: '.$email.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' wrote '.$message.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>This event occured on '.$date.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>Your a '.$gender.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>You said your favorite website is '.$website.'</span></h3></li>';
echo '</div>';
}
?>
</ul>
</div>
<p id="submit">Would you like to submit another post?</p>
<?php require 'footer.php' ?>
</body>
</html>
You can check through jquery in the submit function
var datepicker=$("#datepicker").val();
if(datepicker=='') { alert('Please enter date'); return false; }
It should be
if(empty(($date)) {
echo "sorry you did not enter a date";
}
NOT
if(!empty(($date)) {
echo "sorry you did not enter a date";
}
The first expression will print "sorry you did not enter a date" if the date field is empty. The second expression will print that message if the date field is not empty.
You can try the code below. It will print 'This is an empty string'
<?php
$date = '';
if (empty($date)) {
echo 'This is an empty string';
}
if (!empty($date)) {
echo 'The date is ' . $date;
}

Php errors, cant find where

I have this file that I need help fixing the errors I am gettng. I checked and it seems fine, but something must be wrong. The errors are
Notice: Undefined index: name in /home/info130/FA13/users/tmh233fa13/www/Test/posting_wall.php on line 62
and my php is listed below, both files.
Thanks!
Posting_wall.php file.
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="post.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
</head>
<body>
<?php
/* [INFO/CS 1300 Project 3] index.php
* Main page for our app.
* Shows all previous posts and highlights the current user's post, if any.
* Includes a link to form.php if user wishes to create and submit a post.
*/
require('wall_database.php');
// Fetching data from the request sent by form.php
$name = $_REQUEST['name'];
$is_valid_post = true;
// Checking if a form was submitted
if (isset($_REQUEST['name'])){
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
// Saving the current post, if a form was submitted
$post_fields = array();
$post_fields['name'] = $name;
$post_fields['email'] = $email;
$post_fields['message'] = $message;
$post_fields['date'] = $date;
$success_flag = saveCurrentPost($post_fields);
}
//Fetching all posts from the database
$posts_array = getAllPosts();
require('header.php');
?>
<p>Submit a Post</p>
<?php
if(isset($name)) {
echo "<h3>Thanks ".$name." for submitting your post.</h3>";
}
?>
<p>Here are all the posts we have received.</p>
<ul id="posts_list">
<?php
// Looping through all the posts in posts_array
$counter = 1;
foreach(array_reverse($posts_array) as $post){
$name = $post['name'];
$email = $post['email'];
$message = $post['message'];
$date = $post['date'];
if ($counter % 2==1)
$li_class = "float-left";
else
$li_class = "float-right";
echo '<li class="'.$li_class.'"><h3><span>'.$name.'</span> wrote a post.</h3></li>';
// Add more details here
}
?>
</ul>
</div>
</body>
</html>
Form.php file
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="index.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
$('form').submit(function (e) {
var value;
// "message" pattern : from 3 to 15 alphanumerical chars
value = $('[name="message"]').val();
if (!/^[A-Za-z0-9]{3,15}$/.test(value)) {
alert('Wrong value for "message".');
e.preventDefault();
return;
}
// "name" pattern : at least 1 digit
value = $('[name="name"]').val();
if (!/\d+/.test(value)) {
alert('Wrong value for "name".');
e.preventDefault();
return;
}
});
});
</script>
</head>
<body>
<h1> <u>Daily Dorm News</u> <br> The best place to get your latest Dorm news </h1>
<form action="posting_wall.php" method="get">
<div id="container">
Name:<input type="text" name="name" pattern="[A-Za-z0-9]{3,15}" title="Letters and numbers only, length 3 to 15" required autofocus><br>
E-mail: <input type="email" name="email" maxlength="20" required><br>
Post:<br>
<textarea rows="15" cols="50" name='message'></textarea>
</div>
Date this event took place: <input type="text" name='date' id="datepicker" required> <br>
<input type="reset" value="Reset">
<input type="submit">
</form>
<p>Posting Wall</p>
</body>
</html>
It means that the HTTP POST lack the 'name' key.
The error is explicit, if you edit the php file and go to line 62, you can understand.
You never set $name, you set $username.
Copyed and clipped from your code:
$username = strip_tags($_REQUEST['name']);
...
$post_fields['username'] = $name;

Categories