How to pass form data between template files in WP? - php

I'm trying to identify which search form is used by the user in WP and depending on the answer, output a specific template.
I have a general idea of how to accomplish it, but WP does not hand form information over to the search.php template. For example a input value.
How could one provide search.php with submitted form data?
This is what I have so far;
located in archive.php
<form>
<input type="hidden" name="formName" value="globalSearch"/>
</form
Located in search.php
<?php $formIdentifier = $_GET['formName']; ?>
<?php if ( strcmp( $formIdentifier, 'globalSearch' ) ) { ?>
// Show foo
<?php } else { ?>
// Show bar
<?php } ?>
And this is the response from the browser:
Notice: Undefined index: formName in -
/wp-content/themes/understrap-child/search.php
EDIT: 26 Jun 2019 # 15:38
After some testing it turned out WP was doing some fancy stuff with my urls, resulting in cleaner urls such as; www.example.com/posts/hello-world You can't access the $GET variable without it displaying in the browser (At least to my knowledge.)
Disabling this feature means my urls now read; www.example.com/s=testing&formName=catalogueSearch&submit= and now the search.php argument I have built works as expected.

Try this snippet.
if(isset($_GET['formName'])) {
$type = $_GET['formName'];
if($type == 'globalSearch') {
load_template(TEMPLATEPATH . '/normal-search.php');
} elseif($type == 'books') {
load_template(TEMPLATEPATH . '/global-search.php');
}
}

Related

get the original URL in PHP file from a Wordpress site

I have a Wordpress site with about 100 pages that contain a link to a contact form that is on a non-Wordpress site.
Let's call my Wordpress site https://example.com. Let's call one of the pages https://example.com/refinance-your-home-today/.
The contact form has the following code, which contains "https://example.com" as the original url (client_url in the code) about 75% of the time. Using the example above, the client_url should capture "https://example.com/refinance-your-home-today/."
When I use the following code, the client_url value is NULL:
<?php
session_start();
function wp_get_original_referer() {
if ( ! empty( $_REQUEST['_wp_original_http_referer'] ) && function_exists( 'wp_validate_redirect' ) ) {
return wp_validate_redirect( wp_unslash( $_REQUEST['_wp_original_http_referer'] ), false );
}
return false;
}
$_SESSION['client_url'] = wp_get_original_referer();
When I use the following code the client_url appears correctly only about 25% of the time. It appears about 75% of the time as "https://example.com":
<?php
session_start();
$_SESSION['client_url'] = $_SERVER['HTTP_REFERER'];
Any help is greatly appreciated.
I found a workaround that solved my issue.
In the original URL page, I changed the a tag to include the client_url=(the page url).
In the index.php (1st page of the form), I added the following:
if(isset($_GET['client_url'])) {
$cu = $_GET['client_url'];
}
$_SESSION['cu'] = $_GET['client_url'];
echo $cu; // to verify the URL is being captured
Then in the body of the form I added the following:
<input type="hidden" name="client_url" value="<?php echo $_SESSION['cu']; ?>">

Five unique pages lead to one page. Can I change the <h1> according to the page they came from?

I have five unique forms each on a page of HTML. They then go to a PHP file to send the e-mail of data. Next they go to the HTML thank you page. I am hoping to change the heading according to which form they just submitted.
For example, if they submit a review, the should read "Thank you for your review" etc.
Technically all of these are saved as php files but only the e-mail page has php items.
Like <?php echo("<p>". $mail->getMessage()."</p>"); ?>
You should redirect to another php file and pass a parameter on url. Example:
sendemail.php
<?php
/** After send the email, check what kind form is (I don't know how do you check this).
This example is just to show you: */
if ($formType == 'review') {
$type = 'review';
} else if ($formType == 'anothertype') {
$type = 'anothertype';
}
header('Location: /thankspage.php?type=' . $type);
?>
thankspage.php
<?php
$type = $_GET['type'];
if ($type == 'review') {
echo '<h1>Thanks for your review</h1>';
} else if($type == 'anothertype') {
echo '<h1>Thanks for your anothertype</h1>';
}
?>
One way put a hidden field in your forms that'll get passed with the other form data. Then put an if statement on the thank you page and echo the appropriate message.
However, that'll only work either if you change the thank you page to php or change the page that receives and processes the form data to echo the thank you message as well

Best way for form action?

