php email validation function does not get processed - php

I've written some code to create a contact form, however I have attempted to validate the email field and when I test using dummy data with incorrect email the function I use (filter_var($email, FILTER_VALIDATE_EMAIL)) does not get processed. I've added all my php and html code together in one file for easier readability and not to complicate things.
Here is my full code:
<?php
// define variables and set to empty values
$first_nameErr = $last_nameErr = $emailErr = $messageErr = "";
$first_name = $last_name = $email = $from = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$to = "pdgcaracas#gmail.com"; // this is your Email address
// this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$from = $_POST['email'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
if (empty($_POST["first_name"])){
$first_nameErr = " First name is required";
}
else if ((!preg_match("/^[a-zA-Z-' ]*$/",$first_name))) {
$first_nameErr = "Please type in only letters and whitespace";
}
else if(empty($_POST["last_name"])){
$last_nameErr = " Last name is required";
}
else if ((!preg_match("/^[a-zA-Z-' ]*$/",$last_name))) {
$last_nameErr = "Please type in only letters and whitespace";
}
else if (empty($_POST["email"])) {
$emailErr = "Email is required";
}
else if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Email is invalid";
}
else if (empty($_POST["message"])) {
$messageErr = "message is required";
}
else {
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo '<script>alert("Mail Sent. Thank you , we will contact you shortly.")</script>';
}
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
<!DOCTYPE HTML>
<!--
Industrious by TEMPLATED
templated.co #templatedco
Released for free under the Creative Commons Attribution 3.0 license (templated.co/license)
-->
<html>
<head>
<title>Generic Page - Industrious by TEMPLATED</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link rel="stylesheet" href="assets/css/main.css" />
</head>
<body class="is-preload">
<!-- Header -->
<header id="header">
<a class="logo" href="index.html">Test</a>
<nav>
Menu
</nav>
</header>
<!-- Nav -->
<nav id="menu">
<ul class="links">
<li>Home</li>
<li>Elements</li>
<li>About me</li>
</ul>
</nav>
<!-- Heading -->
<div id="heading" >
<h1>Contact Us</h1>
</div>
<!-- Main -->
<section id="main" class="wrapper">
<div class="inner">
<div class="content">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name: <input type="text" name="first_name">
<span class="error">* <?php echo $first_nameErr;?></span>
<br>
Last Name: <input type="text" name="last_name">
<span class="error">* <?php echo $last_nameErr;?></span><br>
Email: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea>
<span class="error">* <?php echo $messageErr;?></span><br><br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</div>
</section>
<!-- Footer -->
<footer id="footer">
<div class="inner">
<div class="content">
<section>
<h3>Accumsan montes viverra</h3>
<p>Nunc lacinia ante nunc ac lobortis. Interdum adipiscing gravida odio porttitor sem non mi integer non faucibus ornare mi ut ante amet placerat aliquet. Volutpat eu sed ante lacinia sapien lorem accumsan varius montes viverra nibh in adipiscing. Lorem ipsum dolor vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing sed feugiat eu faucibus. Integer ac sed amet praesent. Nunc lacinia ante nunc ac gravida.</p>
</section>
<section>
<h4>Sem turpis amet semper</h4>
<ul class="alt">
<li>Dolor pulvinar sed etiam.</li>
<li>Etiam vel lorem sed amet.</li>
<li>Felis enim feugiat viverra.</li>
<li>Dolor pulvinar magna etiam.</li>
</ul>
</section>
<section>
<h4>Magna sed ipsum</h4>
<ul class="plain">
<li><i class="icon fa-twitter"> </i>Twitter</li>
<li><i class="icon fa-facebook"> </i>Facebook</li>
<li><i class="icon fa-instagram"> </i>Instagram</li>
<li><i class="icon fa-github"> </i>Github</li>
</ul>
</section>
</div>
<div class="copyright">
© Untitled. Photos Unsplash, Video Coverr.
</div>
</div>
</footer>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>

filter_var returns true only if the provided $email is valid.
To check if the email is invalid, change the if statement of filter_var as following and it should work
//your code
if (!(filter_var($email, FILTER_VALIDATE_EMAIL))) {
$emailErr = "Email is invalid";
}
//your code

