JavaScript and PHP sessions - javascript

My login.php looks like:
if ($count == 1){
$_SESSION['username'] = "1";
if (isset($_SESSION['username'])){
ob_start();
$url = 'main.php';
while (ob_get_status())
{
ob_end_clean();
}
header( "Location: $url" );
}
}
else {
$_SESSION['username']='';
}
and when I succesfully log in, main.php redirects me to login.php instead of running the game loop.
<?php
if(!(isset($_SESSION['username']) && $_SESSION['username']!='')) {
echo "<script>window.location.href=\"login.php\"</script>";
}
else {
echo "<script defer>reload();</script>";
}
?>
Thank you.

try instead
<?php
session_start();
if(empty($_SESSION['username'])) {
echo "<script>window.location.href=\"login.php\"</script>";
}
else {
echo "<script defer>reload();</script>";
}
Emptychecks
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
or do $_SESSION['username']=='' check.

I think your main php code should change like this..
<?php
if(!(isset($_SESSION['username']) && $_SESSION['username']=='')) {
echo "<script>window.location.href=\"login.php\"</script>";
}
else {
echo "<script defer>reload();</script>";
}
?>
here you are checking $_SESSION['username']!=''
Need to change that to..
if(!(isset($_SESSION['username']) && $_SESSION['username']==''))

Related

How can I change css from php side?

Basically, I want to add an additional class when a certain IF condition is met.
<?php
if($type == 'NEW')
{
$('#'+day+s).addClass('new');
}
if($type == 'USED')
{
$('#'+day+s).addClass('used');
}
?>
You would need to do it through JavaScript / jQuery inside of a PHP conditional.
You can either close your PHP tags while leaving the conditional open:
<?php
if($type == 'NEW')
{
?>
<script>$('#'+day+s).addClass('new');</script>
<?php
}
if($type == 'USED')
{
?>
<script>$('#'+day+s).addClass('used');</script>
<?php
}
?>
Or echo() out the <script> tags from within PHP:
<?php
if($type == 'NEW')
{
echo "<script>$('#'+day+s).addClass('new');</script>";
}
if($type == 'USED')
{
echo "<script>$('#'+day+s).addClass('used');</script>";
}
?>
Having said that, you'd be better off simply altering your logic to output classes based on your conditionals. That way you would simply need to add a regular CSS rule for each class. The right rule would be selected based on which class was outputted.
It should be directly in your HTML :
<div class="<?php if ($type == 'NEW') echo 'new';?>"></div>
You have to assign your calss name in a variable and simply give that to your corresponding MHTL.
<?php
if($type == 'NEW')
{
$style = "class_name for if"; //eg:- new
}
if($type == 'USED')
{
$style = "class_name for else"; //eg:- used
}
?>
//html element
for eg:
<p id="days" class="<?php echo $style;?>"></p>
several ways to do that and depends also in your code
<!-- Assignment inline -->
<div class="<?= $type === 'NEW' ? 'newClass' : 'usedClass'?>"></div>
<!-- Assignment previous -->
<?php
$class = 'defaultClass';
if ($type === 'NEW') { $class = 'newClass'; }
if ($type === 'USED') { $class = 'usedClass'; }
?>
<div class="<?=$class?>"></div>
<!-- Assignment in script -->
<?php $class = $type === 'NEW' ? 'newClass' : 'usedClass'; ?>
<script>
$(document).ready(function(){
$('#'+day+s).addClass('<?= $class ?>');
});
</script>
You can put the if condition of PHP inside class attribute directly. No need to do any method or js for this. You can use the logic as below:
<div class="<?php if($type == 'NEW'){ echo 'new';} else if($type == 'USED'){ echo 'used'; } ?>"></div>

Taking data from HTML/JavaScript with PHP and adding to empty txt file