I just started using Code Igniter framework and also just started learning on PHP OOP. I came across something when coding for the forms.
In a form if I have two buttons that would lead to different pages, what would be the most suitable way to do it? I found two ways. The first is to have a dynamic action/link, let's call it method A:
Method A
Variable $form_link is 'form_link'.
(View) main_user_view.php
<?php echo form_open($form_link); ?>
<?php echo form_button($add_user_button); ?>
<?php echo form_button($delete_user_button); ?>
<?php echo form_close(); ?>
(Controller) User.php
public function form_link()
{
// Value of button clicked
$form_submitted = $this->input->post('submit_form');
if($form_submitted == 'add_user')
{
redirect('User/add_user');
}
elseif($form_submitted == 'delete_user')
{
redirect('User/delete_user');
}
elseif($form_submitted == 'back')
{
redirect('User');
}
}
And the other way is instead of having a second button I would use an anchor and make an absolute path for it.
Method B
Variable $form_link is 'add_user' which is a function in the controller.
(View) main_user_view.php
<?php echo form_open($form_link); ?>
<?php echo form_button($add_user_button); ?>
<?php echo anchor('add_delete_user/delete_users_view', 'Delete', array('class'=>'btn btn-info', 'role'=>'button'));?>
<?php echo form_close(); ?>
The only problem I have with method A is that if in the form I have input fields, I cannot get the data through POST as redirect does not carry over the data to other functions. I resolved that by using method B where the anchor would lead to the function I want whereby I can get the POST data.
So my main question is, should I use method B instead whenever I have two or more buttons in a form?
You have to use button names for form post actions,
public function form_link()
{
if($this->input->post('add_user'))
{
redirect('User/add_user');
}
if($this->input->post('delete_user'))
{
redirect('User/delete_user');
}
}
What my opinion is also to use the Method B. To make the URL more nicer you can use custom routing (which is located at 'application/config/routes.php')

passing variables between functions and files in php

I have a file called admin.php in which I have a button with the name send. What I want to do is when I click it, to make visible a link on the user's page, user.php. How can I do this?
I have a file with all my functions called functions.php in which I have a function called onSubmit($var); I initialize the variable $var is admin.php with the value $_POST['send'] but when I call the function in the file user.php I have no way of telling him who the variable $var is so I get 'undefined index'.
Is there another way to do this?
EDIT Added code
This is admin.php
<input type="button" name="send" value="Submit" /><br/>
require 'functions.php';
$posted = $_POST['send'];
onSubmit($posted);
This is user.php
require 'functions.php';
onSubmit($var); //here it says undefined index var because it doesn't know who the variable is
if($isSent == 1) {
<a style="visibility:visible;" href="test3.html" id="test3">Test3</a> <br/>
}
And this is functions.php
global $isSent;
function onSubmit($var) {
if(isset($var)) {
$isSent = 1;
}
}
Basically you need to use sessions like below:
if(isset($_SESSION['makeVisible']) && $_SESSION['makeVisible'] == true){
echo '<button>Button init</button>'; //you could also use html like the comment below.
}
/*
if(condition){?> <!-- this is now html --> <button>Button init</button><?}
*/
Then to set this variable on your admin page use:
if(isset($_POST['submitButton'])){
$_SESSION['makeVisible'] == true;
}
You'll also need a form for this method to work but there are other methods but I prefer this one.
<form name="buttonMakerThing" method="POST">
<input name="submitButton" value="Make button init Visible" type="submit"/>
</form>
Without an action the form defaults to 'POSTING' the form information to the current page. Making the condition if(isset($_POST)) return true.
You will need to add a $_SESSION declaration at the top of every php page you have on your site for this to work. It MUST go on the very first line of every page! for example:
01: | <?php session_start();
02: |//rest of script;
Please look more into $_SESSIONS for unnsetting/destroying your sessions and more uses for them :) http://php.net/manual/en/reserved.variables.session.php
Right I've done a bit of research on Caching and this is what I've come up with. It might not be 100% correct but it's a start as like I've said I've never tried it myself lol
In your admin.php I'd put this function in:
if(isset($_POST['send'])){
if($enabled == true){
$enabled == false;
}
else{
$enabled == true;
}
apc_add('enabled',$enabled);
}
Now to 'get' our $enabled var:
$enabled = apc_fetch('enabled');
Then to check the the var within your client page:
if($enabled == true){
echo ' button';
}
Now the only things I haven't fully looked at is the security of the apc_ function and the client usage. I believe it works for all clients of the server but I'm not 100% certain. Here the php manual to give better examples.
This is the method I was thinking of. But again I'm not sure on the security of it but I'm sure you can find something to keep it secure. The video is actually is tutorial for a Youtube API. But he does cover saving a variable to a cache text file which should be of use to you :)
If you have functions.php which defines functions, simply include it in admin.php file and then you can call the function from there and also pass value.