Related

php problem with using a get value. works on one part of the page but not the other

im working on my crud skills, but im having some trouble. the first page shows a list of all blog posts, when the user clicks on read more it sends the specific posts id through the url and is recieved by the destination page which uses that id to display the single post/ heres the code for that part. it actually works fine
function display_single_post($title,$author,$date,$image,$content){
$main_page_blog_html = "<h2>
<a href='#'>%s</a>
</h2>
<p class='lead'>
by <a href='index.php'>%s</a>
</p>
<p><span class='glyphicon glyphicon-time'></span> Posted on %s</p>
<hr>
<img class='img-responsive' src='images/%s'>
<hr>
<p>%s</p>
<hr>
<hr>";
printf("{$main_page_blog_html}",$title,$author,$date,$image,$content);
if(isset($_GET["id"])){
$id = $_GET["id"];
$stmt = $connect->link->query("SELECT * FROM posts WHERE post_id = $id");
while($row = $stmt->fetch()){
$post_title = $row["post_title"];
$post_author = $row["post_author"];
$post_date = date('F j, Y \a\t g:ia', strtotime( $row["post_date"] ));
$post_image = $row["post_image"];
$post_content = $row["post_content"];
$id = $row["post_id"];
display_single_post($post_title,$post_author,$post_date,$post_image,$post_content);
}
}
like i said this all works fine. the get value is recieved and loads the post. the problem is when i try to use that $_get id in a query to insert a comment. all this code is on the one page im just showing the php without the html. anyway heres the code to insert the comment
if(isset($_POST["create_comment"])){
global $connect;
$post_id = $_GET["id"];
$comment_author = $_POST["comment_author"];
$author_email = $_POST["author_email"];
$comment_content = $_POST["comment_content"];
$comment_status = "pending";
edit with all the code
<div class="container">
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-8">
<h1 class="page-header">
Page Heading
<small>Secondary Text</small>
</h1>
<!-- First Blog Post -->
<?php
$connect = new db();
if(isset($_POST["create_comment"])){
global $connect;
echo "hello";
$post_id = $_GET["id"];
$comment_author = $_POST["comment_author"];
$author_email = $_POST["author_email"];
$comment_content = $_POST["comment_content"];
$comment_status = "pending";
$sql = "INSERT INTO comments(comment_post_id, comment_author, comment_email, comment_content, comment_status)
VALUES(:a,:b,:c,:d,:e)";
$stmt = $connect->link->prepare($sql);
$stmt->bindvalue(":a",$post_id);
$stmt->bindvalue(":b", $comment_author);
$stmt->bindvalue(":c",$author_email);
$stmt->bindvalue(":d",$comment_content);
$stmt->bindvalue(":e",$comment_status);
$stmt->execute();
}
function display_single_post($title,$author,$date,$image,$content){
$main_page_blog_html = "<h2>
<a href='#'>%s</a>
</h2>
<p class='lead'>
by <a href='index.php'>%s</a>
</p>
<p><span class='glyphicon glyphicon-time'></span> Posted on %s</p>
<hr>
<img class='img-responsive' src='images/%s'>
<hr>
<p>%s</p>
<hr>
<hr>";
printf("{$main_page_blog_html}",$title,$author,$date,$image,$content);
}
if(isset($_GET["id"])){
$id = $_GET["id"];
$stmt = $connect->link->query("SELECT * FROM posts WHERE post_id = $id");
while($row = $stmt->fetch()){
$post_title = $row["post_title"];
$post_author = $row["post_author"];
$post_date = date('F j, Y \a\t g:ia', strtotime( $row["post_date"] ));
$post_image = $row["post_image"];
$post_content = $row["post_content"];
$id = $row["post_id"];
display_single_post($post_title,$post_author,$post_date,$post_image,$post_content);
}
}
?>
<hr>
<!-- Blog Comments -->
<!-- Comments Form -->
<div class="well">
<h4>Leave a Comment:</h4>
<form role="form" method="post" action="post.php">
<div class="form-group">
<input type="text" class="form-control" name="comment_author" placeholder="name">
</div>
<div class="form-group">
<input type="email" class="form-control" name="author_email" placeholder="email">
</div>
<div class="form-group">
<textarea class="form-control" rows="3" name="comment_content"></textarea>
</div>
<button type="submit" name="create_comment" class="btn btn-primary">Submit</button>
</form>
</div>
<hr>
<!-- Posted Comments -->
<!-- Comment -->
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placehold.it/64x64" alt="">
</a>
<div class="media-body">
<h4 class="media-heading">Start Bootstrap
<small>August 25, 2014 at 9:30 PM</small>
</h4>
Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.
</div>
</div>
<!-- Comment -->
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placehold.it/64x64" alt="">
</a>
<div class="media-body">
<h4 class="media-heading">Start Bootstrap
<small>August 25, 2014 at 9:30 PM</small>
</h4>
Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.
<!-- Nested Comment -->
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placehold.it/64x64" alt="">
</a>
<div class="media-body">
<h4 class="media-heading">Nested Start Bootstrap
<small>August 25, 2014 at 9:30 PM</small>
</h4>
Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.
</div>
</div>
<!-- End Nested Comment -->
</div>
</div>
</div>
Based on your code and your comments, I assume the page is called post.php and when you first reach the page it has the id on the url like this: post.php?id=156.
But once you submit the comments' form, since the action for said form it is simply post.php you're losing the id.
You could add the id on the action after post:
<form role="form" method="post" action="post.php?id=<?php echo $id; ?>">
or add a hidden input with the id:
<input type="hidden" name="id" value="<?php echo $id; ?>">
But then you'd have to reach it with $_POST
Another option is to use the SELF for the action like this:
<form role="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
This will retain the id but also any other get variables you may have on the url.
//EDIT
This is a simplification of the probelm which is working, if you visit post.php?id=456 (or any number) and then press Submit, you get the proper response:
<!-- First Blog Post -->
<?php
if(isset($_POST["create_comment"])){
$post_id = $_GET["id"];
echo "The id is: $post_id";
// gets comment and inserts into the db
}
if(isset($_GET["id"])){
$id = $_GET["id"];
// calls display_single_post
}
?>
<!-- Comments Form -->
<div class="well">
<h4>Leave a Comment:</h4>
<form role="form" method="post" action="post.php?id=<?php echo $id; ?>">
<button type="submit" name="create_comment" class="btn btn-primary">Submit</button>
</form>
</div>

Redirect header is not redirecting to the destined page

I am trying to redirect the page using header("location: profile.php") after I click a submit button in the login form, but the page won't redirect. The username and password just gets submitted somewhere.
Here is my main page:
<?php
include ($_SERVER["DOCUMENT_ROOT"]."/example/login.php");
if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>welcome to noteshare</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-theme.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/jquery_popup.css" />
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/npm.js"></script>
<script src="js/jquery_popup.js"></script>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/jquery.leanModal.min.js"></script>
<style>
/* Remove the navbar's default margin-bottom and rounded borders */
.navbar {
margin-bottom: 0;
border-radius: 0;
}
/* Set height of the grid so .sidenav can be 100% (adjust as needed) */
.row.content {height: 450px}
/* Set gray background color and 100% height */
.sidenav {
padding-top: 20px;
background-color: #f1f1f1;
height: 100%;
}
/* Set black background color, white text and some padding */
footer {
background-color: #555;
color: white;
padding: 15px;
}
/* On small screens, set height to 'auto' for sidenav and grid */
#media screen and (max-width: 767px) {
.sidenav {
height: auto;
padding: 15px;
}
.row.content {height:auto;}
}</style>
</head>
<!-- Body Starts Here -->
<body id="body">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Logo</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Projects</li>
<li>Contact</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-log-in"></span>Login</li>
</ul>
</div>
</div>
</nav>
<div class="container-fluid text-center">
<div class="row content">
<div class="col-sm-2 sidenav">
<p>Link</p>
<p>Link</p>
<p>Link</p>
</div>
<div class="col-sm-8 text-left">
<h1>noteshare</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididuntut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint occaecat cupidatat non proident,sunt in culpa qui
officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<hr>
<img src="images/girl_studying.jpg">
</div>
<div class="col-sm-2 sidenav">
<div class="well">
<p>ADS</p>
</div>
<div class="well">
<p>ADS</p>
</div>
</div>
</div>
</div>
<footer class="container-fluid text-center">
<p>Footer Text</p>
</footer>
<div id="abc">
<!-- Popup Div Starts Here -->
<div id="popuplogin">
<!-- Contact Us Form -->
<form action="" id="form" method="post" name="form">
<img id="close" src="images/cross.png" onclick ="div_hide()">
<h2>login form</h2>
<hr id="line">
<input id="username" name="username" placeholder="username" type="text" required>
<input id="password" name="password" placeholder="password" type="password" required>
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
<p> click here to register first</p>
</form>
</div>
<!-- Popup Div Ends Here -->
</div>
<!-- Display Popup Button -->
</body>
<!-- Body Ends Here -->
</html>
and here is the login.php page that contains the header() function call:
<?php
session_start(); // Starting Session
$error=""; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$server="localhost";
$username="root";
$password="";
$database="noteshare";
$conn = new mysqli($server, $username, $password, $database);
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
//$username = mysql_real_escape_string($username);
//$password = mysql_real_escape_string($password);
// Selecting Database
//$db = mysqli_select_db("noteshare", $conn);
// SQL query to fetch information of registerd users and finds user match.
$qry="select * from signin where password='$password' AND username='$username'";
$query = mysqli_query($conn,$qry);
$rows = mysqli_fetch_row($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("Location:http://localhost.com/profile.php", true, 301); exit;// Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysqli_close($conn); // Closing Connection
}
}
?>
function mysqli_fetch_row returns an array or NULL. Therefore
if ($rows == 1)
is never true and you won't reach the redirect with header().
You can use i.e if (is_array($rows)) or if (isset($rows))
You can always insert a var_dump($rows) for debugging to see what the variable $rows looks like.
Note, HTTP code 301 is a permanent redirect. It should be 302. Or simply you can omit the second and third argument of the header() function and it will be a 302.
Did your connection with mysql is ok, then try this,
header('Location:filename');
Eg: header('Location:test1.php');
Try this
header("Location:profile.php"); die();
OR redirect with JS
echo '<script>window.location.href = "profile.php";</script>' ;
You are using an absolute URL. TLD .com is not used when working on a local server.
Change:
header("Location:http://localhost.com/profile.php");
To:
header("Location:http://localhost/profile.php");
It should work!

