Change language after POST - php

I was following this tutorial to use multiple languages on my site, but i'm trying to switch language after POST, but actually the language switch happens when clicked on POST button twice.
This code is called out in the beginning of page.
<?php
if (!isset($_SESSION['lang'])){
$_SESSION['lang'] = 'ENG';
require "lang/ENG.php";
}
else {
$language = (isset($_SESSION['lang'])) ? $_SESSION['lang'] : "ENG";
switch($language) {
case "EST":
require "lang/EST.php";
break;
case "ENG":
require "lang/ENG.php";
break;
default:
require "lang/ENG.php";
}
}
?>
This code is called out when form is submitted:
if(isset($_POST['selectlang'])){
$lang = $_POST['country'];
//Change language??
}
If i click POST button twice, the language is switched, but not on the first try. What do i need to change?
Edit #2: Adding modified HTML now based on answers:
<?php
include('connection.php');
?>
<?php
if (!isset($_SESSION['lang'])){
$_SESSION['lang'] = 'ENG';
require "lang/ENG.php";
}
else {
$language = (isset($_SESSION['lang'])) ? $_SESSION['lang'] : "ENG";
switch($language) {
case "EST":
require "lang/EST.php";
break;
case "ENG":
require "lang/ENG.php";
break;
default:
require "lang/ENG.php";
}
}
?>
<!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="">
<title><?php echo $lang['reklamatsioon_title'];?></title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/logo-nav.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<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="reklamatsioon.php">
<img src="logo.png" alt="">
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<?php echo $lang['link1'];?>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<form action="" method="post" class="form-horizontal" role="form">
<div class="form-group">
<label for="selector" class="col-sm-3 col-lg-3 control-label">Pick language</label>
<div class="col-sm-9 col-lg-9">
<span id="selector" class="input-group-btn">
<select id="country" name="riik" class="form-control">
<option <?php if($_POST['riik'] == "EST"){ echo "selected='selected'"; }?> value="EST">Eesti</option>
<option <?php if($_POST['riik'] == "ENG"){ echo "selected='selected'"; }?> value="ENG">English</option>
<option <?php if($_POST['riik'] == "FIN"){ echo "selected='selected'"; }?> value="FIN">Suomi</option>
<option <?php if($_POST['riik'] == "SWE"){ echo "selected='selected'"; }?> value="SWE">Rootsi</option>
<option <?php if($_POST['riik'] == "NOR"){ echo "selected='selected'"; }?> value="NOR">Norra</option>
</select>
</span>
<span class="input-group-btn">
<button class="btn btn-primary" name="selectlang" type="submit">Choose language!</button>
</span>
</div>
</div>
</form>
</div>
<?php
if(isset($_POST['selectlang'])){
$lang = $_POST['riik'];
$_SESSION['lang'] = $lang;
//Show code form and terms and conditions url!
echo "<div class='row'>";
echo "<form action='' method='post' class='form-horizontal' role='form'>";
echo "<div class='form-group'>";
echo "<label for='code' class='col-sm-3 control-label'>"."Code"."</label>";
echo "<div class='col-sm-6'>";
echo "<input type='number' id='code' name='code' placeholder='Code' class='form-control' autofocus>";
echo "<span class='help-block'></span>";
echo "</div>";
echo "</div>";
echo "<div class='form-group'>";
echo "<div class='col-sm-6 col-sm-offset-3'>";
echo "<button type='submit' class='btn btn-primary btn-block' name='gobutton'>Continue to form</button>";
echo "</div>";
echo "</div>";
echo "</form>";
echo "</div>";
}
if(isset($_POST["gobutton"])){
$codeVal = $_POST['code'];
$brokenCode = false;
if(strlen($codeVal) < 9){
$codeQuery = mysql_query("SELECT clientNumber FROM client WHERE clientNumber = '$codeVal'",$connection) or die(mysql_error());
if (mysql_num_rows($codeQuery) == 1){
header('location: ankeet.php?code='.$codeVal);
}
else {
$brokenCode = true;
}
}
else {
$brokenCode = true;
}
if ($brokenCode){
echo "<div class='row'>";
echo "<form action='' method='post' class='form-horizontal' role='form'>";
echo "<div class='form-group'>";
echo "<label for='code' class='col-sm-3 control-label'>"."Code"."</label>";
echo "<div class='col-sm-6'>";
echo "<input type='number' id='code' name='code' placeholder='Code' class='form-control' autofocus value='".$codeVal."'>";
echo "<span class='help-block'></span>";
echo "</div>";
echo "</div>";
echo "<div class='alert alert-danger col-sm-6 col-sm-offset-3'>Such code does not exist!</div>";
echo "<div class='form-group'>";
echo "<div class='col-sm-6 col-sm-offset-3'>";
echo "<button type='submit' class='btn btn-primary btn-block' name='gobutton'>Continue to form</button>";
echo "</div>";
echo "</div>";
echo "</form>";
echo "</div>";
}
}
?>
</div>
<!-- /.container -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>