Persistent flag that user is on facebook?

I'm in the middle of designing a mobile site for our main ecommerce site. Because the site is composed of inflexible legacy code I've opted to look up the users user agent string and identify them as a mobile user each page request. That way no changes to the url structure are needed. This seems to be working nicely so far.
However, I thought it may be kind of cool to use this mobile version so that users can browse our ecommerce site on facebook via iframe (the dimensions are perfect). But, unlike the mobile browsers, I am having trouble finding a persistent way to identify the user as a facebook user. I know facebook sends a $_POST variable the first time a page is viewed via iframe, and I could simply just store that in a session variable and be done with it. The issue that arises though is that what if the user visits with facebook, gets marked as a facebook user in their session, then visits our regular ecommerce site? Well, they'd still be identified as a facebook user and get served the facebook version, which is not ideal.
Maybe you can tackle the problem for another angle and test if the website is loaded from a frame or not?
This is possible with javascript:
if (top === self) {
//not a frame
} else {
//a frame
}
Not sure if it's proper etiquette to answer my own question but I found an answer which is a combo of Hassou's answer and a javascript php detection script.
The script I altered is from here:
http://snippets.bluejon.co.uk/check4-js-and-cookies/check4-js-enabled-v2-phpcode.php
Essentially the idea is to use javascript to submit a form referencing the current url, the result tells you if javascript is enabled... However, the idea can easily be altered to submit a form only if javascript returns true for being in an iframe. You can then pass in the $_POST data into the form so that the $_POST data is carried over (only needed if the $_POST data is referenced within the display layer of your application). Here's the basic idea:
<?php
/* Include head of your application goes here, this should do whatever
session handling code you have and all processing done to the $_POST variables */
// ~~~~~~Full Url Function - Works With Mod_Rewrite~~~~~~~~~ //
// important thing is function will grab all $_GET vars
function fullurlnav()
{
$fullurlsortnav = 'http';
$script_name = '';
if(isset($_SERVER['REQUEST_URI']))
{
$script_name = $_SERVER['REQUEST_URI'];
}
else
{
$script_name = $_SERVER['PHP_SELF'];
if($_SERVER['QUERY_STRING']>' ')
{
$script_name .= '?'.$_SERVER['QUERY_STRING'];
}
}
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on')
{
$fullurlsortnav .= 's';
}
$fullurlsortnav .= '://';
if($_SERVER['SERVER_PORT']!='80')
{
$fullurlsortnav .=
$_SERVER['HTTP_HOST'].':'.$_SERVER['SERVER_PORT'].$script_name;
}
else
{
$fullurlsortnav .= $_SERVER['HTTP_HOST'].$script_name;
}
return $fullurlsortnav;
}
// ~~~~~~~~~~~End Full URL Function~~~~~~~~~ //
?>
<html>
<body>
<?php
// Only run this check if user has been identified as a facebook user in their session
// or if they've been identified via the $_POST['signed_request'], which facebook sends
// upon first request via iframe.
// Doing this removes the check when it's unneeded.
if (!isset($_POST['inIframe']) && ( isset($_SESSION['inIframe']) || isset($_POST['signed_request']) ) )
{
?>
<form name="postJs" action="<?php echo fullurlnav(); ?>" method="post">
<input type="hidden" name="inIframe" value="1">
<?php
// Carry over $_POST
foreach($_POST as $key => $value)
{
echo '<input type="hidden" value="'.$value.'" name="'.$key.'" />';
}
?>
</form>
<script type="text/javascript">
<!--
// If in an iframe
if (top !== self)
{
document.postJs.submit();
}
//-->
</script>
<?php
}
elseif(isset($_POST['inIframe']) && ( isset($_SESSION['inIframe']) || isset($_POST['signed_request']) ) )
{
$_SESSION['inIframe']=1;
}
else
{
$_SESSION['inIframe']=0;
}
if ($_SESSION['inIframe']== 1){
echo 'IS in an Iframe';
}else{
echo 'IS NOT in an Iframe';
}
// echo out rest of your template code
?>
</body>
</html>
It gets a little tricky skating around your page display code output and it's workings, but that's the basic idea i have so far. Technically one could separate the form generation block from the elseif else statements below, and use those above your code before any display output, that may be easier to handle. Note that the above code is untested, just given to provide the basic idea for others with the same issue.

Categories