I am trying to take information taken from a HTML/JavaScript file and I want to add the data ($email = string, $vote = value from radio button) to an empty txt file using php.
What's wrong with my code? I don't think the foreach loop is being run. Thanks!
<?php
$email = $_REQUEST['email'];
$vote = $_REQUEST['player'];
$emailList = file('email.txt');
$voteList = file('votes.txt');
foreach ($emailList as $line => $value) {
if (is_null($value)) {
file_put_contents("email.txt", $email."<br>", FILE_APPEND);
} else if ($value == $email) {
echo "You have already voted!";
} else {
file_put_contents("email.txt", $email."<br>", FILE_APPEND);
echo "Your vote has been stored! Thanks.";
}
}
?>
$foundMail = false;
foreach($emailList as $line => $value){
if(trim(preg_replace('/\n/', '',$value)) == trim($email)) {
$foundMail = true;
}
}
if(!$foundMail) {
file_put_content("email.txt", $email."\n", FILE_APPEND);
echo ('your vote has been stored');
} else {
echo 'you have allready voted';
}

How to display username on home page only after login?

//header.php
<?php
session_start();
if(isset($_SESSION['loggedin']))
$_SESSION['displayname']="notset";
else
$_SESSION['loggedin']=0;
?>
//index.php
<?php
require "header.php";
if($_SESSION['loggedin']==1) //ignores the if statement
{
echo "Welcome".$_SESSION['displayname']."!";
echo "<button id='logout_button'>
<a href='logout.php'>Logout</a>
}
else
{
echo '<a id="display_name" href="login.html">Login/ Signup</a>';
}
?>
//verify.php
<?php
session_start();
include "connect.php";
$uname=$_POST['uname'];
$pass=$_POST['pass'];
$check=mysqli_query($conn,"SELECT * FROM member_list WHERE username='$uname'");
$numrows=mysqli_num_rows($check);
if ($numrows == 1)
{
$row = mysqli_fetch_array($check);
$dbusername = $row['username'];
$dbpassword = $row['password'];
if( $uname == $dbusername && $pass == $dbpassword )
{
$_SESSION['loggedin']=1;
$_SESSION['displayname'] = $uname;
header("location:index.php");
}
else
{
$msg="Invalid Password !!";
echo "<script type='text/javascript'>alert('$msg');
window.location.replace('loggedin.html')</script>";
}
}
else
{
$msg="Invalid Username !!";
echo "<script type='text/javascript'>alert('$msg');
window.location.replace('index.html')</script>";
}
?>
This is my code. There is no error. But when I login it does not display the username. It ignores the if statement on index.php and goes straight to the else statement.
try this to debug your apps
index.php
<?php
//start header.php
ob_start();
session_start();
$_SESSION['loggedin'] = (isset($_SESSION['loggedin'])) ? $_SESSION['loggedin'] : 0;
if($_SESSION['loggedin']==1)
$_SESSION['displayname']="admin";
else
$_SESSION['displayname']="guest";
//end header.php
if($_SESSION['loggedin']==1)
{
echo $_SESSION['displayname'];
echo "<a href='logout.php'>Logout</a>";
}
else
{
echo $_SESSION['displayname'];
echo "<a href='login.php'>Login</a>";
}
?>
login.php
<?php
ob_start();
session_start();
$_SESSION['loggedin']=1;
echo "try login....";
sleep(1);
header( 'Location: index.php' ) ;
?>
logout.php
<?php
ob_start();
session_start();
$_SESSION=NULL;
session_destroy();
echo "try logout....";
sleep(1);
header( 'Location: index.php' ) ;
?>
let me know this script work or not

PHP echo is printing JavaScript alert code on page

