PHP Session Not Changing in Server but works in Localhost - php

I wrote a simple login form website with change language in PHP.
When I run in localhost, I can login after I fill in the registration number and password. I can also change the language to Chinese/English after I click on the hyperlink.
However, after I deploy the PHP files to server, the functions are not working.
After I click on the English hyperlink, the login page will not change to English and remains as the default language (Chinese).
The login form is not working also, I have to click on the any of the Chinese/English hyperlink and fill in the login form, then I can login to the dashboard.
After login, the dashboard language will show in the language I selected in the index.php. I have no idea on why the index.php will not change to the language I wanted. It is working fine in localhost.
Below are the codes. I appreciate if anyone can advise me on this.
Thanks a lot.
index.php
<?php
session_start();
include 'includes/language.php';
?>
<html>
<div class="container2" style="justify-content: center;">
<a href="change-Language.php?language=en">
<?php echo getLanguage($resultAll, 'nav-english'); ?>
</a> |
<a href="change-Language.php?language=zh">
<?php echo getLanguage($resultAll, 'nav-chinese'); ?>
</a>
</div>
<div class="container">
<label for="regno">
<b><?php echo getLanguage($resultAll, 'nav-regno'); ?></b>
</label>
<input type="text" placeholder="<?php echo getLanguage($resultAll, 'nav-regno'); ?>" name="regno">
<label for="psw">
<b><?php echo getLanguage($resultAll, 'nav-password'); ?></b>
</label>
<input type="password" placeholder="<?php echo getLanguage($resultAll, 'nav-password'); ?>" name="password">
<button type="submit">
<?php echo getLanguage($resultAll, 'nav-login'); ?>
</button>
</div>
</html>
includes/language.php
<?php
if (!isset($_SESSION['language']))
{
$_SESSION['language'] = "zh";
}
if ( isset($_SESSION['language']) && $_SESSION['language'] == "en")
{
$query = $pdo->prepare("SELECT message_code, message_en as msg FROM tbl_language");
}
if ( isset($_SESSION['language']) && $_SESSION['language'] == "zh")
{
$query = $pdo->prepare("SELECT message_code, message_zh as msg FROM tbl_language");
}
$results = $query->execute();
$resultAll = $query->fetchAll(\PDO::FETCH_ASSOC);
function getLanguage($resultAll, $key)
{
foreach ($resultAll as $row)
{
if ($row['message_code'] == $key)
{
echo $row['msg'];
}
}
}
?>
change-Language.php
<?php
session_start();
$language = $_GET['language'];
$_SESSION['language'] = $language;
$referer = $_SERVER['HTTP_REFERER'];
header("Location: $referer");
?>

Related

issue on updating data in php mysql

I was trying to create an update system , but I don't know why my code is not working . My code are :
<?php
include "dbconnection.php";
if(isset($_POST['submit'])){
$residency_status = $_POST['residency_status'];
$query="UPDATE profile SET
residential_status='$residency_status'
WHERE id = '".user_id."'
";
}
header('location:profile.php');
?>
I am adding some Code from profile.php page :
<?php
session_start();
include_once ('dbconnection.php');
if(!isset($_SESSION['logged_in'])){
header("Location: login.php");
die();
}
$usrname=$_SESSION['username'];
$pasword=$_SESSION['password'];
$user_id= get_user_id($usrname, $pasword);
while($us_id= $user_id->fetch_assoc()) :
$collected_id=$us_id['id'];
$resi_status=$us_id['residential_status'];
endwhile;
?>
The code for the form is : I am trying to keep the code short to avoid
<form class="form-group row" action="get_update.php" method="POST"
enctype="multipart/form-data">
<h4>Residential Status </h4>
<div class="form-group">
<input type="radio" name="residency_status" value="yes" class=""
id=""
<?php
if ($resi_status == "yes") { ?> checked <?php }
?>
>yes
<input type="radio" name="residency_status" value="No" class="" id=""
<?php
if ($resi_status == "no" || $resi_status == "") { ?> checked
<?php } ?> >no
</div>
<br>
Thank you .
You are missing out on mysqli_query.Your code should be as
<?php
include "dbconnection.php";
if(isset($_POST['submit'])){
$residency_status = $_POST['residency_status'];
$query="UPDATE profile SET
residential_status='$residency_status'
WHERE id = '".user_id."'";
mysqli_query($conn,$query); // $conn must be as per your `mysqli_connect` variable
}
header('location:profile.php');
?>