How do i require user authentication to view dashboard page

On my index page i have my login form for users, then it goes to login.php to handle the login script, from there the users are redirected to dashboardd.php. But i want it to to be so that they have to be logged in to access this page, and not just type in the URL.
Index.php
<?php
session_start();
?>
<?php
if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
echo '<ul style="padding:0; color:red;">';
foreach($_SESSION['ERRMSG_ARR'] as $msg) {
echo '<li>',$msg,'</li>';
}
echo '</ul>';
unset($_SESSION['ERRMSG_ARR']);
}
?>
<!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">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="img/favicon.ico">
<title>Jumbotron Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/style.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Alec Grogan</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<form class="navbar-form navbar-right" role="form" action="login.php" method="POST">
<div class="form-group">
<input type="text" placeholder="Username" name="uname" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="Password" name="pword" class="form-control">
</div>
<button type="submit" class="btn btn-success">Sign in</button>
</form>
</div><!--/.navbar-collapse -->
</div>
</nav>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron">
<div class="container">
<h1>Hello, world!</h1>
<p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p>
</div>
</div>
<div class="container">
<!-- Example row of columns -->
<div class="row">
<div class="col-md-4">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
<div class="col-md-4">
<h2>Heading</h2>
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
<div class="col-md-4">
<h2>Heading</h2>
<p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
</div>
<hr>
<footer>
<p>© Company 2014</p>
</footer>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../dist/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
login.php
<?php
session_start();
$errmsg_arr = array();
$errflag = false;
// configuration
$dbhost = "localhost";
$dbname = "alecgrogan";
$dbuser = "root";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$user = $_POST['uname'];
$password = $_POST['pword'];
if($user == '') {
$errmsg_arr[] = 'You must enter your Username';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'You must enter your Password';
$errflag = true;
}
// query
$result = $conn->prepare("SELECT * FROM users WHERE username= :hjhjhjh AND password= :asas");
$result->bindParam(':hjhjhjh', $user);
$result->bindParam(':asas', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($rows > 0) {
header("location: dashboard.php");
}
else{
$errmsg_arr[] = 'Username and Password are not found';
$errflag = true;
}
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: index.php");
exit();
}
?>
dashboard.php
<?php
echo "string";
?>
Make a $_SESSION e.g. $_SESSION['logged_in'] and fill it with data or set it to true
$username = $_POST['username']; //don't forget to sanitize $_POST values
$userID = (int)$_POST['userID'];
$_SESSION['logged_in'] = array('username' => $username, 'id' => $userID);
OR
$_SESSION['logged_in'] = TRUE;
And then check on the dashboard
if(!isset($_SESSION['logged_in'])){
header('Location:index.php');
}
Now if it does not exists, it will return the user to index.php. Don't forget to use session_start() at the top of every page where you want to call the $_SESSION variables.
You can set an array() in a $_SESSION, so this is ideal for storing user info. Do not store user passwords in a $_SESSION tho.