I was making a form for inserting products for admin in an e-commerce project. During validation of the form data, I tried to check if the form data is empty or not.
Thus I introduced an if statement and checked the values of all the parameters passed from the form and in the if block wrote an echo statement.
Here is my code:
<? php
//text variables
if(isset($_POST['insert_product'])){
$product_title = $_POST['product_title'];
$product_cat = $_POST['product_cat'];
$product_brand = $_POST['product_brand'];
$product_price = $_POST['product_price'];
$product_desc = $_POST['product_desc'];
$product_status = 'on';
$product_keywords = $_POST['product_keywords'];
//images variables
$product_img1 = $FILES['product_img1']['name'];
$product_img2 = $FILES['product_img2']['name'];
$product_img3 = $FILES['product_img3']['name'];
//temp names
$temp_name1 = $FILES['product_img1']['tmp_name'];
$temp_name2 = $FILES['product_img2']['tmp_name'];
$temp_name3 = $FILES['product_img3']['tmp_name'];
//validation and insertion query
if($product_title == '' OR $product_cat == '' OR $product_brand == '' OR $product_keywords == '' OR $product_img1 == '' OR $product_price == ''){
echo"<script>alert('you have not entered all the values')</script>";
exit();
}
}
?>
It is producing an output like
(...alert('you have not entered all the values');"; exit();} } ....)
Please help me to solve this problem.
I am using Sublime text and checked the same in Notepad++ but it’s giving the same error.
This works fine for me. Try iterating through $_POST in a loop, checking values that way. It'll condense your code and make things easier to read in the future:
<?php
if (isset($_POST)) {
foreach ($_POST as $key => $value) {
if (!isset($_POST[$key]) || $value == "") {
echo "<script> alert('you have not entered all the values'); </script>";
exit;
}
}
}
That said, you should try to preserve $_POST and use a cleaned string if you're using data provided by the user:
<?php
if (isset($_POST)) {
// Clean a string, making it safe for using with a database.
function clean_string($string) {
global $mysqli;
$string = $mysqli->real_escape_string($string);
stripslashes($string);
return $string;
}
foreach ($_POST as $key => $value) {
if (!isset($_POST) || $value == "") {
echo "<script> alert('you have not entered all the values'); </script>";
exit;
}
// If you're going to be using this $_POST data with a database you should also
// clean the strings before using them in any way.
$Data = new stdClass();
foreach ($_POST as $key => $value) {
if (isset($_POST[$key]) && $_POST[$key] !== "") {
$Data->$key = clean_string($value);
}
}
}
// All of the $_POSTed items are set and cleaned for use. Do what you will with them below.
}
try the following, *note semicolon
echo "<script language='javascript'>alert('thanks!');</script>";
echo"<script>alert('you have not entered all the values');</script>";
use this .....u r forgetting semicon after )

PHP variable with a value of string is not equal in PHP variable with a value of html id from javascript?

This is my example code
<script>
var item = "yooow";
jQuery("#view").html(item);
</script>
<?php $str_html = '<p id="view"></p>';
echo $str_html; //it will output "yooow"
?>
but...
when i'm trying to compare this into another php variable
<?php $str_php ="yooow";
if($str_html == $str_php)
{
echo "true";
}
else
{
echo "false";
}
?>
but it returns to false
how can they be an equal?
PHP is run serverside which means it's not aware of any changes you make in the DOM using Javascript.
<script>
var item = "yooow";
Value set only in clinet side, PHP don't know about changes here
jQuery("#view").html(item);
</script>
<?php $str_html = '<p id="view"></p>';
WRONG, it will output "<p id="view"></p>"
echo $str_html; //it will output "yooow" ?>
<?php $str_php ="yooow";
Comparing "<p id="view"></p>" and "yoow" and that is not equal!
if($str_html == $str_php)
Better, you give the item value in cookie/session. And, compare the cookie value with $str_php.
<?php session_start(); ?>
<script>
$(document).ready(function(){
var item = "<?php echo $_SESSION['html']="yooow"; ?>";
$("#view").html(item);
});
</script>
<?php
$str_html = '<p id="view"></p>';
$strHtml=$_SESSION['html'];
$str_php ="yooow";
if($strHtml == $str_php)
{
echo "true";
}
else
{
echo "false";
}
?>

Categories