Unable to connect the Database and Handle the POST request

Hello I am working with a predefined template and I am trying to fetch some data from the input space in form of POST/GET request using php. But I am unable to do so, How can I integrate the database and handle the php parameters?
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<input type="text" placeholder="Adhaar" name="Adhaar" required="">
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="">
<?php
if(isset($_GET['Adhaar']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
?>
}
Hello change your code to this
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<input type="text" placeholder="Adhaar" name="Adhaar" required="">
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="">
<?php
if(isset($_GET['Adhaar']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
//Connect to the database here
}
?>
</div>
</div>
For the database connection it depends on which database you are working with but you can start here. A simple Google query with provide you what you are looking for
I put together an example for you that may come in handy. This shows how you can use PHP to submit a form print some values that the user enters on the page. I also included some commented out code that you can copy and move to a seperate script and call by changing the action value to the file path.
The PHP script:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// try {
// Connect to the database:
// $db = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Retrieve all records:
// $sql = 'SELECT * FROM categories';
// $result = $db->query($sql);
// } catch (Exception $e) {
// $error = $e->getMessage();
// }
// echo '<pre>';
// Pass MYSQLI_BOTH or MYSQLI_ASSOC as the argument to change the array type
// $all = $result->fetch_all();
// echo json_encode($all);
// echo '</pre>';
// $db->close();
$data = [
"BOB" => "AWESOME",
"JOE" => "AVERAGE",
"TOM" => "COOL"
];
}
?>
Next, we have the form. I added this form because you need it to submit to the page. (Well you don't "need" it but it makes life easy.)
<div class="container">
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<div class="form-group">
<input class="form-control"
type="text"
placeholder="Adhaar"
name="adhaar"
required
value="<?= isset($_POST['adhaar']) ? $_POST['adhaar'] : '' ?>">
</div>
<div class="form-group">
<input class="form-control"
type="text"
placeholder="Town/City"
name="city"
required
value="<?= isset($_POST['city']) ? $_POST['city'] : '' ?>">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">CLICK ME!</button>
</div>
</form>
<?php if (isset($_POST['adhaar'])) : ?>
<p>Hi there <?= $_POST['adhaar'] ?></p>
<?php endif ?>
<?php if (isset($_POST['city'])) : ?>
<p><?= $_POST['city'] ?> is a great place to live!</p>
<?php endif ?>
<?php if (isset($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<p><?= $key ?> - <?= $value ?></p>
<?php endforeach ?>
<?php endif ?>
</div>
Last piece of the file simply outputs information onto the page if it finds it in the $_POST global array.
<?php if (isset($_POST['adhaar'])) : ?>
<p>Hi there <?= $_POST['adhaar'] ?></p>
<?php endif ?>
<?php if (isset($_POST['city'])) : ?>
<p><?= $_POST['city'] ?> is a great place to live!</p>
<?php endif ?>
<?php if (isset($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<p><?= $key ?> - <?= $value ?></p>
<?php endforeach ?>
<?php endif ?>
This commented out part here you can use to pull data from the database and pass it back to your page. If you are just starting it's cool to tinker but ideally you DO NOT want to make calls to the db on the same page as your view. It should live in it's own file.
// try {
// Connect to the database:
// $db = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Retrieve all records:
// $sql = 'SELECT * FROM categories';
// $result = $db->query($sql);
// } catch (Exception $e) {
// $error = $e->getMessage();
// }
// echo '<pre>';
// Pass MYSQLI_BOTH or MYSQLI_ASSOC as the argument to change the array type
// $all = $result->fetch_all();
// echo json_encode($all);
// echo '</pre>';
// $db->close();
You should Try This Code ..This is working i Simply add a submit button to it
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<form method="GET" action="xxx.php">
<input type="text" placeholder="Adhaar" name="Adhaar" required="" />
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="" />
<input type="submit" name="submit" value="show">
<?php
if(isset($_GET['submit']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
//Connect to the database here
}
?>
</div>
</form>
</div>

PHP Header Exceptions

I have a seperate navigator.php included on top of every page that I have for public.And it has a login form.If users have an account,they can login and be sent to the current page that they are at.
I pass the current URL adress to a hidden input as it's value.And post it to giris.php(login).Then redirecting the user with Header.
But when it comes to register.php(when no sessions were set);Im trying to login there and it still sends me back to the register.php.But SESSION is being set.Thats where I need an exception and want to send user to the index.php through register.php.
navigator.php
<div id="top">
<ul class="topnav" id="myTopnav">
<li>Anasayfa</li>
<li>İletişim</li>
<li>Hakkımızda</li>
<?php
if (isset($_SESSION["giris"]))
{
echo '<li>Panel</li>
<li>Çıkış Yap</li>';
}
else
{
$url= $_SERVER["REQUEST_URI"];
echo '<li>Kayıt Ol</li>
<li id="log">
<form method="post" action="giris.php"><div id="login">
<input type="hidden" name="location" value="'.$url.'">
<input type="text" name="username" placeholder="Kullanıcı Adı" class="loginField" required>
<input type="password" name="password" placeholder="Şifre" class="loginField" required>
<input type="submit" name="login" value="Giriş" id="logBut">
</form>
</li>';
}
?>
<li class="icon">
☰</li>
</ul>
</div>
<div id="banner">
<div id="title">
<h1>Topluluk Bloğu</h1>
<br/>
<h5>Community Blog</h5>
<br/>
<?php if(isset($_SESSION["giris"])){echo '<p id="username">Hoşgeldin '.$_SESSION["kullanici"].'</p>'; }?>
</div>
</div>
giris.php
<?php
session_start();
ob_start();
include 'func/constr.php';
if(isset($_POST["login"]))
{
$kullanici = $_POST['username'];
$password = $_POST['password'];
$URL = $_POST["location"];
$query = mysqli_query($connect,"SELECT * FROM kullanicilar where kullanici_adi='$kullanici' and sifre='$password'");
$count = mysqli_num_rows($query);
if ($count == 1)
{
$_SESSION["giris"] = true;
$_SESSION["kullanici"] = $kullanici;
$_SESSION["sifre"] = $password;
header("Location:$URL");
}
else
{
$invalid = "Kullanıcı adı ya da şifre yanlış";
$_SESSION["invalid"] = $invalid;
header("Location:index.php");
}
}
ob_end_flush();
?>
try this but not tested, if your other code is ok and redirect problem then
header("Location:$URL");
to
header('Location: ' . $URL);

Stop on submit form refreshing page

I am having a problem, since my website reloads each time somemone submit a form.
It's a wide scroll, so i just found also another solution, but gives me an error.
PHP CODE:
<?php
session_name("fancyform");
session_start();
$_SESSION['n1'] = rand(1,20);
$_SESSION['n2'] = rand(1,20);
$_SESSION['expect'] = $_SESSION['n1']+$_SESSION['n2'];
if(isset($_SESSION['sent']))
{
$success='<h1>Thank you!</h1>';
unset($_SESSION['sent']);
header('Location: index.php#5');
}
?>
FORM CODE:
<form class="demo-form" name ="demo-form" data-parsley-validate method="post" action="submit.php" >
<ul>
<li class="js-hide-label">
<label for="name">Nombre:</label>
<input type="text" placeholder="Nombre" id="name" name="name" data-parsley-trigger="change" required tabindex="1" autocomplete="off" value="<?php echo (isset($_SESSION['post']['name']) ? $_SESSION['post']['name'] : ''); ?>" >
</li>
<li class="js-hide-label">
<label for="email">Your Email:</label>
<input type="email" placeholder="Your Email" id="email" data-parsley-trigger="change" name="email" autocomplete="off" required tabindex="2" value="<?php echo (isset($_SESSION['post']['email']) ? $_SESSION['post']['email'] : ''); ?>">
</li>
<li class="js-hide-label">
<label for="message">Message:</label>
<textarea placeholder="Message…" id="message" name="message" tabindex="3" required data-parsley-trigger="keyup" textarea id="message" data-parsley-minlength="20" data-parsley-maxlength="100" data-parsley-minlength-message = "Come on! You need to enter at least a 20 caracters long comment.." data-parsley-validation-threshold="10"><?php echo (isset($_SESSION['post']['message']) ? $_SESSION['post']['message'] : ''); ?></textarea>
</li>
<input class="btn btn-default"type="submit" name="button" id="button" value="Submit" />
</ul>
<?php echo isset($success)?$success:''; ?>
</form>
As you can see, adding a POSSIBLE SOLUTION with header('Location: index.php#5'); makes my website come back to the contact form (not exactly what I wanted, but helps a bit), but it breaks the $success='<h1>Thank you!</h1>';.
Is there any easy way to do it (using my original code) with AJAX? Since I am not used to work with scripts.
In the other hand, could be a solution on display $success='<h1>Thank you!</h1>'; and make the function header('Location: index.php#5'); work on the same form?
Use Ajax to post data if you don't want to refresh the page.
See documentation here
$.post documentation
Or
Ajax
Use header and redirect the page.
header("Location:your_page.php");
You can redirect to same page or different page.
or
<?php
session_name("fancyform");
session_start();
$_SESSION['n1'] = rand(1,20);
$_SESSION['n2'] = rand(1,20);
$_SESSION['expect'] = $_SESSION['n1']+$_SESSION['n2'];
if(isset($_SESSION['sent']))
{
unset($_SESSION['sent']);
header('Location: index.php?msg=sucess');
}
if ( isset($_GET['msg']) && $_GET['msg'] == 'sucess' )
{
$success='<h1>Thank you!</h1>';
}
You can try this :-
By using session :
if(isset($_SESSION['sent']))
{
unset($_SESSION['sent']);
$_SESSION['thanks_msg'] = 'Thank You';
header('Location: index.php#5');
}
?>
On index.php file :-
check if the $_SESSION['thanks_msg'] is set or not, if set then displaythat session msg.
By using GET method :-
if(isset($_SESSION['sent']))
{
$success='Thank you!';
unset($_SESSION['sent']);
header('Location: index.php?msg='.$success);
}
?>
on index.php file
if(isset($_GET['msg']))
{
echo $_GET['msg'];
}
EDIT :-
if(isset($_SESSION['sent']))
{
$success='Thank you!';
unset($_SESSION['sent']);
header('Location: index.php?msg='.$success);
}
?>
on index.php file
if(isset($_GET['msg']))
{
echo $_GET['msg'];
}

requested URL is not found this server? doesn't redirect to the next php page

Good evening everyone i'm working on a stock market simulation using php ...and i've few errors that i can't reslove ..
1- after i submit log in credentials i get to get this message
Not Found
The requested URL /viewdetails.php was not found on this server.
i'm using wamp server ..so if i want to proceed to "viewdetails.php" i have to add the folder name in which the project is at manually to the URL for instance URL Test/viewdetails.php
so here is the code for both of the php pages ! to start with is the "index.php"
<?php
require("functions_start.php");
if (isset($_REQUEST["username"]) && isset($_REQUEST["password"]))
{
$error = $theUser->LoginCheck($_REQUEST["username"], $_REQUEST["password"]);
}
if (isset($_REQUEST["logout"]))
$theUser->Logout();
if (isset($_SESSION["authenticated"]) && $_SESSION["authenticated"]== true)
{
header("Location: /viewdetails.php");
exit;
}
HTMLHeader("Login to the stocks!",false);
if (isset($error))
{
if ($error==false)
echo "<div>Not able to login, please try again</div>";
}
if (isset($_REQUEST["logout"]))
echo "Thanks for using the site, you are logged out!";
?>
-
<div id="login">
<b class="rtop">
<b class="r1"></b> <b class="r2"></b> <b class="r3"></b> <b class="r4"></b>
</b>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" onsubmit="">
Login
<p>
Username : <input type="text" name="username" id="username" value=
"<?php echo $_REQUEST["username"]; ?>"/>
</p>
<p>
Password : <input type="password" name="password" id="password"/>
</p>
<p>
<input type="submit"/>
</p>
<p id="right">
Register here.
</p>
</form>
<b class="rbottom">
<b class="r4"></b> <b class="r3"></b> <b class="r2"></b> <b class="r1"></b>
</b>
</div>
<?php
HTMLFooter();
?>
and this is a part form the "viewdetails.php"
<?php
require("functions_start.php");
global $theStock;
if (!isset($_SESSION["authenticated"]) || $_SESSION["authenticated"]== false)
{
header("Location: /index.php");
exit;
}
foreach ($_REQUEST as $key => $value)
{
if (strpos($key, "remove_") === 0)
$theStock->SellStock($_SESSION["username"], $value);
if ($key=="stock")
$getStock = $value;
}
HTMLHeader("The details of your account");
?>

Categories