First you need:
if (isset($_POST['country'])) {
$_SESSION['lang'] = $_POST['country'];
}
So the language can be switched.
Then you need to load your settings.
$language = (isset($_SESSION['lang'])) ? $_SESSION['lang'] : "ENG";
switch($language) {
case "DE":
require "lang/de.php";
break;
case "ENG":
default:
require "lang/eng.php";
}
That way nothing, that you dont want can happen
There are several other things you could optimize but for now that should solve your problem.
You should NEVER require or include a file based on a variable that can be set by the website user!
Edit:
I have seen your posted code now: It can not work because you first include your file and switch the session value later on. At that time the file has already been loaded. You need to do things in the correct order, just think of it like that:
1) initialize request
2) make configurations
3) output html code
Edit again:
There are so many bad practices in your code, that i actually dont know where to start.
1) Dont include user input unfiltered in SQL queries, that way you can be attacked by anyone with minimal knowledge. And people will try - believe me. You have to escape values, that are used in sql queries. It would be much better to use parameter binding, please google "php mysql pdo parameter binding"
2) When rendering your options, you should consider using a loop to avoid repeating yourself, please google "DRY dont repeat yourself"
3) you can not send a http header after you printed output already. That does not work due to the nature of the http protocol. First the headers are sent to the browser, followed by the content, basically it looks like:
HeaderLineOne: HeaderValue
HeaderLineTwo: HeaderValue
Content
3) You should really handle the request first and output your code later on. So put your php logic on top of the file (handle input, configure etc) and output your response at the end. That way you can react properly and dont mix up your view with your logic. Basically like:
<?php
// bootstrap application
require_once "connection.php";
require_once "other_include.php";
// configure
$language = "ENG";
if (isset($_SESSION['language'])) {
$language = $_SESSION['language'];
}
// allow user override for language
if (isset($_POST['country'])) {
$language = $_POST['country'];
// make change persistent
$_SESSION['language'] = $language;
}
// include translation labels
switch($language) {
case "DE":
require "lang/de.php";
break;
case "ENG":
default:
require "lang/eng.php";
}
// handle user request
if (isset($_POST['someValue'])) {
// handle user input, make database calls etc
// this is where your logic goes
}
// finally render response
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title><?= $lang['title'] ?></title>
</head>
<body>
<h1><?= $lang['title'] ?>
</body>
</html>

Related

How to add shortcut to single product page in ajax action.php file

