I am working on a project where I send the information being stored in the session variable $_SESSION['favourites'].
I made use of the print_r function print_r($_SESSION, true) and it did work with the output being as follows
Array
(
[favourites] => Array
(
[0] => Array
(
[item_id] => 3
)
[1] => Array
(
[item_id] => 11
)
)
)
Instead I implemented a foreach with a while loop to display the contents and store them in a variable $email_message. The problem with the code is that since $email_message is a variable it is being overwritten and echoed in a while loop.
My main objective is to send all the information in the session variable over email.
This is the phpmailer code including the foreach and while loop mentioned above.
<?php
use PHPMailer\PHPMailer\PHPMailer;
foreach($_SESSION["favourites"] as $key => $value)
{
$id = $value['item_id'];
$sql= "SELECT * FROM menu WHERE id = '$id'";
$result=mysqli_query($conn, $sql);
$resultcheck=mysqli_num_rows($result);
while($row=mysqli_fetch_assoc($result))
{
$email_message = ($row['id']). ($row['name']). ($row['price']).'<br>';
}
echo $email_message;
}
if(isset($_POST['fullname']) && isset($_POST['email']))
{
$name = $_POST['fullname'];
$email = $_POST['email'];
$subject = 'My favourite\'s list as of '. date("Y/m/d");
//Calling the PHPMailer 'functions'
require_once "vendor\phpmailer\phpmailer\src\PHPMailer.php";
require_once "vendor\phpmailer\phpmailer\src\SMTP.php";
require_once "vendor\phpmailer\phpmailer\src\Exception.php";
$mail = new PHPMailer();
//SMTP Settings
//$mail -> SMTPDebug = 3;
$mail -> isSMTP();
$mail -> Host = "smtp.gmail.com";
$mail -> SMTPAuth = true;
$mail -> Username = "cis1045sem2a2021#gmail.com";
$mail -> Password = 'universityofmalta';
$mail -> Port = 587;
$mail -> SMTPSecure = "tls";
//Email Settings
$mail -> isHTML(true);
$mail -> setFrom($email, $name);
$mail -> addAddress("cis1045sem2a2021#gmail.com");
$mail -> Subject = $subject;
$mail -> Body = $email_message;
if ($mail->send()) {
echo "Email is sent!";
} else {
echo "Something is wrong: <br><br>" . $mail->ErrorInfo;
}
}
?>
This is the favourites page.
<!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.0">
<title>El Tabata</title>
<link rel="shortcut icon" type="image/x-icon" href="./assets/images/mexican-mascot.png"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="./assets/CSS/styles.css">
<link rel="stylesheet" href="./assets/CSS/responsive.css">
</head>
<body>
<?php
include 'header.php';
include_once 'dbHandler.php';
if(isset($_SESSION))
{
session_destroy();
}
session_start();
?>
<!-- THE REMOVAL FROM FAVOURITES -->
<?php
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
{
foreach($_SESSION["favourites"] as $keys => $values)
{
if($values["item_id"] == $_GET["id"])
{
unset($_SESSION["favourites"][$keys]);
echo 'Item has been removed successfully';
echo '<script>window.location="favourites.php"</script>';
}
}
}
}
if(!empty($_SESSION['favourites']))
{
?>
<section class="container">
<ul id="contact_form" class="food-cards">
<!-- DISPLAYING THE ITEMS IN THE SESSION VARIABLE THROUGH DATABASE -->
<?php
foreach($_SESSION["favourites"] as $key => $value)
{
$id = $value['item_id'];
$sql= "SELECT * FROM menu WHERE id = '$id'";
$result=mysqli_query($conn, $sql);
$resultcheck=mysqli_num_rows($result);
while($row=mysqli_fetch_assoc($result))
{
?>
<li class="card-info">
<div class="food-card">
<div class="food-pic">
<img src="./assets/images/english-breakfast.png" alt="">
</div>
<div class="food-cont">
<h2 class="food-title">
<?php echo $row["name"]; ?>
</h2>
<div class="price-fav-btn">
<div class="price">
<?php echo "€".$row["price"]; ?>
</div>
<input type="hidden" name="hidden_id" value="<?php echo $row["id"]; ?>" />
<a style="color: white;" href="favourites.php?action=delete&id=<?php echo $id; ?>">Remove from favorits</a>
</div>
</div>
</div>
</li>
<?php
}
}
?>
</ul>
<div class="form-fav">
<form id="contact_form" method="POST">
<input type="text" name="fullname" placeholder="Full Name" required>
<input type="text" name="email" placeholder="Email" required>
<!-- <input type="text" name="body" placeholder="Start typing your message" required> -->
<button class="frm-btn" type="submit" name="submit" value="Submit">Submit</button>
</form>
</div>
</section>
<?php
echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
require 'emailfunction.php';
}
else
{
?>
<section>
<div class="container">
<h4> Please add an item to your favourite's list. </h4>
<img src="./assets/images/sad-taco.jpg" alt="sad-taco">
</div>
</section>
<?php
} //end of main if-else statement
?>
<?php include 'footer.php' ?>
<script src="main.js"></script>
</body>
</html>
This is the html preview
Html Preview
This is the email preview where it is only sending 1 item only.
Function is sending 1 item only
This is what I am trying to achieve where it sends every item in 1 email.
What I am trying to achieve
If i understood correctly the problem is here:
$email_message = ($row['id']). ($row['name']). ($row['price']).'<br>';
This way you always replacing the value in $email_message
Instead of that you should concatenate the message as follows
First declare $email_message = ''; before the loop
And in the loop write:
$email_message .= ($row['id']). ($row['name']). ($row['price']).'<br>';
or
$email_message .= ($row['id']). ($row['name']). ($row['price']).PHP_EOL;
And by the way the help is coming from Malta too ;)
Change this:
$email_message = ($row['id']). ($row['name']). ($row['price']).'<br>';
to this:
$email_message .= ($row['id']). ($row['name']). ($row['price']).'<br>';
That's what El_Vanja was saying.
Related
I have a query where I check if a user it's already stored on the database, but the problem it's that it's perfectly working on MYSQL but not on PostgreSQL where I need it..what can I do? The steps are: user register for an account. If it already exists in the database it returns an message, if no, send an email where he needs to confirm the registration. The confirmation doesn't work(the adress where the user can enter and activate his account).
This is the confirmation code(email_verification.php):
<?php
ob_start();
$success = false;
// Errors reporting, used if needed
error_reporting(E_ALL);
ini_set('display_errors', 'on');
// General configuration like base, used if needed
include_once ('include/config.inc.php');
// Mail functions
include_once ('include/mail.functions.php');
// Start session if needed
session_start();
// DBConn
include_once ('class/DB/DBConn.includeall.php');
$db = new DBConn(NULL);
// Includere clasa login
require_once ('class/class_login.php');
// Set up current language
$lang = "ro";
$_SESSION[PRE.'lang'] = $lang;
$message = '';
if(isset($_GET['cod_activare']))
{
$query = "
SELECT * FROM tregister
WHERE cod_activare = :cod_activare
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':cod_activare' => $_GET['cod_activare']
)
);
$no_of_row = $statement->rowCount();
if($no_of_row > 0)
{
$result = $statement->fetchAll();
foreach($result as $row)
{
if($row['email_status'] == '0')
{
$update_query = "
UPDATE tregister
SET email_status = '1'
WHERE id = '".$row['id']."'
";
$statement = $connect->prepare($update_query);
$statement->execute();
$sub_result = $statement->fetchAll();
if(isset($sub_result))
{
$message = '<label class="text-success">Email verificat cu success! <br />Poti efectua checkin-ul aici - Efectueaza check-in</label>';
}
}
else
{
$message = '<label class="text-info">Adresa de mail deja verificata</label>';
}
}
}
else
{
$message = '<label class="text-danger">Link invalid</label>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Hotel Amethyst</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<h3><?php echo $message; ?></h3>
</div>
</body>
</html>
<?php
ob_end_flush();
?>
And here it's the register.php:
<?php
ob_start();
$success = false;
// Errors reporting, used if needed
error_reporting(E_ALL);
ini_set('display_errors', 'on');
// General configuration like base, used if needed
include_once ('include/config.inc.php');
// Mail functions
include_once ('include/mail.functions.php');
// Start session if needed
session_start();
// DBConn
include_once ('class/DB/DBConn.includeall.php');
$db = new DBConn(NULL);
// Includere clasa login
require_once ('class/class_login.php');
// Set up current language
$lang = "ro";
$_SESSION[PRE.'lang'] = $lang;
$access = 0;
// Check if the cookie for "remember me" exists
if(isset($cookie_name))
{
if(isset($_COOKIE[$cookie_name]))
{
parse_str($_COOKIE[$cookie_name]);
$login = new Login($db);
if ($login->_checkLogin($usr, $hash) == true)
{
$access = 1;
}
}
}
$user = (isset($_POST['user']) && !empty($_POST['user'])) ? $_POST['user'] : "" ;
$email = (isset($_POST['email']) && !empty($_POST['email'])) ? $_POST['email'] : "" ;
$cod_activare = md5(rand());
$email_status=0;
$db = pg_connect("host=local port=5432 dbname=login_robinson user=robinson password=123");
$query = "INSERT INTO tregister(nume,email,cod_activare,email_status) VALUES ('$user','$email','$cod_activare','$email_status')";
$result = pg_query($query);
if(isset($_POST['submit'])){
$base_url = "http://local/login-robinson/www/";
$mail_body = "
Buna ziua ".$_POST['user'].",\n
Multumim pentru inregistrare. Te rog deschide acest link pentru a incepe procesul de check-in - ".$base_url."email_verification.php?activation_code=".$cod_activare."
Cu stima,\nHotel Amethyst
";
$from = 'Activare rezervare';
$subject = 'De pe site';
if (mail ($email, $subject, $mail_body, $from)){
echo "<script>
alert('Utilizator inregistrat cu success! Te rog verifica adresa de mail!');
window.location.href='login.php';
</script>";
}
else{
echo "<script>
alert('S-a produs o eroare! Te rog mai verifica odata formularul!');
</script>";
}
if($user !=''&& $email !='')
{
$success=true;
}
}
?>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<!-- <base href="http://dev.incorom.local/ticketing/www/login.php" /> -->
<title>Inregistrare</title>
<?php
include('include/links.php');
include('include/scripts.php');
?>
</head>
<body style="display: block !important;" ng-cloak="" ng-class="{ 'layout-fixed' : app.layout.isFixed, 'layout-boxed' : app.layout.isBoxed, 'layout-dock' : app.layout.isDocked, 'layout-material': app.layout.isMaterial, 'aside-offscreen' : app.sidebar.isOffscreen, 'aside-mini' : app.sidebar.isMini, 'aside-right' : app.sidebar.isRight, 'footer-hidden': app.footer.hidden, 'in-app': !$state.includes('page')}">
<div class="animated fadeOutZoom">
<div class="container container-sm animated fadeInDown">
<div class="center-block mt-xl">
<img src="images/logo_iconlab.png" alt="Image" class="center-block img-rounded">
<div class="panel">
<div class="panel-body">
<p class="pv text-bold">Date de inregistrare rezervare</p>
<form class="mb-lg" method="post" action="register.php" id="form">
<div class="row">
<div class="col-md-12">
<div class="form-group has-feedback mb">
<input type="text" placeholder="Nume" autocomplete="off" class="form-control" name="user" id="user" required /><span class="fa fa-envelope form-control-feedback text-muted"/></span>
</div><br>
<div class="form-group has-feedback mb">
<input type="email" placeholder="Adresa de mail" autocomplete="off" class="form-control" name="email" id="email" required /><span class="fa fa-envelope form-control-feedback text-muted"/></span>
</div><br>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-block btn-info btnblue mb" name="submit">Inregistrare</button>
</div>
</div>
<div id="main_area" class="row-fluid">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<?php
ob_end_flush();
?>
The registration works OK but I can register the same email for an infinite number of times.
I'm trying a tutorial about making a private inbox feature, everything went well apart from the fact I get a 500 server error every time I try to press send. I have checked out the logs for what could be causing this error and here's what I received: PHP Fatal error: Call to undefined function fetch_users_id() in /apps/bla/web/inboxPage.php on line 17, referer: http://hinat.local/inboxPage.php
I have checked the function to see if anything is out of place, but cannot spot anything that could be throwing it off.
Would appreciate another pair of eyes to help me see what I have done wrong here.
Thanks in advance!
inboxPage.php:
<?php
if(isset($_POST['to'], $_POST['subject'], $_POST['body'])){
$errors = array();
if(empty($_POST['to'])){
$errors[] = 'You must enter at least one name.';
} else if (preg_match('#^[a-z, ]+$#i', $_POST['to']) === 0){
$errors[] = 'The list of names you gave does not look valid.';
} else {
$user_names = explode(',',$_POST['to']);
//Will remove and trailing spaces before and after name
foreach ($user_names as &$name){
$name = trim($name);
}
$user_id = fetch_users_id($user_names);
if(count($user_id) !== count($user_names)){
$errors[] = 'The following users could not be found: ' . implode(', ', array_diff($user_names, array_keys($user_id)));
}
}
if(empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
}
if(empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
if(empty($errors)){
}
}
if(isset($errors)){
//Form has been submitted but errors have occured
if(empty($errors)){
echo '<div class="msg success"> Your message has been sent! Return to your Inbox</div>';
//Form has been submittied and errors have occured
} else {
foreach ($errors as $errors) {
echo '<div class="msg error">', $errors, '</div>';
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="site.css" >
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,400" rel="stylesheet">
</head>
<body>
<!-- Header -->
<header class="primary-header container group">
<h1 class="logo">
<!-- <img src="../home/wendy/Pictures/Logo.png" alt="Website Logo"><br> -->
</h1>
<h3 class="tagline"> Cardiff, Wales </h3>
<nav class="nav primary-nav">
<ul>
<li>Home</li><!--
--><li>Login</li><!--
--><li>Register</li><!--
--><li>Tutors</li><!--
--><li>About Us</li><!--
--><li>Contact Us</li>
</ul>
</nav>
</header>
<form action="" method= "post">
<section class="row">
<div class="grid">
<div>
<label for="to">To</label>
<input type="text" name="to" id="to" value="<?php if (isset($_POST['to'])) echo htmlentities($_POST['to']); ?>" />
</div>
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" value="<?php if (isset($_POST['subject'])) echo htmlentities($_POST['subject']); ?>" />
</div>
<div>
<textarea name="body" rows="20" cols="110"><?php if (isset($_POST['body'])) echo htmlentities($_POST['body']); ?></textarea>
</div>
<div>
<input type="submit" value="send" />
</div>
</div>
</section>
</form>
<footer class="primary-footer container group">
<small> ©</small>
<nav class="nav">
<ul>
<li>Home</li><!--
--><li>Login<!--
--><li>Tutors<!--
--><li>Register<!--
--><li>About Us<!--
--><li>Contact Us
</ul>
</nav>
</footer>
</body>
</html>
users.php:
<?php
function fetch_users_id($user_names){
foreach($user_names as &$name) {
$name = mysql_real_escape_string($name);
}
$results = mysql_query("SELECT id, Username FROM users WHERE Username IN ('" . implode("', '", $user_names) . "')");
$names = array();
while (($row = mysql_fetch_assoc($results)) !== false){
$names[$row['Username']] = $row['id'];
}
return $names;
}
?>
The function fetch_users_id does not exist in inboxPage.php
You must include or require users.php in inboxPage.php if you want to use that function within that file.
<?php
include("users.php");
Thank you in advance for looking at my code and helping me with the problem i am having. I am trying to build a simple contact form. The thing is when i hit my submit button everything that gets directed to the next page displays everything into an array. How can i go about fixing this?
Also, my if statement is giving me a hard time how can i go about fixing this? Am i using the wrong type of arrays?
contact.php
<?php
session_start();
require_once 'PHPMailerAutoload.php';
$errors = [];
if(isset($_POST['name'], $_POST['email'], $_POST['message'])){
$fields = [
'name' => $_POST['name'],
'email' => $_POST['email'],
'message' => $_POST['message']
];
foreach($fields as $field => $data) {
if(empty($data)){
$errors[] = 'The ' . $field . ' field is required.';
}
}
if(empty($errors)){
$m = new PHPMailer;
$m->isSMTP();
$m->SMTPAuth = true;
$m->Host = 'smtp.gmail.com';
$m->Username = 'none#gmail.com';
$m->Host = 'Pa$$w0rd1';
$m->SMTPSecure = 'ssl';
$m->Port = '465';
$m->isHTML();
$m->Subject = 'Contact form submitted';
$m->Body = 'From: ' . $fields['name'] . ' (' . $fields['email'] . ')<p>' . $fields['message'] . '</p>';
$m->From = 'Contact';
$m->AddAddress('none#gmail.com', 'name');
if($m-> send()){
header('Location: thankyou.php');
die();
} else {
$errors[] = 'Sorry, could not send email. Try again late.';
}
}
} else {
$errors[] = 'Something went wrong.';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
header('Location: contactform.php');
?>
contactform.php
<?php
session_start();
require_once 'security.php';
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Contact Us</title>
<link rel="stylesheet" href="css/website.css">
</head>
<center><body>
<div class="contact">
<?php if(!empty($errors)): ?>
<div class="panel">
<ul><li><?php echo implode(('</li><li>'), $errors); ?></li></ul>
</div>
<?php endif; ?>
<form action="contact.php" method="post">
<label>
Your name *
<input type="text" name="name" autocomplete="off">
</label>
<br><label>
Your email address *
<input type="text" name="email" autocomplete="off">
</label>
<br><label>
Your message or concern *
<textarea name="message" rows="8"></textarea>
</label>
<input type="submit" value="Send">
<p class="muted">* means a required field</p>
</form>
</div>
</body></center>
</html>
<?php
unset($_SESSION['errors']);
unset($_SESSION['fields']);
?>
This is the if statement i am referring to in the above code
<?php if(!empty($errors)); ?>
<div class="panel">
<ul><li><?php echo implode(('</li><li>'), $errors); ?></li></ul>
</div>
<?php endif ?>
Please Please Please help me with this.
Problem is semicolon at end of your if statement.
If you want to use if with endif you need to use ":" like this:
if(!empty($errors)):
code;
endif;
Try this:
<?php if(!empty($errors)): ?>
<div class="panel">
<ul><li><?php echo implode(('</li><li>'), $errors); ?></li></ul>
</div>
<?php endif; ?>
The proper way to use if ... endif is:
<?php if (condition): ?>
// Things to do when condition is true
<?php endif; ?>
I have designed a form which check validation when it is sent, I am using Swiftmailer and all of the validation works however I have a problem. When I return back to the contact form the errors are still there if they filled it out wrong so...
name is required!
email is required!
the errors only go when it passes validation.
How do I refresh the page when the user leaves and comes back to a fresh form?
Contact form:
<?php
session_start();
?>
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>Send a message</title>
</head>
<body>
<div class="container">
<div <?php if(isset($_SESSION['form_message'])) { echo 'style="color: green"'; } elseif (isset($_SESSION['form_errors'])) { echo 'style="color: red"'; } ?>>
<?php
if(isset($_SESSION['form_message']))
{
echo $_SESSION['form_message'];
unset($_SESSION['form_data']);
}
elseif(isset($_SESSION['form_errors']))
{
echo '<b>You have the following errors:</b>';
echo "<br>";
foreach($_SESSION['form_errors'] as $display_err) {
echo $display_err . "<br>";
}
}
?>
</div>
<form name="contact" method="post" action="swift_mail.php">
<div>
<label for="name">Full name</label><br />
<input type="text" name="name" id="name" value="<?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['name'] ; } ?>" />
</div>
<div>
<label for="email">Email Address</label><br />
<input type="text" name="email" id="email" value="<?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['email'] ; } ?>" />
</div>
<div>
<label for="comment">Comment</label><br />
<textarea name="comment" id="comment"><?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['comment'] ; } ?></textarea>
<input type="submit" value="submit" name="submit_msg"/>
</div>
</form>
</div>
</body>
</html>
</code>
swift
<?php
session_start();
require_once 'Swift-5.0.3/lib/swift_required.php';
require 'vendor/autoload.php';
if(isset($_POST['submit_msg'])) {
/*
Validate data before it is posted
*/
$rule_set = array (
'name' => array(
'required'
),
'email' => array(
'required'
),
'comment' => array(
'required'
)
);
/*
Checking Validation
*/
$validation_result = SimpleValidator\Validator::validate($_POST, $rule_set);
if ($validation_result->isSuccess() == true ) {
/*
Contact Form Information
*/
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
// Main Point of contact
$email_address = 'ben#bubbledesign.co.uk';
// Composed Message
$body_msg = "Name: " . $name . "<br>" . "Comments: " .$comment;
/*
Swift Mail Transport
*/
$transport = Swift_MailTransport::newInstance();
$mail = Swift_Mailer::newInstance($transport);
/*
Create the Swift Message
*/
$message = Swift_Message::newInstance('Subject line')
->setFrom($email)
->setTo($email_address)
->setBody($body_msg, "text/html");
/*
Send Swift Message
*/
$result = $mail->send($message);
$_SESSION['form_message'] = "Thank you for your message someone will be in touch soon.";
unset($_SESSION['form_errors']);
unset($_SESSION['form_data']);
header('location: contact-form.php');
} else {
$_SESSION['form_data'] = $_POST;
$_SESSION['form_errors'] = $validation_result->getErrors();
header('Location: contact-form.php');
}
}
?>
I am trying to cater to past users who have posted in the past. What I am trying to do is highlight any of the users pasts posts and also, on the home page do something like welcome back $name ! ONLY if the user has posted before though. I have no idea how to do this, need to check against the database probably but I am not sure how.
Thank you in advance.
The blogs form
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/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 150 alphanumerical chars
value = $('[name="message"]').val();
if (!/^[-\.a-zA-Z\s0-9]{3,150}$/.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>
<?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:s Y-m-d') ."\n";
?>
</body>
</html>
Post page PHP
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/post.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
</head>
<body>
<h1>Your Daily Dorm News Post! </h1>
<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>
</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();
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">
<div id="posts">
<?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 '<div class=post>';
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>
</body>
</html>