Show a pages code including require statements

I am trying to display the code of a php file as plain html. This is all going well except for that fact that I would like it to 'open up' the <?php require 'Main_content_bar.php'; ?> statements aswell.
So far I have show_source($page); correctly working.
It currently prints:
<?php require 'Main_content_bar.php'; ?>
<!-- Jumbotron -->
<div class="jumbotron">
<h1>Property</h1>
<p class="lead">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Fusce dapibus, tellus ac cursus
commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet.</p>
</div>
<div class="row">
<div class="col-md-12">
<h2>Current properties</h2>
</div>
</div>
<div class="footer">
<p><a href="Source_code.php" target="_blank"> <img src="Images/codebutton<?php echo $page_lower;?>.jpg" alt="<?php echo $page;?> Source"> </img>
</a></p>
<p>© Robin B'stards Retail 2014</p>
</div>
</body>
</html>
However, as one can see, the contents of the require statements do not show. I cannot for the life of me work out how to do this.
So what it would end up looking like is something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.2/css/bootstrapValidator.min.css"/>-->
<!-- <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.2/js/bootstrapValidator.min.js"></script>-->
<link href="justified-nav.css" rel="stylesheet">
<script>
$(function(){
var url = window.location.href;
var page = url.substr(url.lastIndexOf('/')+1);
$('.nav a[href*="'+page+'"]').parent().addClass('active');
});
</script>
</head>
<body>
<div class="container" style="width: 1263px">
<div class="masthead">
<h3 class="text-muted">Ruthless Real Estate</h3>
<ul class="nav nav-justified">
<li class="menu">Property</li>
<li class="menu">Client</li>
<li class="menu">Type</li>
<li class="menu">Feature</li>
<li class="menu">Multiple Properties</li>
<li class="menu">Property Features</li>
<li class="menu">Images</li>
</ul>
</div>
<!-- Jumbotron -->
<div class="jumbotron">
<h1>Property</h1>
<p class="lead">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Fusce dapibus, tellus ac cursus
commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet.</p>
</div>
<div class="row">
<div class="col-md-12">
<h2>Current properties</h2>
</div>
</div>
<div class="footer">
<p><a href="Source_code.php" target="_blank"> <img src="Images/codebutton<?php echo $page_lower;?>.jpg" alt="<?php echo $page;?> Source"> </img>
</a></p>
<p>© Robin B'stards Retail 2014</p>
</div>
</body>
</html>
Note the lack of require statements
You cannot do that with show_source, which just "show some code sources" of a file.
You need to create your own function which take a filename in argument, then you have to analyze the source like this:
replace all require/include/require_once/include_once (what do I forget?) by their own content
make the function recursive (because Main_content_bar.php can have other include inside it)
Use highlight_string at the end of your function.
EDIT to search & replace, one way (there is several) is to use preg_match_all. That part of the code would look like this :
$new_content = file_get_contents('your-file.php');
$base_path = __DIR__.'/';
// pattern to find require, require_once, include, include_once functions
// and catch their arguments
$pattern = "#<\?php (?:require|include(?:_once)?)\s*'(.*)'; \?>#u";
if (preg_match_all($pattern, $new_content, $matches))
{
foreach($matches[0] as $pattern_index => $full_pattern)
{
$file = $matches[1][$pattern_index];
$subcontent = file_get_contents($base_path.$matches[$pattern_index]);
$new_content = str_replace($new_content, $full_pattern, $subcontent);
}
}
highlight_string($new_content);

