I am looking to show some content on a page based on the parameter in a link.
If a link is given to a user https://www.examplesite.com/example-page/?client_feeback=1
then they will see the content of the page, if not using the link, then users will not see the content.
Additionally, I need the users of the link to be able to look on other pages and return to the page where the content is hidden/shown and still see the content.
I have set a cookie in functions.php, that will expire in 30days.
code added into functions.php
add_action('init', 'set_feedback_cookie');
function set_feedback_cookie () {
$name = 'client_feedback';
$value= 1;
setcookie($name, $value, strtotime( '+30 days' ), "/example-page/", "examplesite.com", "true" );
}
I have then added the following into the example-page.php template file
<?php
if (!isset($_GET['client_feedback'])) { ?>
<style type="text/css">#form__feedback {display:none!important}</style>
<?php } else { ?>
<style type="text/css">#form__feedback {display:block!important}</style>
<?php } ?>
The cookie is loaded on to the site and the content is hidden/shown when using/ not-using the url link.
What is not working, is the ability to browse other pages on the site and come back to the page with the hidden content and still see it!
Since you confirmed in the comment section that you are not leaving your own domain, You could put the GET variable into a SESSION variable and do your checks based on that. That way, you will always have that available to you until the user leaves the site or you manually kill the session somewhere.
Example:
<?php
session_start();
$_SESSION["client_feedback"] = $_GET['client_feedback'];
?>
As long as declare your session_start(); at the very beginning of your page(s) (literally before ANYTHING else), you can access your session variable anywhere you want.
Now you can perform checks on your session variable with the logic you're trying to achieve in order to display your desired content.
Full Example:
<?php
session_start();
if($_GET['client_feedback'] != "") {
$_SESSION["client_feedback"] = $_GET['client_feedback'];
}
if( isset( $_SESSION["client_feedback"] ) != "" ) {
?> <style type="text/css">#form__feedback {display:block!important}</style> <?php
} else {
?> <style type="text/css">#form__feedback {display:none!important}</style> <?php
}
?>
You can read more about PHP sessions here.
Related
I have a form on every page that is a quick navigation. Based on the value of the drop-downs it will redirect to a specific page. The URL after using it will look like /page?first=abc&second=def&third=ghi. If you leave the page and go to pageB the url will just say /pageB. I'm trying to create a SESSION for second if it's set and when it's no longer set (navigating to a different page not using the quicknav) still store the value when it was set. Here is what I have so far...
function storeVariable {
global $saved_second
$store_second = $_GET['second'];
$saved_second ='';
if (isset($store_second)) {
$_SESSION['second'] = $_GET['second'];
$sessionsecond = $_SESSION['second'];
$saved_second = $sessionsecond;
}
return $save_second
}
In the header I have
global $saved_second;
echo $saved_second;
The above code is fine for the initial page the quick navigation goes to. It shows the value of $saved_second in the header. I'm not sure how I would say
if (isset($saved_second) && (!isset($stored_second) {
USE SESSION THAT WAS CREATED WHEN $stored_second WAS SET
I thought something like...
if ($store_second != $sessionsecond){
but that doesn't work either because the session was created in an IF statement.
Then I tried...
IF (!isset($saved_second)) {
IF (isset($_GET['second'])) {
$_SESSION['second'] = $_GET['second'];
$saved_second = $_SESSION['second'];
}}
Any suggestions?
I have a div that contains a slider when the homepage of the website is opened. What im trying to achieve is that when the website is opened for the first time, the slider should appear. However, if the user goes another page other than the homepage and then returns to the homepage again, the slider should not appear.
Below is the code I am trying to implement:
<div class="homeslidermain" style="display:<?php echo empty($_SESSION['first_load']) ? 'block' : 'none'; ?>">
<?php putRevSlider("typewriter-effect", "homepage") ?>
</div>
The recommended way would be to set a cookie using setcookie() and getcookie() (http://php.net/manual/de/features.cookies.php).
If you want to use the session then you are setting "first_load" incorrectly. Make sure that on any page call:
session_start(); // before you do anything else
if(!isset($_SESSION['first_load'])) // set it to true on first load
... and to false in any other case.
The only reason why this might go wrong is if you are reinitializing your session wrong. Make sure you are still in the same session after switching pages.
There is no need to output the div as display:none. Just output the div only when user visits the homepage for the first time. Use the setcookie() function to remember that user already visited he homepage, but please note that you should call this function before any output.
<?php
if (empty($_COOKIE['homepage_visited'])) {
// Remember the first visit for one year
setcookie('homepage_visited', 1, strtotime('+1 year'));
// Show the slider
echo '<div class="homeslidermain">';
putRevSlider("typewriter-effect", "homepage");
echo '</div>';
}
There are several ways to achieve it, best is to check if user visiting page for first time
session_start();
if(!isset($_SESSION['first_load']))
{
$_SESSION['first_load'] = '1';
}
if(empty($_SESSION['first_load']))
{?>
<div>
Slider block // this block loads only is first load is empty
</div>
<?php
}?>
You Could try something like this
// start the session
session_start();
$bShowBanner = true;
if(isset($_SESSION['BannerShown'])){
$bShowBanner = false;
}else{
$_SESSION['BannerShown'] = true;
}
?>
<div class="homeslidermain" style="display:<?php echo ($bShowBanner ? 'block' : 'none'); ?>">
<?php putRevSlider("typewriter-effect", "homepage") ?>
</div>
first time Question asker here. I'm building a web page and want to change the text on page if the user has visited certain pages.
My initial idea was too create an array in the session which records each url as its visited with something like $_SERVER['REQUEST_URI'], which would probably work if it was a site I was building from scratch. however... Because the site is built in Wordpress I'm not 100% how to go about doing that within there system.
Now here's what I'd suggest you do. Navigate to your Theme and open the file functions.php
Then find a suitable spot anywhere on the File (The bottom of the file wouldn't be that odd).
Then, add the following functions:
<?php
// FILE-NAME: functions.php <== LOCATED AT THE ___/wp-content/themes/your-theme-name
add_action("init", "initiatePageLogging");
function initiatePageLogging(){
// START THE SESSION IF IT HAS NOT BEEN STARTED
// THIS WOULD BE USED TO SHARE DATA ACROSS YOUR PAGES...
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
// CHECK THAT THE SESSION VARIABLE FOR OUR PAGE-LOGGING IS THERE
// IF NOT CREATE IT
if(!isset($_SESSION['visitedPages'])){
// IT DOES NOT EXIST SO WE CREATE IT & INITIALIZE IT AS AN EMPTY ARRAY
$_SESSION['visitedPages'] = array();
}
// NO NEED TO KEEP THE SESSION ARRAY $_SESSION['visitedPages'] TOO LONG
// SO WE TRIM IT OUT CONDITIONALLY TO KEEP IT UNDER CHECK
if(count($_SESSION['visitedPages']) >= 10){
// WE REMOVE ABOUT 7 ELEMENTS FROM THE BEGINNING OF THE ARRAY
// LEAVING JUST THE LAST 3 - NOW THAT'S COOL...
$arrVisitedPages = $_SESSION['visitedPages'];
array_splice($arrVisitedPages, 0, 7);
// RE-DEFINE THE $_SESSION['visitedPages'] ARRAY
$_SESSION['visitedPages'] = $arrVisitedPages;
}
}
function getLastVisitedPage(){
$lastVisitedPage = get_site_url() . $_SERVER['REQUEST_URI']; //<== FALL BACK TO THE CURRENT PAGE IF WE HAVE AN ISSUE.
if( isset($_SESSION['visitedPages']) && is_array($_SESSION['visitedPages']) ){
$arrVP = $_SESSION['visitedPages'];
$intArrVPLength = count($arrVP);
$diff = ($intArrVPLength - 2);
$lastVisitedPage = ( $intArrVPLength > 1) ? $arrVP[$diff] : $lastVisitedPage;
}
return $lastVisitedPage;
}
?>
Now, Part 1 is done! Inside of your Theme, You will still find a File Called header.php
This is where we have to do the logging because by default every page in Word-Press loads this Page (except when configured otherwise).
At the very, very top of that File - I mean on Line 1, do this:
<?php
// FILE-NAME: header.php <== LOCATED AT THE ___/wp-content/themes/your-theme-name
// BUILD THE URL OF THE CURRENT PAGE & PUSH IT TO THE SESSION VARIABLE...
$thisPage = get_site_url() . $_SERVER['REQUEST_URI'];
$_SESSION['visitedPages'][] = $thisPage;
// THAT'S ALL! BELOW HERE, THE ORIGINAL CONTENT OF THE header.php FILE CONTINUES...
?>
One more thing! How do we now use the $_SESSION['visitedPages'] Variable?
Otherwise, how do we know which page was last visited using the $_SESSION['visitedPages'] Variable?
Now on every File like (page.php, index.php, category.php, taxonomy.php, etc); you can now find out the last visited Page by doing something like this:
<?php
// FILE-NAME: ANY FILE IN THE THEME LIKE: page.php, index.php, category.php, taxonomy.php, etc
$lastVisitedPage = getLastVisitedPage();
// THAT'S IT, PAL...
?>
I hope this helps....
I have a dynamic link which fetches invoice detail based on invoice ID.
<a href='<?php echo $_SERVER['PHP_SELF']; ?>/retrieve?class=InvoiceLineItems&id=<?php echo $invoice['invoice_id']; ?>'><?php echo $invoice['invoice_number']; ?></a> <?php echo $invoice['customer_name'] ?> <?php echo $invoice['invoice_date'] ?>
It calls this function
public function retrieve($class,
$id = NULL)
{
switch ($class) {
case 'Invoice':
$invoices = $this->invoice->getInvoices();
include 'view/invoiceList.php';
break;
case 'InvoiceLineItems':
$partnerInfo = $this->partnerInfo->getPartnerInfo($id);
$invoiceLineItems = $this->invoiceLineItems->getInvoiceLineItems($id);
include 'view/invoice.php';
break;
}
}
However, the include statement found in case 'InvoiceLineItems:' appends the content of invoice.php to the bottom of the existing page rather than replacing it altogether. I've tried adding a target to the anchor, but that didn't work. How do I get the link to open the new page?
UPDATE: based on #sixeightzero suggestion, here is the call to retrieve();
if (isset($_REQUEST['id'])) {
// A request ID value indicates arrival here through link.
$this->retrieve('InvoiceLineItems',
$_REQUEST['id']);
}
Also, I tried using a header redirect.
ob_start();
header('Location: /view/invoice.php', 302);
ob_end_flush();
exit();
It redirects, but I lose access to my array variables from
$invoiceLineItems = $this->invoiceLineItems->getInvoiceLineItems($id);
So, I get errors like
Notice: Undefined variable: partnerInfo in C:\xampp\htdocs\bp\view\invoice.php on line 25
and
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\bp\view\invoice.php on line 25
put exit(); at the end of the function to stop executing code after calling it.
or better still use invoice.php to display the invoices instead of the current page.
1) Since, you are using super global *$_SERVER['PHP_SELF']*, the
anchor will always direct to the same page.
2) Now, I assume, you call the function retrieve() at the end of
the page which in turn, after you hit the link, appends
'view/invoice.php' to the page, so you see the appended content at the
end.
Now, you want to get the link to open the new page, there are two ways:
1) You redirect the page to the page view/invoice.php and there you
call the function retrieve and include target="self" in the anchor tag.
Or
2) You do what you are doing but include target="blank" in the
anchor tag.
In order to get the link to open as fresh content, do as follows:
1) Add javascript to the page. In the Html Head section add the
following lines:
<script type="text/javascript">
function hideMainContentDiv(){
document.getElementById("mainContent").setAttribute("style", "display:none");
}
</script>
2) Add the onclick attribute to the anchor tag as:
<a onclick="hideMainContentDiv()">
3) Now, enclose the content of the page in and give it
id="mainContent" as:
<div id="mainContent"> <!-- All your content --> </div>
4) At the end of the page when you have enclosed your content, add
another div and call your function retrieve as:
<div id="newContent">
<?php retrieve($class,$id); ?>
</div>
What this will do is:
When you click the link, it will call the javascript and hide all your existing page content in the div whose id="mainContent".
When your function retrieve() will be called, it will include 'view/invoice.php' which will show your new content.
Your old content has already been hidden by javascript call.
I hope this resolves your query.
The answer turned out to be sessions.
case 'InvoiceLineItems':
$partnerInfo = $this->partnerInfo->getPartnerInfo($id);
$invoiceLineItems = $this->invoiceLineItems->getInvoiceLineItems($id);
$_SESSION['partnerInfo'] = $partnerInfo;
$_SESSION['invoiceLineItems'] = $invoiceLineItems;
ob_start();
header('Location: /view/invoice.php');
ob_end_flush();
exit();
break;
I added the array data to two session variables in the controller. Then, in the view, I replaced the corresponding variable names -- $partnerInfo and $invoiceLineItems -- with their session equivalents $_SESSION['partnerInfo'] and $_SESSION['invoiceLineItems'].
I'm aware that this topic has been covered before here on Stack, and I have looked at some answers, but I'm still a bit stuck, being fairly new to PHP. Every page on my website requires a login, and so users are redirected to a login page on page load. At the top of each page then I have:
<?
require("log.php");
include_once("config.php");
include_once("functions.php");
?>
This redirects the user to log.php (with new code added):
<?
session_name("MyLogin");
session_start();
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php"; // default page for
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","",""); // your MySQL connection data
$db = mysql_select_db(""); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM users WHERE login='$name'");
if (!$q_user) {
die(mysql_error());
}
if(mysql_num_rows($q_user) == 1) {
$query = mysql_query("SELECT * FROM users WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) {
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/$url"); // success page. put the URL you want
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}
// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}
?>
The login form is contained in login.php. The code for login.pho relevant to the PHP/log.php is:
<?
session_start();
if($_GET['login'] == "failed") {
print $_GET['cause'];
}
?>
and
<form name="login_form" id="form" method="post" action="log.php?action=login">
The answer that I came across stated that I should add:
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
to the top of each page, which I did, at the top of the page (above "require("log.php");"), and then add:
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php"; // default page for
to my login page, and use the following URL for redirect on successful login:
header("Location: http://example.com/$url"); // perform correct redirect.
I am not 100% where the code which stores the referring URL should go, at the top of log.php or login.php.
I have tried adding it to both, but the login page is just looping once I have entered the username and password.
I wonder if someone could help me get this working?
Thanks,
Nick
It appears that I don't have the privilege to comment on your post, so I'll do the best that I can to answer. I apologize for all of the scenarios, I'm just doing the best I can to answer on a whim.
SCENARIO 1:
If you've truly not selected a database in your code, as demonstrated here, could that potentially be your issue? Please do note, that the code below, is the code you've posted.
$db = mysql_select_db(""); //put your database name in here
SCENARIO 2:
The code below is not something I've ever used in anything I've built, might I suggest that you try replacing that line of code with the line below it?
if(session_is_registered("name") == false) { // Current
if(isset($_SESSION['name']) == false) { // Potential Replacement
SCENARIO 3:
If you're logic for the following, exists on the login.php file as well... That could potentially be your problem. Upon visiting your site, I noticed your form appears on login.php, yet your logic is posting to log.php. I'm hoping this bit of code can help rule out that "jump", as login.php might be saving itself and overwriting the $_SESSION variable you've established
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
If it's too complex to take it out of the login.php file, if you even have it there, I've put together some code that you can use to create "internal" breadcrumbs, so you can go 2 pages back in your history.
if(!isset($_SESSION['internal_breadcrumbs']))
$_SESSION['internal_breadcrumbs'] = array();
$_SESSION['internal_breadcrumbs'][] = $_SERVER['REQUEST_URI'];
$max_breadcrumbs = 5;
while(count($_SESSION['internal_breadcrumbs']) > $max_breadcrumbs)
array_shift($_SESSION['internal_breadcrumbs']);
That will create an array with a max of $max_breadcrumbs elements, with your most recent page at the end, like the following
Array
(
[internal_breadcrumbs] => Array
(
[0] => /other_page.php
[1] => /other_page.php
[2] => /other_page.php
[3] => /user_page.php <-- desired page
[4] => /login.php <-- most recent page
)
)
So now... you can setup your url to be something more like the following...
// I'm doing - 2 to accommodate for zero indexing, to get 1 from the current page
if(isset($_SESSION['internal_breadcrumbs']))
$url = $_SESSION['internal_breadcrumbs'][count($_SESSION['internal_breadcrumbs']) - 2];
else
$url = "index.php"; // default page for
All the best, and I certainly hope this has helped in some way.
IN SCENARIO 4
From the client test the login/password which ajax XMLHttpRequest with javascript code to a dedicated script for validation (do it on mode https for secure)
If response is right send the login password to your script server.
Stips : Encoding password is better secure !
Using header() function it's a bad idea.
Manual specification say ;
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.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
So in your case, i suggest that to use cookies with an ID generate only for the session, at the first connection its generate, and the duration of the cookie maybe for only from 2 to 10 minutes.
Regenerate cookie each time the loging.PHP is called !
Have a nice day