I've successfully created a contact form with php that gives the various required messages. Now I would like to add a simple random arithmetic captcha (non-image). See the anonymised (working) html form and existing (working, but without arithmetic captcha) php below.
The idea is to show "Incorrect answer" in the same way as the other error messages, or to pass to the Thankyou page for a correctly filled out form with correct answer. I've had a good go at this but can't quite get it to work. Any assistance much appreciated.
HTML:
<p>Area of interest:
<input type="radio" name="likeit" value="A" checked="checked" /> A
<input type="radio" name="likeit" value="B" /> B
<input type="radio" name="likeit" value="C" /> C</p>
<p>How did you hear about us?
<select name="how">
<option value=""> -- Please select -- </option>
<option>Recommendation</option>
<option>Internet</option>
<option>Advertisement</option>
<option>Other</option>
</select></p>
<p><strong>Your message subject:</strong><br /><input type="text" name="subject" size="35"/></p>
<p><strong>Your message:</strong><br />
<textarea name="comments" rows="10" cols="40"></textarea></p>
<p>Please answer the following arithmetic question: What is <?php echo $digit1;?> + <?php echo $digit2;?>?
<input name="captcha" type="text" size="2" id="captcha"/></p>
<p><input type="submit" value="Send" /></p>
</form>
PHP:
<?php
/* Contact form with arithmetic captcha */
$myemail = "enquiries#X.co.uk";
/* Check all form inputs using check_input function */
$yourname = check_input($_POST['yourname'], "Enter your name");
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$website = check_input($_POST['website']);
$likeit = check_input($_POST['likeit']);
$how_find = check_input($_POST['how']);
$subject = check_input($_POST['subject'], "Add a subject");
$comments = check_input($_POST['comments'], "Add your message");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Email address is not valid");
}
/* If URL is not valid set $website to empty */
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))
{
$website = '';
}
/* Message for the email */
$message = "Hello!
Your contact form has been submitted by:
Name: $yourname
Email: $email
Telephone: $telephone
URL: $website
Area of interest? $likeit
How did they find us? $how_find
Comments:
$comments
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thankyou page */
header('Location: thankyou.html');
exit();
/* Functions used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
Head data in here
-->
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<div id="mainheader">
<div id="mainlogo">
<h1><a href="http://www.X.co.uk/" title="X">
<img style="border:0;width: 260px; height: 160px;" src="images/X.jpg" alt="X" /></a></h1>
</div>
</div>
<div id="content">
<div class="content">
<h2 class="title">Error!</h2>
<p><strong>Please correct the following error:</strong></p>
<p><?php echo $myError; ?></p>
</div>
</div>
<div id="panel">
<div id="main" class="boxed">
<h2 class="heading">Main</h2>
<ul>
<li>Home </li>
<li>About </li>
<li>Contact </li>
</ul>
</div>
<div id="services" class="boxed">
<h2 class="heading">Services</h2>
<ul>
<li>Services </li>
<li>Recent projects </li>
</ul>
</div>
<div id="pricing" class="boxed">
<h2 class="heading">Pricing</h2>
<ul>
<li>Pricing </li>
</ul>
</div>
<div id="info" class="boxed">
<h2 class="heading">Info</h2>
<ul>
<li>Tips and tricks </li>
<li>Useful links </li>
<li>Frequently asked questions </li>
<li>Site map </li>
</ul>
</div>
<div id="contact" class="boxed">
<h2 class="heading">Contact</h2>
<ul>
<li>Contact by email </li>
<li><strong>Telephone:<br />X</strong> </li>
</ul>
</div>
</div>
<div id="mainfooter">
<p> © 2011 X<br />Designed by <strong>X</strong> </p>
<a href="http://validator.w3.org/check?uri=referer" title="Valid XHTML 1.0">
<img style="border:0;width:88px;height:31px" src="images/valid-xhtml10.png" alt="Valid XHTML 1.0" />
</a>
<a href="http://jigsaw.w3.org/css-validator/check/referer" title="Valid CSS!">
<img style="border:0;width:88px;height:31px" src="images/vcss.gif" alt="Valid CSS!" />
</a>
</div>
</body>
</html>
<?php
exit();
}
?>
Generally, the idea of captcha is to prevent automated form processing. Any non-image comparisons will be easily solved.
Regardless, I would use sessions to solve this issue.
Simply store the expected result in a session variable on the first page, and make sure it matches on the second
page1.php:
<?php
session_start();
$digit1 = mt_rand(1,20);
$digit2 = mt_rand(1,20);
if( mt_rand(0,1) === 1 ) {
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
} else {
$math = "$digit1 - $digit2";
$_SESSION['answer'] = $digit1 - $digit2;
}
?>
<form method="POST" action="page2.php">
What's <?php echo $math; ?> = <input name="answer" type="text" /><br />
<input type="submit" />
</form>
page2.php
session_start();
echo "You entered ".htmlentities($_POST['answer'])." which is ";
if ($_SESSION['answer'] == $_POST['answer'] )
echo 'correct';
else
echo 'wrong. We expected '.$_SESSION['answer'];
?>
Use a Simple PHP Math Captcha
https://github.com/kmlpandey77/MathCaptcha
MathCaptcha
A Simple PHP Math Captcha
Usage
composer require kmlpandey77/math-captcha
Math in Image
It will return Math in image
Create captcha.php
<?php
require_once 'vendor/autoload.php'; // link to vendor's autoload.php
use Kmlpandey77\MathCaptcha\Captcha;
$captcha = new Captcha();
$captcha->image();
Create form.php
<form action="check.php" method="post">
<p>
Answer it <img src="./captcha.php" alt="" valign="middle"> <input type="text" name="captcha">
</p>
<p><button type="submit" name="submit">Submit</button></p>
</form>
Math in Text
It will return Math in text
Create form.php
Place this code to top of form.php
<?php
require_once 'vendor/autoload.php'; // link to vendor's autoload.php
use Kmlpandey77\MathCaptcha\Captcha;
?>
And place this code in body
<form action="check.php" method="post">
<p>
Answer it <?php echo new Captcha; ?> <input type="text" name="captcha">
</p>
<p><button type="submit" name="submit">Submit</button></p>
</form>
Check
Checks to see if the user entered the correct captcha key
Create check.php
<?php
require_once 'vendor/autoload.php'; // link to vendor's autoload.php
use Kmlpandey77\MathCaptcha\Captcha;
if(isset($_POST['submit'])){
if(Captcha::check()){
//valid action
echo('<font color="green">Answer is valid</font>');
}else{
echo('<font color="red">Answer is invalid</font>');
}
}
Related
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>©2019 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....
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");
I created a little form validator with PHP and having some problems with it.
MY VIEW FILE is here :
<form action="" method="post">
<?php if( isset($status) ) : ?>
<p class="notice"><?php echo $status; ?> </p>
<?php endif; ?>
<ul>
<li>
<label for="name">Your Name : </label>
<input type="text" name="name">
</li>
<li>
<label for="email">Your Email : </label>
<input type="text" name="email">
</li>
<li>
<input type="submit" value="Sign Up">
</li>
</ul>
</form>
and here's my little controller :
<?php
require 'index.tmpl.php';
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if (empty($name) || empty($email)) {
$status = "Please provide a name and a valid email address";
}
echo $name;
}
?>
Now what happens is that , when I open up the page and leave the form fields blank and submit it ,it just reloads ,does not echo anything.
You want to echo $status, not $name.
How about moving the require line to below the if?
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if (empty($name) || empty($email)) {
$status = "Please provide a name and a valid email address";
}
echo $name;
}
require 'index.tmpl.php';
?>
The <form action="" points to the location where the form will be submitted. If blank, it submits the form back to itself.
<form action="yourLittleController.php" method="POST">
Edited with more info:
in php, post is not POST. Example here: https://eval.in/89002
make sure you have
method="POST">
and not
method="POST">
you should mention your second file name in your view file's form's action attribute like action = "controller.php"
My entire error code is Parse error: syntax error, unexpected $end in /home/a3704125/public_html/home.php on line 356
Here is my entire PHP file.. Tell me what the problem may be? ._. Thanks!
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('GamesFXLogin');
// Starting the session
session_set_cookie_params(2*7*24*60*60);
// Making the cookie live for 2 weeks
session_start();
if($_SESSION['id'] && !isset($_COOKIE['GamesFXRemember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the GamesFXRemember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: home.php?logout=true");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM gamesfx_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('GamesFXRemember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php?page=home&error=true");
exit;
}
else if($_POST['submit']=='Register')
{
// If the Register form has been submitted
$err = array();
if(isset($_POST['submit']))
{
//whether the username is blank
if($_POST['username'] == '')
{
$err[] = 'User Name is required.';
}
if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32)
{
$err[]='Your username must be between 3 and 32 characters!';
}
if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))
{
$err[]='Your username contains invalid characters!';
}
//whether the email is blank
if($_POST['email'] == '')
{
$err[]='E-mail is required.';
}
else
{
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$sql1 = "SELECT * FROM gamesfx_members WHERE email = '$email'";
$result1 = mysql_query($link,$sql1) or die(mysql_error());
if (mysql_num_rows($result1) > 0)
{
$err[]='This Email is already used.';
}
}
else
{
//this error will set if the email format is not correct
$err[]='Your email is not valid.';
}
}
//whether the password is blank
if($_POST['password'] == '')
{
$err[]='Password is required.';
}
if(!count($err))
{
// If there are no errors
// Make sure the email address is available:
if(!count($err))
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$activation = md5(uniqid(rand()));
$encrypted=md5($password);
$sql2 = "INSERT INTO gamesfx_members (usr, email, pass, Activate) VALUES ('$username', '$email', '$encrypted', '$activation')";
$result2 = mysql_query($link,$sql2) or die(mysql_error());
if($result2)
{
$to = $email;
$subject = "Confirmation from GamesFX to $username";
$header = "GamesFX: Confirmation from GamesFX";
$message = "Please click the link below to verify and activate your account. rn";
$message .= "http://www.mysite.com/activate.php?key=$activation";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail)
{
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
else
{
echo "Cannot send Confirmation link to your e-mail address";
}
}
exit();
}
}
$script = '';
if($_SESSION['msg'])
{
// The script below shows the sliding panel on page load
$script = '
<script type="text/javascript">
$(function(){
$("div#panel").show();
$("#toggle a").toggle();
});
</script>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A Cool Login System With PHP MySQL & jQuery | Tutorialzine demo</title>
<link rel="stylesheet" type="text/css" href="demo.css" media="screen" />
<link rel="stylesheet" type="text/css" href="css/slide.css" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<!-- PNG FIX for IE6 -->
<!-- http://24ways.org/2007/supersleight-transparent-png-in-ie6 -->
<!--[if lte IE 6]>
<script type="text/javascript" src="js/pngfix/supersleight-min.js"></script>
<![endif]-->
<script src="js/slide.js" type="text/javascript"></script>
<?php echo $script; ?>
</head>
<body>
<!-- Panel -->
<div id="toppanel">
<div id="panel">
<div class="content clearfix">
<div class="left">
<h1>The Sliding jQuery Panel</h1>
<h2>A register/login solution</h2>
<p class="grey">You are free to use this login and registration system in you sites!</p>
<h2>A Big Thanks</h2>
<p class="grey">This tutorial was built on top of Web-Kreation's amazing sliding panel.</p>
</div>
<?php
if(!$_SESSION['id']):
?>
<div class="left">
<!-- Login Form -->
<form class="clearfix" action="" method="post">
<h1>Member Login</h1>
<?php
if($_SESSION['msg']['login-err'])
{
echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
unset($_SESSION['msg']['login-err']);
}
?>
<label class="grey" for="username">Username:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" id="password" size="23" />
<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> Remember me</label>
<div class="clear"></div>
<input type="submit" name="submit" value="Login" class="bt_login" />
</form>
</div>
<div class="left right">
<!-- Register Form -->
<form action="" method="post">
<h1>Not a member yet? Sign Up!</h1>
<?php
if($_SESSION['msg']['reg-err'])
{
echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
unset($_SESSION['msg']['reg-err']);
}
if($_SESSION['msg']['reg-success'])
{
echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
unset($_SESSION['msg']['reg-success']);
}
?>
<label class="grey" for="username">Username:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="email">Email:</label>
<input class="field" type="text" name="email" id="email" size="23" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" id="password" size="30" />
<label>A password will be e-mailed to you.</label>
<input type="submit" name="submit" value="Register" class="bt_register" />
</form>
</div>
<?php
else:
?>
<div class="left">
<h1>Members panel</h1>
<p>You can put member-only data here</p>
View your profile information and edit it
<p>- or -</p>
Log off
</div>
<div class="left right">
</div>
<?php
endif;
?>
</div>
</div> <!-- /login -->
<!-- The tab on top -->
<div class="tab">
<ul class="login">
<li class="left"> </li>
<li>Hello <?php echo $_SESSION['usr'] ? $_SESSION['usr'] : 'Guest';?>!</li>
<li class="sep">|</li>
<li id="toggle">
<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Open Panel':'Log In | Register';?></a>
<a id="close" style="display: none;" class="close" href="#">Close Panel</a>
</li>
<li class="right"> </li>
</ul>
</div> <!-- / top -->
</div> <!--panel -->
I am trying to use the slide panel that's a login panel.. Don't know if you ever heard of it. But anyhow, I am wondering how to fix this error. As-for I can't see what the problem may be.. I'm banging my head over it, thanks for the help!
EDIT: I added what's after the below this text..
<div class="pageContent">
<div id="main">
<div class="container">
<h1>A Cool Login System</h1>
<h2>Easy registration management with PHP & jQuery</h2>
</div>
<div class="container">
<p>This is a simple example site demonstrating the Cool Login System tutorial on <strong>Tutorialzine</strong>. You can start by clicking the <strong>Log In | Register</strong> button above. After registration, an email will be sent to you with your new password.</p>
<p>View a test page, only accessible by <strong>registered users</strong>.</p>
<p>The sliding jQuery panel, used in this example, was developed by Web-Kreation.</p>
<p>You are free to build upon this code and use it in your own sites.</p>
<div class="clear"></div>
</div>
<div class="container tutorial-info">
This is a tutorialzine demo. View the original tutorial, or download the source files. </div>
</div>
</div>
</body>
</html>
Closing brackets in here :
else if($_POST['submit']=='Register')
{
Put two closing brackets here:
$script = '';
}} #line 175
if($_SESSION['msg'])
Moral: always put opening and closing brackets together when going for any condition statement.
When using php do you set your path in reference to the files directory or from the page it is displayed from.
For example:
index.php is the home page of course
Directory structure.
index.php
includes > footer.php, header.php
product > product.php [blueproduct] > blueproduct.php
storescripts > connect_to_mysql.php, more.php
=================================================
Inside of footer I have a script that is not working on every page. Its a newsletter script to collect info. This is the code I'm using within my included footer.php:
</div>
<div class="footer">
<div class="wideNewsletter">
<div class="wrapNewsletter">
<div class="newsletterIntro"><b>NEWSLETTER SIGN UP</b></div>
<div class="newsletterForm">
<?php
$name = "";
$email = "";
$msg_to_user = "";
if ($_POST['name'] != "") {
include "../storescripts/connect_to_mysql.php";
// Be sure to filter this data to deter SQL injection, filter before querying database
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email) {
$msg_to_user = '<div class="warning"><ul><li>Please type an email address ' . $name . '.</li></ul></div><br /><br />';
} else if ($numRows > 0) {
$msg_to_user = '<div class="warning"><ul><li>' . $email . ' is already in the system.</li></ul></div><br /><br />';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime)
VALUES('$name','$email',now() )") or die (mysql_error());
$msg_to_user = '<div class="success"><ul><li>Thanks ' . $name . ', hope you find what you want!</li></ul></div><br /><br />';
$name = "";
$email = "";
}
$message = 'Name: ' . $_POST['name'] . ' Email: ' . $_POST['email'];
mail('newproducts#moniquetrinidadjewelry.com', 'New Newsletter Sign Up at Monique Trinidad Jewelry', $message);
}
?>
<form style="width:430px;" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset style="text-align:left;padding:0px;border:0px;">
Name:
<input name="name" type="text" maxlength="36" value="<?php echo $name; ?>" />
Email:
<input name="email" type="text" maxlength="36" value="<?php echo $email; ?>" />
<input type="image" src="https://www.moniquetrinidadjewelry.com/images/new-images/green-bullet.png" border="0" name="mySubmitBtn" type="submit" value="Submit">
</fieldset>
</form></div>
<div style="position:absolute;top:120px;"><?php echo $msg_to_user; ?></div>
<div class="newsletterExplain">Receive product updates. Remember only one of each!</div>
</div>
</div><!--wide newletter end-->
<div class="wrapFooter">
<div class="tearOneFooter">
<div class="footerColumnList">
<div class="footerTitles">Connect With Us</div>
<div class="footerLists">
<ul>
<li>Connect With Monique!</li>
</ul>
</div>
</div>
<!--Seperate Connect With us Column from Information Column-->
<div class="footerColumnList">
<div class="footerTitles">Information</div>
<div class="footerLists">
<ul>
<li>About Us</li>
<li>Packaging</li>
<li>Terms & Conditions</li>
</ul>
</div>
</div>
<!--Seperate Information Column from Shipping and Returns Column-->
<div class="footerColumnList">
<div class="footerTitles">Shipping and Returns</div>
<div class="footerLists">
<ul>
<li><a href="https://www.moniquetrinidadjewelry.com/return-policy.php">Orders and Returns<a/></li>
<li>Secure Shopping</li>
<li></li>
</ul>
</div>
</div>
<!--Seperate Shipping and Returns Column from Services & Support Column-->
<div class="footerColumnList">
<div class="footerTitles">Hours Of Operation</div>
<div class="footerLists">
<ul>
<li>We are a 24/7 <br />Online Establishment!<br />(US Based)</li>
</ul>
</div>
</div>
<!--Seperate Connect With us Column from Information Column-->
</div>
<!--Beging SecondTearFooterArea-->
<div class="tearTwoFooter">
<!--<div class="signUpNewsLetter"><img src="https://www.moniquetrinidadjewelry.com/images/news_letter_temp_IMG.png" alt="newsletter" /></div>-->
<div class="paymentOptions"><img src="https://www.moniquetrinidadjewelry.com/images/payment_options_temp.png" alt="payment options" /></div>
<div class="twitter"><img src="https://www.moniquetrinidadjewelry.com/images/twitter_temp.png" alt="twitterLink" /></div>
</div>
</div>
</div>
</div>
This is working within the [blueproduct] directory from the product directory, but not the index.php.
I have another issue as well, but I believe better practice would be to open another question after I've done research on the issue correct? If not let me know and I'll edit this original message.
================================================================================
Edits and Additions Below
I have everything configured and I believe I can elminiate this as the issue. I'm really stumped on this one. The link to give you a better idea of what I mean is http://www.moniquetrinidadjewerly.com . If you go there and try the form it doesn't process, but that same form if you select 'necklace' within the navigation you can see works fine and runs correctly. Here is the updated footer.php file below to include changes for abs path.
</div>
<div class="footer">
<div class="wideNewsletter">
<div class="wrapNewsletter">
<div class="newsletterIntro"><b>NEWSLETTER SIGN UP</b></div>
<div class="newsletterForm">
<?php
$name = "";
$email = "";
$msg_to_user = "";
if ($_POST['name'] != "") {
include_once(DOC-ROOT."/storescripts/connect_to_mysql.php");
// Be sure to filter this data to deter SQL injection, filter before querying database
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email) {
$msg_to_user = '<div class="warning"><ul><li>Please type an email address ' . $name . '.</li></ul></div><br /><br />';
} else if ($numRows > 0) {
$msg_to_user = '<div class="warning"><ul><li>' . $email . ' is already in the system.</li></ul></div><br /><br />';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime)
VALUES('$name','$email',now() )") or die (mysql_error());
$msg_to_user = '<div class="success"><ul><li>Thanks ' . $name . ', hope you find what you want!</li></ul></div><br /><br />';
$name = "";
$email = "";
}
$message = 'Name: ' . $_POST['name'] . ' Email: ' . $_POST['email'];
mail('newproducts#moniquetrinidadjewelry.com', 'New Newsletter Sign Up at Monique Trinidad Jewelry', $message);
}
?>
<form style="width:430px;" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset style="text-align:left;padding:0px;border:0px;">
Name:
<input name="name" type="text" maxlength="36" value="<?php echo $name; ?>" />
Email:
<input name="email" type="text" maxlength="36" value="<?php echo $email; ?>" />
<input type="image" src="https://www.moniquetrinidadjewelry.com/images/new-images/green-bullet.png" border="0" name="mySubmitBtn" type="submit" value="Submit">
</fieldset>
</form></div>
<div style="position:absolute;top:120px;"><?php echo $msg_to_user; ?></div>
<div class="newsletterExplain">Receive product updates. Remember only one of each!</div>
</div>
</div><!--wide newletter end-->
<div class="wrapFooter">
<div class="tearOneFooter">
<div class="footerColumnList">
<div class="footerTitles">Connect With Us</div>
<div class="footerLists">
<ul>
<li>Connect With Monique!</li>
</ul>
</div>
</div>
<!--Seperate Connect With us Column from Information Column-->
<div class="footerColumnList">
<div class="footerTitles">Information</div>
<div class="footerLists">
<ul>
<li>About Us</li>
<li>Packaging</li>
<li>Terms & Conditions</li>
</ul>
</div>
</div>
<!--Seperate Information Column from Shipping and Returns Column-->
<div class="footerColumnList">
<div class="footerTitles">Shipping and Returns</div>
<div class="footerLists">
<ul>
<li><a href="https://www.moniquetrinidadjewelry.com/return-policy.php">Orders and Returns<a/></li>
<li>Secure Shopping</li>
<li></li>
</ul>
</div>
</div>
<!--Seperate Shipping and Returns Column from Services & Support Column-->
<div class="footerColumnList">
<div class="footerTitles">Hours Of Operation</div>
<div class="footerLists">
<ul>
<li>We are a 24/7 <br />Online Establishment!<br />(US Based)</li>
</ul>
</div>
</div>
<!--Seperate Connect With us Column from Information Column-->
</div>
<!--Beging SecondTearFooterArea-->
<div class="tearTwoFooter">
<!--<div class="signUpNewsLetter"><img src="https://www.moniquetrinidadjewelry.com/images/news_letter_temp_IMG.png" alt="newsletter" /></div>-->
<div class="paymentOptions"><img src="https://www.moniquetrinidadjewelry.com/images/payment_options_temp.png" alt="payment options" /></div>
<div class="twitter"><img src="https://www.moniquetrinidadjewelry.com/images/twitter_temp.png" alt="twitterLink" /></div>
</div>
</div>
</div>
</div>
The config.inc.php file is located within the main directory and it reads :
<?php
define("Monique trinidad Jewelry","My Website");
define("DOC_ROOT","/home3/onlinfr7/public_html");
define("URL","https://www.moniquetrinidadjewelry.com");
?>
I'm not sure where the issue is occurring or what exactly is happening with the homepage(index.php) newsletter form in the footer. Why it works in one page, but not the other. It seems that path may not be the issue as I first thought. Any advice?
there's the current working directory, which you can get with getcwd(). THAT'S the path that everything will be relative to in any file operations you perform. By default it will be the directory that your main script is executed from.
Whether you go relative to that, or relative to something else, or just absolute on everything is up to you. There's no right/wrong answer - just whatever's easiest for YOU to maintain.
What I like to do that makes things easier when including other files is create a config file and include that in the main file or header like index.php
So this might be my config file called config.inc.php
<?php
define("SITENAME","My Website");
define("DOC_ROOT","/home/username/webroot");
define("URL","http://www.example.com");
?>
I include this config file in my index.php like
include("/home/username/webroot/config.inc.php");
Then I can use DOC_ROOT whenever I want to include another file somewhere and it will always have the full absolute path so that you know it's included.
e.g. include_once(DOC_ROOT."/storescripts/connect_to_mysql.php");