Query returning only 1 row instent of all

I'm Stuck on below code... Accroding to my understanding below code should display all the rows data which has been created in my database... But im getting only 1 row data in result only one product on my product page... Please help...
<?php
include 'core/database/connect.php';
include 'core/includes/listhead.php';
$dynamiclist = "";
$sql = mysql_query("SELECT * FROM `index` ORDER BY price1 LIMIT 2");
$hotelcount = mysql_num_rows($sql);
if($hotelcount > 0) {
while($row = mysql_fetch_array($sql)) {
$id = $row['index_id'];
$pic = $row['main_pic'];
$country = $row['country1'];
$destination = $row['destination1'];
$price = $row["price1"];
$dynamiclist = '<div class=/"offset-2/">
<div class="col-md-4 offset-0">
<div class="listitem2">
<img src="'. $pic .'" alt=""/>
<div class="liover"></div>
<a class="fav-icon" href="#"></a>
<a class="book-icon" href="details.html"></a>
</div>
</div>
<div class="col-md-8 offset-0">
<div class="itemlabel3">
<div class="labelright">
<img src="images/filter-rating-5.png" width="60" alt=""/><br/><br/><br/>
<img src="images/user-rating-5.png" width="60" alt=""/><br/>
<span class="size11 grey">18 Reviews</span><br/><br/>
<span class="green size18"><b>'. $price .'</b></span><br/>
<span class="size11 grey">Avg/Night</span><br/><br/><br/>
<form action="http://demo.titanicthemes.com/travel/details.html">
<button class="bookbtn mt1" type="submit">Book</button>
</form>
</div>
<div class="labelleft2">
<b>'. $country .'</b><br/><br/><br/>
<p class="grey">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum nec semper lectus. Suspendisse placerat enim mauris, eget lobortis nisi egestas et.
Donec elementum metus et mi aliquam eleifend. Suspendisse volutpat egestas rhoncus.</p><br/>
<ul class="hotelpreferences">
<li class="icohp-internet"></li>
<li class="icohp-air"></li>
<li class="icohp-pool"></li>
<li class="icohp-childcare"></li>
<li class="icohp-fitness"></li>
<li class="icohp-breakfast"></li>
<li class="icohp-parking"></li>
<li class="icohp-pets"></li>
<li class="icohp-spa"></li>
</ul>
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="offset-2"><hr class="featurette-divider3"></div>';
}
} else {
$dynamiclist = 'We Do Not Have Any Hotel Listed in This City';
}
?>
<?php echo $dynamiclist ?>
<?php include 'core/includes/listfooter.php'; ?>
You have two issues
Your database query is limited to 2 items (although that doesn't explain the 1 item problem you have at the moment)
removing LIMIT 2 will fix this
Secondly
$dynamiclist = '<div class=/"offset-2/">
the "=" sign means that you set it as the content each time.
This is fine except you echo it OUTSIDE your while loop
either echo it within your while loop or change it to
$dynamiclist .= '<div class=/"offset-2/">
notice the .= -> that Adds items to the end of the string.
Hope that helps
Change the
$dynamiclist = '<div class=/"offset-2/">
to
$dynamiclist .= '<div class=/"offset-2/">
If you want to load all rows, remove 'LIMIT' from your query.

Categories