PHP- Session lost upon refresh or revist - php

I'm new to php as you can tell and I'm having trouble with my session.Session is being lost upon refreshing page. I have a simple button that toggles between light and dark mode, it works and I store the value into a session value. I'm able to print the value and see that it is being stored, however upon a refresh or a revisit, the mode switches to the opposite mode and then upon refresh/revisit, the state is actually saved. I've tried to search for my issue but I cant find anything and I'm off to bed so I thought I may as well post in the meantime. I'm not sure what I'm missing, probably something obvious, but I appreciate the help. I can only use PHP for this by the way.
<?php
session_start();
//header('Refresh: 3000; url=index.php');
echo "" . $_SESSION['color'] . "";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
?>
<!DOCTYPE html>
<html lang = "en-US">
<head>
<link rel="stylesheet" href="index.css">
<title>
Web Technologies
</title>
</head>
<body>
<?php session_start();
include_once "templateFunctions.php";
if (isset($_POST['dark'])) {
if (!isset($_SESSION['color'])) {
//session_register('color');
$_SESSION['color'] = "rgb(54, 53, 53)";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
} else {
if ($_SESSION['color'] == "rgb(54, 53, 53)") {
$_SESSION['color'] = "white";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
} else {
$_SESSION['color'] = "rgb(54, 53, 53)";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
}
}
}
/*$color = "rgb(48, 48, 48)";
setcookie('color', $color, time() + 10, '/');
$_COOKIE['color'] = [$color];
echo "<p>'$cookie'</p>";
echo "<body style = 'background-color: $cookie;'>";
else {
$_SESSION['color'] = "rgb(54, 53, 53)";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
}
*/
?>
<div class = "header">
<div class = "title" >
<h1>Jimbo Fimbo</h1><h2><u>Software Stuff</u></h2></th>
</div>
<div class = "img">
<img id = "img1" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTci5Mqm2mgMe_9KfJR0TqMEd-A_wtmqq69cru0wed7OEQF6jVAYycqCY_KzWV0o3hIVYs&usqp=CAU" alt="https://i.ytimg.com/vi/KEkrWRHCDQU/maxresdefault.jpg">
</div>
</div>
<hr style = "margin-bottom: 20px;">
<div class = "colgroup">
<div class="column1">
<h3 style = "text-align: center;">Menu</h3><hr style = "color:white;">
<ul style = "padding-left:20px; font-size: 25px;">
<li>GitHub<br></li>
<li>Courses<br></li>
<li>School<br></li>
</ul>
</div>
<div class="column2">
<h1>About Me</h1>
<img id = "img2"src="https://i.ytimg.com/vi/KEkrWRHCDQU/maxresdefault.jpg">
<p>
Heres some lorem ipsum! <br> Lorem ipsum dolor sit amet. Reprehenderit sunt est quia
necessitatibus est eius quis. Est dolor adipisci et dolor molestiae hic vitae expedita eum inventore quam aut mollitia natus. Qui quia
dolor aut totam Quis qui expedita repudiandae non quam magni et enim ipsa qui consequatur omnis. Ea incidunt debitis est nemo nesciunt
eum quia rerum eum recusandae sunt nam maiores saepe. Hic omnis dolores ab deserunt vero cum fugiat explicabo vel perferendis numquam.
Sed unde voluptatibus quo aliquid iure rem accusamus voluptatum aut maxime adipisci id molestiae voluptatem? In quia necessitatibus et
provident id nobis eius ea enim voluptatem in aliquam voluptas ut similique facilis. Et porro ipsam eos excepturi voluptatem non ullam sint.
</p>
<p>Stuff goes here </p>
</div>
<div class="column3">
<p style = "text-align: center;">Enrolled Courses</p>
<hr style = "color:white;">
<ol style = "padding-left: 20px; font-size: 25px;">
<li>CS-3753</li>
<li>CS-4393</li>
<li>CS-4413</li>
<li>CS-4423</li>
<li>CS-4843</li>
</ol>
<form action="index.php" method = "post" accept-charset=utf-8 >
<input type="submit" name = "dark" id ="submit" value = "Dark Mode">
</form>
</div>
</div>
<footer class="foot">
Copyright 2022, Jimbo Fimbo
</footer>
</body>
</html>
I'm expecting what I mentioned above.
I've looked over the code to no avail, I've tried using another session variable to save the color change, I tried saving the session to a path using said method, and I've looked on the internet for similar problems but I guess I suck at googling since this seems like it would be straightforward.