I'm making a website for my school and my website is like a laptop store and the main thing in my webpage is a product filter. I have made the product filter, it works great, but the problem is that I added shortcuts that send you to a single product page by clicking one of the products in the product filter. You can click on a product when you just came in the website and haven't messed with the product filter and it sends you to the single product page, but once you search for something using the filter the filtrated product cant be clicked on and you have to refresh the page to select your product. This is happening, because when you come in the website, you see index.php, but once you use the product filter, you are seeing action.php.
here is a part of my code from index.php:
<?php
$sql="SELECT * FROM Laptop";
$result=$conn->query($sql);
if ($result-> num_rows > 0) {
while($row=$result->fetch_assoc()){
$Laptop_ID = $row['Laptop_ID'];
?>
<?php echo "<a href='single_laptop.php?Laptop=" . $Laptop_ID ."'>" ?>
<div class="col-md-3 mb-2" style="color: blue">
<div class="card-deck">
<div class="card boarder-secondary">
<div class="card-img-overlay">
<h6 class="text-light bg-success text-center rounded p-1">
<?= $row['Nosaukums']; ?></h6>
</div>
<br>
<img src="<?= $row['Bilde']; ?>" class="card-img-top">
<div class="card-body">
<p>
Procesors : <?= $row['Procesors']; ?><br>
Videokarte : <?= $row['Videokarte']; ?><br>
RAM : <?= $row['RAM']; ?><br>
</p>
</div>
</div>
</div>
</div>
<?php }
}else {
echo "nav rezultātu";
}?>
</div>
</div>
</div>
And here is my action.php:
<?php
require 'dataB.php';
if(isset($_POST['action'])){
$sql = "SELECT * FROM Laptop WHERE Modelis !=''";
if(isset($_POST['Modelis'])){
$Modelis = implode("','", $_POST['Modelis']);
$sql .="AND Modelis IN('".$Modelis."')";
}
if(isset($_POST['Tips'])){
$Tips = implode("','", $_POST['Tips']);
$sql .="AND Tips IN('".$Tips."')";
}
if(isset($_POST['RAM'])){
$RAM = implode("','", $_POST['RAM']);
$sql .="AND RAM IN('".$RAM."')";
}
if(isset($_POST['Procesors'])){
$Procesors = implode("','", $_POST['Procesors']);
$sql .="AND Procesors IN('".$Procesors."')";
}
if(isset($_POST['Videokarte'])){
$Videokarte = implode("','", $_POST['Videokarte']);
$sql .="AND Videokarte IN('".$Videokarte."')";
}
$result = $conn->query($sql);
$output='';
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$output .='
<div class="col-md-3 mb-2" style="color: blue">
<div class="card-deck">
<div class="card boarder-secondary">
<div class="card-img-overlay">
<h6 class="text-light bg-success text-center rounded p-1">
'.$row['Nosaukums'].'</h6>
</div>
<br>
<img src="'.$row['Bilde'].'" class="card-img-top">
<div class="card-body">
<p>
Procesors : '.$row['Procesors'].'<br>
Videokarte : '.$row['Videokarte'].'<br>
RAM : '.$row['RAM'].'<br>
</p>
</div>
</div>
</div>
</div>';
}
} else {
$output = "<h3>No Products Found!<h3>";
}
echo $output;
}
?>
I need to figure out how to properly put the code from index.php, where it makes it possible to redirect me to single.laptop.php, to action.php, so I can redirect to single_laptop.php with no problems using the product filter.
$(document).keydown(function(e){
var keycode=e.keyCode;
if (keycode == 27)
{
$("#change").trigger('click');
}
});
$("#change").click(function() {
//do what you need
if($("#radio:checked").length==0)
{
alert("abc");
return false;
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#3.3.7/dist/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#3.3.7/dist/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
Press ESC
</body>
</html>

Unknown issue with $_SERVER["REQUEST_METHOD"] returning false when it should be true

Hey there stackoverflow users, i have come upon a very confusing problem that I cant seem to move past. I am creating a forum type web page and am currently working on the comments section. I have a form that uses the post method to send your comment as well as a hidden input to store the threads ID. I will post the entire php file below just to make sure nothing is left out.
<?php
session_start();
parse_str($_SERVER['QUERY_STRING'], $link);
$threadID = $link['ID'];
require("config.php");
$connection = mysqli_connect($host, $user, $password, $database);
$error = mysqli_connect_error();
if($error != null) {
$output = "<p>Unable to connect to database!</p>";
exit($output);
} else {
//Get Thread Data
$query = "SELECT username, title, content FROM threads, users WHERE threads.ID = $threadID AND users.ID = threads.makerID;";
$results = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($results);
//Get Comment Data
$query = "SELECT username, comment FROM comments, users WHERE threadID = $threadID AND users.ID = comments.makerID;";
$results = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($results);
}
?>
<!DOCTYPE html>
<html>
<head lang="en">
<title>BodyweightMate</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/styling.css"/>
</head>
<body>
<!--Top masthead-->
<header class="masthead" id="top">
<h1 class="masthead-title"> Welcome To BodyweightMate </h1>
</header>
<!--Navigation bar-->
<nav class="navbar">
<table class="navbar-table">
<tr>
<!--Logo-->
<td>
<a class="navbar-brand" href="main.php">
<img src="../images/logo.jpg" alt="BodyweightMate" height="30" width="30">
</a>
</td>
<!--Login/Profile-->
<?php if(isset($_SESSION['login_user'])) {
echo"<td><a class=\"navbar-profile\" href=\"profile.php\"> Profile </a></td>";
echo"<td><a class=\"navbar-logout\" href=\"logout.php\"> Logout </a></td>";
} else {
echo"<td><a class=\"navbar-login\" href=\"login.php\"> Login </a></td>";
}?>
</tr>
</table>
</nav>
<!--Main portion-->
<section class="content-section">
<article>
<h3><?php echo $row['username']. ": " .$row['title']; ?></h3>
<p><?php echo $row['content']; ?></p>
<br>
<h3>Comments</h3>
<p>Some annoying user: Gr8 B8 M8</p>
<p>Annoying users friend: I R8 8/8</p>
</article>
<div>
<!--If logged in, ability to comment-->
<?php if(isset($_SESSION['login_user'])): ?>
<form role="comment-form" method="POST" action="processcomment.php" id="mainForm">
<input type="hidden" value="$threadID" name="threadID">
<div class="form-group">
<label for="comment">Comment </label> <br>
<textarea class="comment-text" name="comment" rows="2" maxlength="255"></textarea>
</div> <br>
<input type="Submit" class="btn-newcomment" value="Submit Comment" name="submit">
</form>
<?php endif ?>
</div>
</section>
<!--Right portion-->
<aside class="content-aside">
<div>
<!--If logged in, be able to create a thread-->
<?php
if(isset($_SESSION['login_user'])) {
echo"<form method=\"post\" action=\"makethread.php\">";
echo"<input type=\"submit\" class=\"btn-newthread\" value=\"Create New Thread\" name=\"submit\">";
echo"</form>";
}
?>
</div>
<!--Info-->
<div>
<p> GOING TO NEED A SEARCH FUNCTION HERE
This is the cool little aside section. It will always be there to provide you with some very nice little details, helpful links, maybe a list of moderators? who knows! The uses are endless when you have a beautiful little aside like this one! Here are a few very useful bodyweight fitness links to get us started :D </p>
</div>
<br>
<div>
<ul class="content-aside-links">
<li>
Reddit's Bodyweightfitness Forum
</li>
<li>
Reddit's Bodyweightfitness RR
</li>
<li>
Antranik's Bodyweightfitness Routine
</li>
</ul>
</div>
<div></div>
</aside>
<!--Footer -->
<footer class="footer">
<div>
<p> Use of this site constitutes acceptance of our User Agreement © 2017 BodyweightMate inc. All rights reserved. </p>
</div>
</footer>
</body>
</html>
The error is occurring under the main portion where i check if a user is logged in, and if they are add a short form consisting of a message, a text area, and a submit button. This form sends the information to the following php file.
<?php
session_start();
if(!isset($_SESSION['login_user'])) { header("location: main.php"); }
?>
<!DOCTYPE html>
<html>
<body>
<?php
require("config.php");
$connection = mysqli_connect($host, $user, $password, $database);
$error = mysqli_connect_error();
if($error != null) {
$output = "<p>Unable to connect to database!</p>";
exit($output);
} else {
//Validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$comment = $_POST['comment'];
$threadID = $_POST['threadID'];
$user = $_SESSION['login_user'];
} else {
//Redirect back to register
echo"<p>Form must use post or input was bypassed.</p>";
echo" Return to home page. ";
mysqli_close($connection);
exit();
}
There is no issue with connecting to the database, and I don't believe the remainder of the code is necessary to help me with this error since that one if statement of checking if the form is using post is failing and the else statement is always called. Why is this? i have rewritten the form multiple times ensuring that its properly structured and using post yet it fails every time!

Redirecting to PHP file in Flask

I am running a localhost website using Flask and python. I have some php files that I want to run when the users click a button. Problem is that Flask isn't recognizing the PHP file as PHP code and the code is showing up as text on the webpage. It's showing the text of all the echo statements, but the words in those statements correspond to variable in the code that allow the user to login and logout of the website. What do I do?
Python Code:
#app.route('/example.php')
def phpexample():
return render_template('example.php')
This shows a html page with text resulting from the echo statements.
The PHP code (example.php):
<?php
require ('steamauth/steamauth.php');
?>
<html>
<head>
<title>Eliminate Phishers! Join Steap now</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<!--[if lte IE 8]><script src="css/ie/html5shiv.js"></script><![endif]-->
<script src="js/jquery.min.js"></script>
<script src="js/skel.min.js"></script>
<script src="js/init.js"></script>
<noscript>
<link rel="stylesheet" href="css/skel.css" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/style-wide.css" />
</noscript>
<!--[if lte IE 8]><link rel="stylesheet" href="css/ie/v8.css" /><![endif]-->
</head>
<body>
<!-- Header -->
<div id="header">
<span class="logo icon fa-paper-plane-o"></span>
<h1>Welcome. This is Steap</h1>
<p>A website designed to help eliminate phishers
<br />
and hackers on Steam.</p>
</div>
<!-- Main -->
<div id="main">
<header class="major container small">
<h3>
<?php
if(!isset($_SESSION['steamid'])) {
echo "welcome guest! <br />\n please login ";
steamlogin(); //login button
} else {
include ('steamauth/userInfo.php');
$url = $steamprofile['profileurl'];
if ($steamprofile['personastate'] == 0) {
$state = '<span style="color:#616161";>(Offline)</span>';
$picture = '<span style="color:#616161";><img src="'.$steamprofile['avatarfull'].'" title = "" alt = ""></span>';
} else if ($steamprofile['personastate'] == 1) {
$state = '<span style="color:#006EFF";>(Online)</span>';
$picture = '<span style="border: 10px dotted #006EFF;"><img src="'.$steamprofile['avatarfull'].'" title = "" alt = ""></span>';
} else if ($steamprofile['personastate'] == 2) {
$state = '<span style="color:#006EFF";>(Busy)</span>';
$picture = '<span style="border-color:#006EFF border-style: solid";><img src="'.$steamprofile['avatarfull'].'" title = "" alt = ""></span>';
} else if ($steamprofile['personastate'] == 3) {
$state = '<span style="color:#006EFF";>(Away)</span>';
$picture = '<span style="border-color:#006EFF border-style: solid";><img src="'.$steamprofile['avatarfull'].'" title = "" alt = ""></span>';
} else if ($steamprofile['personastate'] == 4) {
$state = '<span style="color:#006EFF";>(Snooze)</span>';
$picture = '<span style="border-color:#006EFF border-style: solid";><img src="'.$steamprofile['avatarfull'].'" title = "" alt = ""></span>';
} else if ($steamprofile['personastate'] == 5) {
$state = '<span style="color:#006EFF";>(Looking to Trade)</span>';
$picture = '<span style="border-color:#006EFF border-style: solid";><img src="'.$steamprofile['avatarfull'].'" title = "" alt = ""></span>';
} else if ($steamprofile['personastate'] == 6) {
$state = '<span style="color:#006EFF";>(Looking to Play)</span>';
$picture = '<span style="border-color:#006EFF border-style: solid";><img src="'.$steamprofile['avatarfull'].'" title = "" alt = ""></span>';
}
//Protected content
echo "Welcome back" . "</br> </br>" . $picture ."</br>". $steamprofile['personaname'] . "</br>" .$state . "</br>". "Steam ID: ". $steamprofile['steamid'] . "</br>";
echo 'Steam Profile' . "</br> </br>" . "<form action=\"steamauth/logout.php\" method=\"post\"><input value=\"Logout\" type=\"submit\" /></form>"; // Display their avatar!
}
?>
</h3>
</header>
<footer class="major container small">
<ul class="actions">
<li>Get Phishers</li>
</ul>
</footer>
</div>
<!-- Footer -->
<div id="footer">
<div class="container small">
<header class="major last">
<h2>Questions or comments?</h2>
</header>
<p>Program not working? Not detecting the phishers properly? <br \> Send us a message. We'll be sure to back to you as soon as possible.</p>
<form method="post" action="#">
<div class="row collapse-at-2">
<div class="6u">
<input type="text" name="name" placeholder="Name" />
</div>
<div class="6u">
<input type="email" name="email" placeholder="Email" />
</div>
</div>
<div class="row">
<div class="12u">
<textarea name="message" placeholder="Message" rows="6"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" value="Send Message" /></li>
</ul>
</div>
</div>
</form>
<ul class="icons">
<li><span class="label">Twitter</span></li>
<li><span class="label">Facebook</span></li>
<li><span class="label">Instagram</span></li>
<li><span class="label">Github</span></li>
<li><span class="label">Dribbble</span></li>
</ul>
<ul class="copyright">
<li>© Steap 2014 All rights reserved.</li><li>Design: HTML5 UP</li>
</ul>
</div>
</div>
</body>
</html>
Maybe you should run php server (such as Apache or another) on other port (such as 8080) and when you call any php file, make request from your flask server to php server. And result getting from php server show with flask server. I hope, you can find the way how to send request from flask to other server.
render_template() isn't support PHP.
You can use subprocess to run PHP script:
import subprocess as sp
#app.route('/example.php')
def phpexample():
out = sp.run(["php", "example.php"], stdout=sp.PIPE)
return out.stdout
Flask is not compatible with php. So it can't read php code.
Have you considered using JQuery Ajax?
Here's an example:
You have a file called get_name.php witch contains:
<?php echo "Hello, my name is John"; ?>
Using Jquery ajax function I call the get_name.php
$.ajax({
url : 'get_name.php',
success : function(data) {
console.log(data);
}
});
The output in the console would be:
Hello, my name is John
So, with the returned data you can do whatever you want.

Can't get login feature to work

I'm currently learning PHP and am creating a small CMS feature that includes a login area. I have used the code below which includes an include header file that contains the doctype/head info and the opening tag. It also includes the header content. I also have a connection file for connecting to the db.
My header include code is:
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title><?php echo $pagetitle ?></title>
<link rel="stylesheet" href="../stylesheets/foundation.css">
<link rel="stylesheet" href="../stylesheets/app.css">
<style>#import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800); #import url (http://fonts.googleapis.com/css?family=Kreon:100,200,300,400);</style>
<script src="../javascripts/modernizr.foundation.js"></script>
</head>
<body>
<div class="subHeader">
<div class="row">
<div class="four columns logo">
<img src="../images/logo.png" alt="logo" />
</div>
<div class="eight columns navigation right">
<ul class="navigationMain">
<li class="<?php if($navcurrent == "home"){echo "navigationActive";} ?>">Home</li>
<li class="<?php if($navcurrent == "services"){echo "navigationActive";} ?>">Services</li>
<li class="<?php if($navcurrent == "work"){echo "navigationActive";} ?>">Recent Work</li>
<li class="<?php if($navcurrent == "about"){echo "navigationActive";} ?>">About</li>
<li class="<?php if($navcurrent == "contact"){echo "navigationActive";} ?>">Contact</li>
</ul>
</div>
<div class="twelve columns titlesection">
<h2><?php echo $headTitle ?></h2>
<h4><?php echo $headsubTitle ?></h4>
</div>
</div><!--End Feature Row-->
</div><!--End Feature-->
<div class="underbar">
<div class="bordertriangle"></div>
<div class="row">
<div class="eight columns"> </div>
<div class="three columns right socialcontainer">
<ul class="socialicons">
<li><a><img id="linkedinIcon" src="../images/socialli.png" alt="linkedin icon" /></a></li>
<li><a><img id="twitterIcon" src="../images/socialtw.png" alt="twitter icon" /></a></li>
<li><a><img id="facebookIcon" src="../images/socialfb.png" alt="facebook icon" /></a></li>
</ul>
</div>
</div>
When I open the admin page, the username password form, header and footer appear as they should. If I test the errors, they return as they should. However, when I successfully log in using a valid username and password, no content appears except the what is included in the header file. Can anyone point me in the direction of what i might be doing wrong? Any help would be much appreciated. I am a relative noob to PHP...
<?php
$pagetitle = "Admin";
$navcurrent = "home";
$headTitle = "ADMIN AREA";
$headsubTitle = "SITE ADMINISTRATION AREA";
include_once('../includes/connection.php');
include_once('../includes/headeradmin.php');
if (isset($_SESSION['logged_in'])) {
echo('Successfully Logged In');
} else {
if (isset($_POST['username'], $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)){
$error = 'An Error Has Occurred - All Fields Are Required';
}
else{
$query = $pdo->prepare('SELECT * FROM users WHERE user_name = ? AND user_password = ?');
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('location: index.php');
exit();
}
else{
$error = 'The username/password you entered was incorrect - Please try again';
}
}
}
?>
<div class="row">
<div class="four columns centered">
<?php if (isset($error)) { ?>
<h5 style="color: #e63333;"><?php echo $error; ?></h5>
<br />
<br />
<?php } ?>
<form action="index.php" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>
</div>
</div>
You can't use the header('location: index.php'); line if you've already output content (i.e - html code) to the browser when you included the header in this line include_once('../includes/headeradmin.php');
read the documentation of header - Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP
you need to redirect the user with the header() function before you output the head html of the admin page

How do I add a class of current to my navigational list items and links?

I've tried a few different ways to add a class of current on my navigation.
I read an article on doing so at: http://alistapart.com/article/keepingcurrent
So far I'm having no luck incorporating any of the ways into my site.
I feel like I'm missing something.
I pull my navigation into the site with an includes file called nav.php:
<div id="nav">
<div id="nav-container">
<ul id="nav-content" class="top menu">
<li<?php if ($thisPage=="home")
echo " id=\"currentpage\""; ?>>
Home</li>
<li<?php if ($thisPage=="portfolio")
echo " id=\"currentpage\""; ?>>
Portfolio</li>
<li<?php if ($thisPage=="services")
echo " id=\"currentpage\""; ?>>
Services</li>
<li<?php if ($thisPage=="resources")
echo " id=\"currentpage\""; ?>>
Resources</li>
<li<?php if ($thisPage=="blog")
echo " id=\"currentpage\""; ?>>
Blog</li>
<li<?php if ($thisPage=="contact")
echo " id=\"currentpage\""; ?>>
Contact</li>
</ul>
</div>
</div>
This is what I have in the body of the index page:
<?php $thisPage="home"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Kristine Morical : Home</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="Kristine Morical" />
<?php include('http://www.kristinemorical.com/includes/head.php'); ?>
</head>
<body id="body">
<?php include('http://www.kristinemorical.com/includes/header.php'); ?>
<?php include('http://www.kristinemorical.com/includes/nav.php'); ?>
<div id="outer" class="clearfix">
<div id="sidebar-wrapper">
<?php //include('http://www.kristinemorical.com/includes/sidebar.php'); ?>
</div>
<div id="content" role="main">
</div> <!-- end #main -->
</div> <!-- end #outer -->
<?php include('http://www.kristinemorical.com/includes/footer.php'); ?>
</body>
</html>
I'm not sure what I'm doing wrong.
First, you can use the ternary condition for cleaner code, and second, use a css class for easier styling (which would allow multiple, if you add other navigation elements):
<li<?= ($thisPage=="services" ? ' class="currentPage"' : '') ?>>
Services
</li>
It can get tedious too to always set $thisPage, so you could go step further and have PHP try to figure it out based on the current request uri.
If you have problems where the class is never printing when it should, then do a var_dump or something on $thisPage to make sure it's being set properly.
Try this:
<div id="nav">
<div id="nav-container">
<ul id="nav-content" class="top menu">
<?php if ($thisPage=="home") echo "<li id=\"currentpage\">"; else echo "<li>";?>
Home</li>
<?php if ($thisPage=="portfolio") echo "<li id=\"currentpage\">"; else echo "<li>";?>
Portfolio</li>
<?php if ($thisPage=="services") echo "<li id=\"currentpage\">"; else echo "<li>";?>
Services</li>
<?php if ($thisPage=="resources") echo "<li id=\"currentpage\">"; else echo "<li>";?>
Resources</li>
<?php if ($thisPage=="blog") echo "<li id=\"currentpage\">"; else echo "<li>";?>
Blog</li>
<?php if ($thisPage=="contact") echo "<li id=\"currentpage\">"; else echo "<li>";?>
Contact</li>
</ul>
</div>
</div>
That will work if you're using ID tags but if you really want to use a class, then you should be using class tags instead. It depends on how you're declaring the class in your head tags of your webpage or in your css file. If you're declaring the class with the # sign then the above code will work but it's not the best practice. You would want to declare the class with a period sign instead and then use class tags in your webpage.

Categories