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

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....

Related

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 keep the user logged on the entire web

I have a problem logging users. When logs, session work, but when you click to another page, the session will disappear and does not work and when I put session_start to the main page and to login.php, I got error that session is already running. Some ideas? Thanks
Main Page.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" type="text/css" href="css.css">
<link rel="icon" href="favicon.ico">
<title>----</title>
</head>
<body>
<!-- HEADER _____________________________________________________________________________ -- >
<div id="whiteblock">
<div id="grayblock">
<div id="logo">
</div>
<h1>----</h1>
<h2>----</h2>
Registration
<?php
include "Login.php";
echo $_SESSION["LogiNick"];
?>
<div id="inputposunuti">
<form name="Log" id="Log" method="post">
<label for="Nick" class="inputtext">Nick:</label>
<input type="text" name="LogiNick" id="LogiNick" class="input"> <?php echo $EmptyNick; echo $Else; ?>
<label for="Pass" class="inputtext">Password:</label>
<input type="password" name="LogiPass" id="LogiPass" class="input"> <?php echo $EmptyPass; echo $Else; ?>
<input type="submit" name="LogIn" value="⇒">
</form>
</div>
</div>
<!-- HEADER _____________________________________________________________________________ -->
<!-- MENU _______________________________________________________________________________ -->
<div id="pruh">
<div id="search">
<form name="search" method="post">
<input type="text" name="hledat" id="sirka">
<input type="submit" name="subhledat" value="Search!" id="button">
</form>
</div>
<div id="menutext">
<p>Home</p>
<p>----</p>
<p>----</p>
<p>----</p>
<p>----</p>
<p>----</p>
</div>
</div>
<!-- MENU _______________________________________________________________________________ -->
<!-- CONTENT ____________________________________________________________________________ -->
<!-- CONTENT ____________________________________________________________________________ -->
<div id="teams"></div>
</div>
<p id="creator">Created by</p>
Login.php
<?php
session_start();
include_once "db.php";
global $db;
$Else = $EmptyNick = $EmptyPass = $EmptyNick = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$LogiNick = $_POST["LogiNick"];
$LogiPass = $_POST["LogiPass"];
if (empty($_POST["LogiNick"])) {
$EmptyNick = " - Nick";
}
if (empty($_POST["LogiPass"])) {
$EmptyPass = " - Password";
}
}
if(!empty($_POST["LogiNick"]) AND !empty($_POST["LogiPass"])){
$LogiPass = $_POST["LogiPass"];
$SHA = sha1($LogiPass);
$sql = "SELECT * FROM WEB_REGISTER WHERE Nick = :nick AND Heslo = :heslo";
$query = $db->prepare($sql);
$query->execute(array('nick' => $LogiNick, 'heslo' => $SHA));
$count = $query->rowCount();
if ($count > 0) {
$_SESSION["LogiNick"];
}
}
?>
You just set a session if you put a value into it.
$_SESSION["name"]=$value;

Auto fill-in data (input field) from MySQL Database in PHP (PDO)