If you want to get rid of the problem that the session variable will be "toggled" on page refresh, One of the ways is to separate the change color part from your display part, so the form submission target can be set to "changecolor.php", which will trigger a page redirection to index.php upon changing the session variable :
index.php
<?php
session_start();
/// initalize the color to be white if no color session variable
if (!isset($_SESSION['color'])) {
$_SESSION['color'] = "white";
}
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
?>
/// other HTML code
<form action="changecolor.php" method = "post" accept-charset=utf-8 >
<input type="submit" name = "dark" id ="submit" value = "Change Color Mode">
</form>
changecolor.php
<?php session_start();
if (isset($_POST['dark'])) {
if (!isset($_SESSION['color'])) {
$_SESSION['color'] = "rgb(54, 53, 53)";
} else {
if ($_SESSION['color'] == "rgb(54, 53, 53)") {
$_SESSION['color'] = "white";
} else {
$_SESSION['color'] = "rgb(54, 53, 53)";
}
}
header("Location: index.php");
}
?>

Related

Save in DB a Progress Scrollbar value(%) when user automatically closes the page

I'm working on a progress scrollbar, and I'm trying to save the value(%) in the database/Mysql automatically where each user leaves on the page when closing it.
Ex.: A user accessed the page and scrolled down to 79% and closed the page, so in my MySQL database it will be registered this value 79% (only the value, nothing about the user)... And so to other users successively to that specific page.
I tryied session, but could only save with the automatic save after a programed time, here's what i have:
index.html:
<div class="progress position-sticky">
<div class="progress-bar" id="myProgressBar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<div class="container text">
<h1>Bootstrap Reading Progressbar Example</h1>
<p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt autem ex illum voluptates officiis earum, odit explicabo repellat ducimus modi excepturi libero officia soluta doloremque voluptatum numquam eligendi quibusdam fugiat. Voluptatem incidunt ipsum nam quisquam repellendus distinctio minus doloribus corporis aspernatur. Sunt omnis repudiandae in illum unde nisi id culpa temporibus, voluptatem aut nobis doloremque optio impedit quidem porro ad rerum qui placeat magnam quod quae maiores deserunt! Soluta aliquid numquam sapiente quasi molestias, nulla magnam illo odio voluptatum sint obcaecati eos odit officia per ....... </p>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type="text/javascript" src="main.js"></script>
<script>
window.onscroll = function() {myFunction()};
function myFunction() {
var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 100;
document.getElementById("myProgressBar").style.width = scrolled + "%";
document.getElementById("myProgressBar").innerHTML= Math.round(scrolled) + "%";
}
</script>
save_post.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
if(isset($_POST["postTitle"]) && isset($_POST["postDescription"]))
{
$post_title = mysqli_real_escape_string($connect, $_POST["postTitle"]);
$post_description = mysqli_real_escape_string($connect, $_POST["postDescription"]);
if($_POST["postId"] != '')
{
//update post
$sql = "UPDATE tbl_post SET post_title = '".$post_title."', post_description = '".$post_description."' WHERE post_id = '".$_POST["postId"]."'";
mysqli_query($connect, $sql);
}
else
{
//insert post
$sql = "INSERT INTO tbl_post(post_title, post_description, post_status) VALUES ('".$post_title."', '".$post_description."', 'draft')";
mysqli_query($connect, $sql);
echo mysqli_insert_id($connect);
}
}
?>
Database:
CREATE TABLE IF NOT EXISTS `tbl_post` (
`post_id` int(11) NOT NULL AUTO_INCREMENT,
`post_title` text NOT NULL,
`post_description` text NOT NULL,
`post_status` varchar(15) NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
But what I need is a system that saves the value automatically where the value(%) of the progress scrollbar stands after the user closes the browser, not time to time when the user still on the page (as this current codes).

how to search for a string in text file using PHP

i have a php code that read TXT file and display its content.
i want to allow the user to make a search on any word he want and if its available the system will display it with the line number.
until now i was able to read the text and display it .
i know that i need to read it line by line and stored in variable right or it there any better options?
code
<?php
$myFile = "test.txt";
$myFileLink = fopen($myFile, 'r');
$myFileContents = fread($myFileLink, filesize($myFile));
while(!feof($myFileContents)) {
echo fgets($myFileContents) . "<br />";
}
if(isset($_POST["search"]))
{
$search =$_POST['name'];
$myFileContents = str_replace(["\r\n","\r"], "\n", $myFileContents);
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches,PREG_OFFSET_CAPTURE))
{
foreach($matches[1] as $match)
{
$line = 1+substr_count(substr($myFileContents,0,$match[1]), "\n");
echo "Found $search on $line";
}
}
}
fclose($myFileLink);
//echo $myFileContents;
?>
<html>
<head>
</head>
<body>
<form action="index.php" method="post">
<p>enter your string <input type ="text" id = "idName" name="name" /></p>
<p><input type ="Submit" name ="search" value= "Search" /></p>
</form>
</body>
</html>
Something like this
$myFileContents = file_get_contents($myFileLink);
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches)){
print_r($matches);
}
Using Preg match all, and case insensitive flag.
Getting the line number is much harder, for that you will want to do something like this:
$myFileContents = "Lorem ipsum dolor sit amet, 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.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.";
$search = "non proident";
//normalize line endings.
$myFileContents = str_replace(["\r\n","\r"], "\n", $myFileContents);
//Enter your code here, enjoy!
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches,PREG_OFFSET_CAPTURE)){
foreach($matches[1] as $match){
$line = 1+substr_count(substr($myFileContents,0,$match[1]), "\n");
echo "Found $search on $line";
}
}
Outputs
Found non proident on 5
You can see it live here
If it's a large file you can do a similar search as you read each line. Something like this
$myFileLink = fopen($myFile, 'r');
$line = 1;
while(!feof($myFileLink)) {
$myFileContents = fgets($myFileLink);
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches)){
foreach($matches[1] as $match){
echo "Found $match on $line";
}
}
++$line;
}

Image and text not displaying on page

Im busy with an school command, and i need to play display and text on a page when you have fill in 2 forms on 2 different pages.
First page is kies_merk.html where you have to choose the merk (brand)
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8" />
<title>Kies merk</title>
</head>
<body>
<h3>Auto selectie (Deel 1 van 3)</h3>
<p>Kies een automerk...</p>
<form name="form" action="kies_type.php" method="get">
<select name="merk">
<option value="Volvo">Volvo</option>
<option value="Peugeot">Peugeot</option>
<option value="Volkswagen">Volkswagen</option>
<option value="Opel">Opel</option>
</select>
<input type="submit" value="ok"/>
</form>
</body>
</html>
Second page is where you have to choose the type of the car:
<?php
$formulier = '<p>Welk type wil je bekijken?</p><form name="form2" action="type_informatie.php" method="get"><select name="type"><option value="S40">S40</option><option value="S60">S60</option><option value="C70">C70</option><option value="S80">S80</option></select><input type="hidden" name="Merk" value="Volvo"><input type="submit" value="ok"/></form>'
?>
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8" />
<title>Kies merk</title>
</head>
<body>
<h3>Auto selectie (Deel 2 van 3)</h3>
<p>Kies een type...</p>
<?php
$merk = ($_GET['merk']);
if ($merk === Volvo) {
echo $formulier;
} else {
echo "<p>Dit merk zit helaas nog niet in het 'systeem'...</p><a href='kies_merk.html'>Maak een andere keuze a.u.b</a>";
}
?>
</body>
</html>
On the third page is the output, but there it goes wrong. It doesnt show the image, it only takes the first number out of the array. If i go to my browser to the image URL, it says for e.g. /S (not even .png extension). I think it goes wrong at the $type = $_GET['type'] part, but i dont know for sure. I hope someone can help me.
type_informatie.php:
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8" />
<title>Kies merk</title>
<style>
img {
height: 200px;
width: auto;
}
</style>
</head>
<body>
<h3>Auto selectie (Deel 3 van 3)</h3>
<p>Je koos de volgende auto: <?php echo ($_GET['Merk']) . " " . ($_GET['type']) ?> </p>
<?php
$S40 = array('/S40.png', 'De S40: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut malesuada tincidunt est ut faucibus.');
$S60 = array('/S60.png', 'De S60: Fusce eget quam in purus interdum tincidunt ultricies sit amet velit. Nulla pulvinar cursus malesuada.');
$C70 = array('/C70.png', 'De C70: Aenean aliquam varius eros. Nam dictum, lorem a maximus gravida, odio risus pretium mi, vel convallis neque dui eget nisl. Quisque vestibulum vel lacus id congue.');
$S80 = array('/S80.png', 'De S80: Nullam rutrum metus nec iaculis facilisis. Maecenas vitae hendrerit orci. Nulla sit amet dolor risus. Fusce accumsan augue nec leo congue, nec porta tellus semper.');
$type = $_GET['type'];
echo "<div>" . "<img src='$type[0]' alt='' />" . "</div>";
echo "<p>$type[1]</p>"
?>
</body>
</html>
$type = $_GET['type']; is going to hold the value of the selected option in your select named type
<select name="type"><option value="S40">
$type[0] is an array reference in <img src='$type[0]' alt='' /> which is referencing the first character in the string, which happens to be S from S40
so you need to echo the whole thing, and probably add the .png extension since that's not in your form.
echo "<div>" . "<img src='$type.png' alt='' />" . "</div>";
if you look at your error logs, then you might also notice a notice
Notice: Use of undefined constant Volvo - assumed 'Volvo' in thispage.php on line 6,000,042
You should clean up that assumption by explicitly changing if ($merk === Volvo) which uses a constant, to if ($merk === 'Volvo') which uses a string.