This post contains:
3 PHP pages
MySQL table picture
Picture of the form
As the title says, I need to extract some information from my database.
So far I have the following:
Index page <-- You need to login here with a personal code. (this is where I get the 'Session username' from that already works at the contact page)
Config page <-- Used for database access and all
Contact page <-- In here I would like to auto fill-in the users data.
Database table consists of:
username; email; realName (and some other stuff I don't need here)
So in the contact page I would like to see the following:
Card number = username (this already works)
Auto fill-in: realName and email according to the username.
Maybe it is possible to extract the info when logging in and storing these in the POST variable already? But how?
Database:
Table I need to use: 'members'
The info given by the user himself/herself = username
The info I need to auto fill-in = realName and email
Picture of the form.
The email should be in the SESSION statement, so I can send a confirmation email to the person, and the realName should be entered from the database.
These are the files currently running:
config.php:
<?php
ob_start();
session_start();
//set timezone
date_default_timezone_set('Europe/Brussels');
//database credentials
define('DBHOST','*****');
define('DBUSER','*****');
define('DBPASS','*****');
define('DBNAME','*****');
//application address
define('DIR','http://*****/');
define('SITEEMAIL','noreply#*****');
try {
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user class, pass in the database connection
include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?>
contact form:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: index.php'); }
?>
<html>
<head>
<title>*****</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="siteassets/assets/js/ie/shiv.js"></script><![endif]-->
<link rel="stylesheet" href="siteassets/assets/css/main.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="siteassets/assets/css/ie8.css" /><![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#next').keyup(calculate);
$('#nextprice').keyup(calculate);
$('#current').keyup(calculate);
$('#currentprice').keyup(calculate);
});
function calculate(e)
{
$('#total').val($('#next').val() * $('#nextprice').val() + $('#current').val() * $('#currentprice').val());
}
</script>
</head>
<body class="landing">
<div id="page-wrapper">
<!-- Header -->
<header id="header" class="alt">
<nav id="nav">
<ul>
<li>
Menu
<ul>
<li>Current Project</li>
<li>Next Projects</li>
<li>Previous Projects</li>
<li>Who are we?</li>
</ul>
</li>
<li>contact</li>
<li><a href='logout.php'>Logout</a></li>
</ul>
</nav>
</header>
<!-- Banner -->
<section id="banner">
<h2>*****</h2>
<p>Slogan.</p>
<ul class="actions">
<li>Current Project</li>
<li>Next Projects</li>
<li>Previous Projects</li>
<li>Who are we?</li>
<li>contact</li>
</ul>
</section>
<!-- Main -->
<section id="main" class="container 75%">
<div class="box">
<?
if($_SERVER['REQUEST_METHOD']=="POST")
{
if(strlen($_POST['name2']) == 0)
{ $error_msg ="- Please, provide us with your name.<br>"; }
if(!empty($error_msg))
{
//Een van de velden werd niet goed ingevuld
echo "<b>Your message can't be send due to the following reason:</b> <br><br>";
echo $error_msg;
echo "<br>Click on <a href='javascript:history.back(1)'>Go back</a> and provide us with your name.<br><br>";
}
else
{
$recipient = "*****";
$subject = "******";
$header = "From: " . $_POST['uwemail'] . "\n";
$mail_body = "Contact script werd op " . date("d-m-Y") . " om " . date("H:i") . " uur uitgevoerd.\n";
$mail_body .= "*****:\n\n";
$mail_body .= "Naam: " . $_POST['name2'] . "\n";
$mail_body .= "Met als kaartnummer: " . $_POST['card2'] . "\n";
$mail_body .= "******: " . $_POST['current2'] . "\n";
$mail_body .= "******: " . $_POST['next2'] . "\n";
$mail_body .= "Voor een totaal van: " . $_POST['total2'] . " EUR.";
$mail_body .= "\n\n -- ****** --";
mail($recipient, $subject, $mail_body, $header);
print "<b>IMPORTANT!</b>";
print "<br><br>*****.";
print "<br><br>***** ";
print $_POST['total2'];
print " *****";
print "<br><br>******.";
print "<br><br>******";
}
}
else
{
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="POST" name="contact">
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Your personal card number
<input type="text" name="card2" id="card" value="<?php echo $_SESSION['username']; ?>" placeholder="Card Number" readonly/>
</div>
<div class="6u 12u(mobilep)">
Please enter your name. (mandatory)
<input type="text" name="name2" id="name" value="" placeholder="Your name" />
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Current Project - Smile
<input type="text" name="current2" id="current" value="" placeholder="How many tickets would you like?" />
</div>
<div class="6u 12u(mobilep)">
Next Project - Sand
<input type="text" name="next2" id="next" value="" placeholder="How many tickets would you like?" />
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
<input type="hidden" id="currentprice" value="10" />
</div>
<div class="6u 12u(mobilep)">
<input type="hidden" id="nextprice" value="10" placeholder="" />
</div>
</div>
<div class="6u 12u(mobile)">
<input name="uwemail" placeholder="Email" type="hidden" value="******"/>
</div>
<div class="6u 12u(mobilep)">
Total price.(In EUR)
<input type="text" name="total2" id="total" value="" readonly/>
</div>
</div>
<div class="row uniform">
<div class="12u">
<ul class="actions align-center">
<li><input type="submit" name="submit"value="Place Order"/></li>
</ul>
</div>
</div>
</form>
<?php
}
?>
</div>
</section>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© *****. All rights reserved.</li>
</ul>
</footer>
</div>
<!-- Scripts -->
<script src="siteassets/assets/js/jquery.min.js"></script>
<script src="siteassets/assets/js/jquery.dropotron.min.js"></script>
<script src="siteassets/assets/js/jquery.scrollgress.min.js"></script>
<script src="siteassets/assets/js/skel.min.js"></script>
<script src="siteassets/assets/js/util.js"></script>
<!--[if lte IE 8]><script src="siteassets/assets/js/ie/respond.min.js"></script><![endif]-->
<script src="siteassets/assets/js/main.js"></script>
</body>
</html>
Index page (where they have to login)
<?php
//include config
require_once('includes/config.php');
//process login form if submitted
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: home.php');
exit;
} else {
$error[] = 'Wrong username or password or your account has not been activated.';
}
}//end if submit
?>
<html>
<head>
<title>******</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="assets/js/iv.js"></script><! [endif]-->
<link rel="stylesheet" href="assets/css/main.css" />
<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /> </noscript>
</head>
<body class="is-loading">
<!-- Wrapper -->
<div id="wrapper">
<!-- Main -->
<section id="main">
<header>
<h1>*****</h1>
<h1><a style="color:#FFFFFF" href=''>Coming soon.</a></h1>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form role="form" method="post" action="" autocomplete="off">
<h2>Please Login</h2>
<hr>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
if(isset($_GET['action'])){
//check the action
switch ($_GET['action']) {
case 'active':
echo "<h2 class='bg-success'>Your account is now active you may now log in.</h2>";
break;
case 'reset':
echo "<h2 class='bg-success'>Please contact us for a new card.</h2>";
break;
case 'resetAccount':
echo "<h2 class='bg-success'>Password changed, you may now login.</h2>";
break;
}
}
?>
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg" placeholder="Enter your card number" value=" <?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
</div>
<div class="form-group">
<input type="hidden" name="password" id="password" class="form-control input-lg" value="*****" tabindex="3" >
</div>
<br>
<div class="row">
<div class="col-xs-6 col-md-6"><input type="submit" name="submit" value="Login" class="btn btn-primary btn-block btn-lg" tabindex="5"></div>
</div>
<hr>
<div class="row">
<div class="col-xs-9 col-sm-9 col-md-9">
<a style="color:#FFFFFF" href='*********'>Lost your card? Contact us.</a>
</div>
</div>
</form>
</div>
</div>
</div>
</header>
</section>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© ******</li>
</ul>
</footer>
</div>
<!-- Scripts -->
<!--[if lte IE 8]><script src="assets/js/respond.min.js"> </script><![endif]-->
<script>
if ('addEventListener' in window) {
window.addEventListener('load', function() { document.body.className = document.body.className.replace(/\bis-loading\b/, ''); });
document.body.className += (navigator.userAgent.match(/(MSIE|rv:11\.0)/) ? ' is-ie' : '');
}
</script>
</body>
</html>
EDITED: Since you're having user class (ex.: $user->is_logged_in()), then in $_POST[] method ignore $_POST['name2'] as it can still be changed through DEV tools and instead change that to $_SESSION['username'] (assuming that's the correct value). This is much more reliable than using HTML field. The PHP part (of query) also differs because you're using PDO, but I can't help with this one because I'm using mysqli_, not PDO (sorry about that), but query itself should be similar.
"SELECT * FROM `table` WHERE `number` = '".$_POST['number']."'"
But don't forget to escape your string, otherwise, your query is vulnerable.
I fixed the problem.
In the user.php file I had everything prepared already, but I just didn't understand why it didn't work.
Turned out to be a simple error XD
<?php
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT password, username, memberID, realName, email FROM members WHERE username = :username AND active="Yes" ');
$stmt->execute(array('username' => $username));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$row = $this->get_user_hash($username);
if($this->password_verify($password,$row['password']) == 1){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['realName'] = $row['realName'];
$_SESSION['email'] = $row['email'];
return true;
}
}
public function logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
return true;
}
}
}
?>
I forgot to add the realName and email to this line: (idiot me :D)
$stmt = $this->_db->prepare('SELECT password, username, memberID, realName, email FROM members WHERE username = :username AND active="Yes" ');

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

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.

Syntax Error, unexpected $end -- PHP error, what's wrong?

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 &amp 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.

Categories