How do I paginate json data in php

I have json data that looks like this
{
"project_no":1693,
"project_name":"Theresa Project",
"description":"Nonumy euismod ornatus usu te, quodsi viderer accommodare sea cu, ut alterum officiis nec. At deleniti eloquentiam vis. Explicari definitionem ei sea. No nec erat fugit voluptaria, in his elit discere fastidii. Aperiri virtute no eos. Te per habemus vulputate, partem iuvaret intellegebat eam in.",
"project_cost":10000.00,
}
{
"project_no":1664,
"project_name":"School Supplies for Children",
"description":"Nonumy euismod ornatus usu te, quodsi viderer accommodare sea cu, ut alterum officiis nec. At deleniti eloquentiam vis. Explicari definitionem ei sea. No nec erat fugit voluptaria, in his elit discere fastidii. Aperiri virtute no eos. Te per habemus vulputate, partem iuvaret intellegebat eam in. ",
"project_cost":8000.00,
},
I have over 60 records, With php I want to show 10 records on each page and dynamically populate the page numbers based on how many records I have.
Heres how I'm displaying the data.
$json = file_get_contents('http://linktojsondata.com');
$obj = json_decode($json, true);
<?php
$i = 0;
foreach ($obj as $project_name => $project_info) { ?>
<a href="single-project-detail.php/<?php echo $project_info['project_no'];?>">
<img class="img-thumbnail" alt="" src="<?php echo $project_info['featured_image_url']; ?>">
</a>
<a href="single-project-detail.php/<?php echo $project_info['project_no'];?>">
<?php echo $project_info['project_name']; ?>
</a>
<p>
<?php $string = strip_tags($project_info['description']);?>
</p>
<?php if (++$i == 10) break; } ?>
Here is a start, you will split the json array into blocks of 10 using array_chunk, and then loop through this using the page number $_GET['p'] - 1 so your page url may look like page.php?p=2 which will select the second set of data.
$pages = array_chunk(json_decode($json, true), 10, true);
foreach ($pages[$_GET['p'] - 1] as $project_name => $project_info) {
// your code
}

Image is not taking 100% of div?

I am trying to create a paragraph and next to that paragraph are images that are generated randomly from a database table. The main container is called ".container" and this includes every element. .container is set to width: 90%. The paragraph (.header) floats to the left and has a width of 70%. The generated images (.recommend) floats to the right and has a width of 30%. Everything works out fine, but the only problem is that when I set the images to take up the whole space of the .recommend div (width: 100%), but it doesn't do that. Instead, the width of the images are 30%. How do I make the images take up the whole space of the .recommend div?
<!DOCTYPE html>
<html>
<head><link type="text/css" rel="stylesheet" href="/science/template.css"></head>
<body>
<div class="container">
<div class="header">
<p>Lorem ipsum dolor sit amet, 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. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div class="recommend">
<?php
$numArray = array();
for ($i = 1; $i <=10; $i++)
{
$numArray[$i] = $i;
}
shuffle($numArray);
$resultSet = $db->query("SELECT * FROM table");
if ($resultSet->num_rows != 0)
{
while ($rows = $resultSet->fetch_assoc())
{
$id = $rows["id"];
$image1 = $rows["image1"];
$image2 = $rows["image2"];
$image3 = $rows["image3"];
$title = $rows["title"];
$title2 = $rows["title2"];
$title3 = $rows["title3"];
echo "<div class=row>";
if ($id == $numArray[0])
{
echo "<div class=col-md-4 id=left><img src=$image1><p>$title</p></div>";
}
if ($id == $numArray[1])
{
echo "<div class=col-md-4 id=left><img src=$image1><p>$title</p></div>";
}
if ($id == $numArray[2])
{
echo "<div class=col-md-4 id=left><img src=$image1><p>$title</p></div>";
}
echo "</div>";
}
}
?>
</div>
</div>
</body>
</html>
CSS
.container{
background--color: green;
width: 90%;
height: auto;
}
.header{
background-color: blue;
float: left;
width: 70%;
}
.recommend{
background-color: red;
width: 30%;
float: right;
}
.recommend img{
width: 100%;
}
It would be FAR more useful to see the rendered HTML than the PHP that generates the html.
The image is taking the full width of the containing div - which is set to 30% width. This markup: <div class=col-md-4 id=left> is using a Bootstrap grid class. And, col-md-4 tells the div to be 4/12 (or 30%) of the width of the parent. Since the parent is .recommend, then the div is 30%, and the image inside is 100% of THAT (which means it is 30% of the .recommend div)
So, you can either remove the col-md-4 class from the divs, or you can try and resolve it another way.
According to the CSS provided .recommend div is set to width:30%
All the child elements that have width:100% (images) will only take up as much space as .recommend div, which is 30%

Categories