using a local variable inside a global variable inside a function - php

So, I have this piece of text that I would like to come from elsewhere to inside a function. I put it in "configuration.php" and would like to use in a file "functions.php"
configuration.php
$event_confirmation_message = "Your awesome submission has been approved - $link. ";
functions.php
somefunction(several arguments go here){
//code that does other stuff with the function arguments
//then we need to send the confirmation message
global $event_confirmation_message; //to change, see configuration.php
$link = "http://www." . $city . "events.info/index.php?option=events&main_id=" . $row['main_id'];
mail($email, "Please check your your submission", $event_confirmation_message, "From: contact#me.info");
}
It all works, the mail is sent, the confirmation message arrives, but $link in the email that is sent is blank (empty, non-defined?). So the local variable $link somehow does not get processed within the global variable $event_confirmation_message. Is there something I am doing wrong?

Do like this:
// configuration.php
$event_confirmation_message = "Your awesome submission has been approved - ";
//functions.php
somefunction(several arguments go here){
global $event_confirmation_message;
$link = "http://www." . $city . "events.info/index.php?option=events&main_id=" . $row['main_id'];
$msg = $event_confirmation_message . $link;
mail($email, "Please check your your submission", $msg, "From: contact#me.info");
}

PHP cannot time travel.
$link in your configuration.php will be evaluated/replaced when configuration.php is parsed/loaded. Therefore your $event_confirmation_message will NOT contain a variable anymore when you use the variable elsewhere. It'll contain whatever text was in $link at the time $event... was defined.
This is very much like buying a cake at the store, and wondering why you can't find the egg/flour/milk/sugar that it's made of - all of that was "destroyed" in the bakery and you have just cake...

Related

success.php in my first contact form plugin results in page not found

UPDATE: sorry, thanks for the solutions offered... not really clear how to implement, I think ive not been too clear... if I can understand how to implement the solutions thatd be neat...
Ive also successfully managed to get code working to create a new database table and insert test data but ommited that so its not so complex....
I REALLY want to be able to...
display some content that I can put in success.php (or else where) when the message is sent successfully
that content would say Message Sent - YAY! and then Id like to be able to add, exisiting wp content - some services or products you might be interested in and display them on that same success result page after the message is sent...
maybe there is a better way to redirect users after the message is sent...
then....I also need to save the form data (not yet done) to the new table that I have created (got the table created via plugin), and then display a table of all form submission records in admin panel (not done)
I replaced the content of my main.php file (the plugin's main php file in plugin-name root.
<?php
/** template info etc...
**/
// Find all .php files in the includes dir of my plug in folder.
foreach ( glob( plugin_dir_path( __FILE__ ) . "includes/*.php" ) as $file ) {
include_once $file;
}
?>
and all my files except the main one (which is in the plugin root) are in plugins/plugin-name/includes and are being found - YAY
so my includes/webform.php displays the form nicely it sends an email but I can't get this error or success message via success.php or error.php thing to work.
includes/success.php now looks like this... as per DK's suggestion
<?Php
$Errors = implode(' ', $_SESSION['errMsg']);
echo $Errors; ?>
includes/webform.php now looks like this...
<?php
function d6s_opp_html_form() {
echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
//Form action page is the current url. the form is called by a shortcode that will run functions that are written within this plugin's files, they can be in different files in different folders within the plug in because we have told the plug in to load them in the main plug in file.php horray thay is working..
// other form fields removed to shorten this stakoverflow post
echo '<p>';
echo 'Your Name* <br />';
echo '<input type="text" name="d6s-opp-name" pattern="[a-zA-Z0-9 ]+" value="' . ( isset( $_POST["d6s-opp-name"] ) ? esc_attr( $_POST["d6s-opp-name"] ) : '' ) . '" size="40" placeholder="First & Last name" required />';
// Now using required - is that better than having to check if not empty in success or fail bit????
echo '<p><input type="submit" name="d6s-submitted" value="Send"/></p>';
echo '</form>';
}
//Short code function is here and works GREAT
Then below that in the same file this is the function i figured DK meant that I should put the first part of his solution 1
I Guess this is where I have it wrong still
function deliver_opp_mail() {
// if the submit button is clicked, send the email
if ( isset( $_POST['d6s-submitted'] ) ) {
//sanitise form values so that form data is readable... eg/ if users enter code/script or formatting symbols, it is not missinterpretted as code and is seen as all text.
$name = sanitize_text_field( $_POST["d6s-opp-name"] );
$email = sanitize_email( $_POST["d6s-opp-email"] );
$messagesubject = sanitize_text_field( $_POST["d6s-opp-subject"] );
$messagecontent = esc_textarea( $_POST["d6s-opp-message"] );
$phone = ( $_POST["d6s-opp-phone"] );
// Would like to consider calling form values via global Variables.
$subject = "NEW OPPURTUNITY: $messagesubject";
$d6sdir = plugin_dir_path( __FILE__ );
//Create the Email Body Message using free text and data from the form.
$message = "New Message From: $name \n MESSAGE: $messagecontent \n Return Email: $email \n Return Phone $phone ";
// get the blog administrator's email address, form data is emailed to this email address.
$to = get_option( 'admin_email' );
// Look into setting a to: Email address in WP Admin Console.
$headers = "From: $name <$email>" . "\r\n";
if ( wp_mail( $to, $subject, $message, $headers ) ) {
//maybe this is in the wrong spot, or perhaps this is not the solution I need, but I have tried this in a few different places and can't get it to work..
$Msg = array(
"You have an error",
"Your mail sent succesfully"
);
$_SESSION['errMsg'] = $Msg;
//this take the user to www.mydomain.com/.....wp-content/plugins/my-plugin/includes/success.php - the file is there, but WP theme not found is displayed.
header("Location: $d6sdir/success.php");
exit;
}
}
}
?>
*Dont want to display a message above the form on success or error... future plans for workflow need to take users to a page with no form and other content after they hit submit.
*also using error reporting - seems like something happen or flashes up before the not found from the theme bit is displayed and no other error are reported...
<?Php error_reporting(E_ALL); ini_set('display_errors', 1);
************************** FROM INITAL POST....
Really keen to learn. First post, thanks for help
Purpose of plug in: Create a plugin that I can eventually build into a custom CRM tool for my small business and Learn to code.
*Why is this so not simple...
Solution 1 passing messages to success.php
$Msg = array(
"You have an error",
"Your mail sent succesfully"
);
$_SESSION['errMsg'] = $Msg;
success.php
$Errors = implode(' ', $_SESSION['errMsg']);
echo $Errors;
Solution 2 :
$_SESSION["errMsg"] = "Your mail sent succesfully";
if(isset($_SESSION['errMsg']) AND !empty($_SESSION['errMsg']) ):
echo "<div class='alert danger'>".$_SESSION['errMsg']."</div>";
endif;
Not found solution :
You can use $_SERVER['DOCUMENT_ROOT']; to find root D:/wamp/www
and then full url to page like so :
echo $_SERVER['DOCUMENT_ROOT']."/yourFolder/test.php";
output :D:/wamp/www/yourFolder/test.php
Note : will be nice if you use exit(); right after header("Location:");

Wordpress is executing URL in code when called via wp_mail()

I have written a custom plugin (that creates a custom post type) and allows any user to submit a new post from a form on my website. To prevent bots, I have setup an e-mail confirmation code which they must click, where this changes the post status from Draft to Published.
Unfortunately the wp_mail() code shown below seems to be executing this confirmation URL automatically. As soon as the post is submitted, it is set to Draft until it reaches this code, and then it automatically publishes.
Removing this block however makes everything work as expected. Does anyone have any idea as to the reason and how to fix it?
$confirm_url = site_url(). '/verification?id=' . $post_id . '&hash=' . $hash;
// Send a verification e-mail to the user to confirm publication
$subject = 'Please confirm your Slicer Profile submission';
$body = $confirm_url;
wp_mail( $profile_email, $subject, $body );
This has been resolved, wanted to share the solution for anyone else that may stumble into this themselves. The site_url() was stored in its own variable and the forward slash in the URL string was not properly escaped, which seemed to have been causing the issue.
This has now been updated to the following and works perfect.
$site_url = site_url();
$confirm_url = $site_url. '\/verification?id=' . $post_id . '&hash=' . $hash;
// Send a verification e-mail to the user to confirm publication
$subject = 'Please confirm your Slicer Profile submission';
$body = $confirm_url;
wp_mail( $profile_email, $subject, $body );

Save variable as variable in MYSQL for later use

I have an email template which i am saving in database. My problem is some part of message are variable means these data are coming from current user data.
For Example My Template is
$message="This is test for $username. I am sending mail to $email."
here $username and $email is coming from current users and it is varying from user to user.
So problem is how to save it in database so i can use it as variable on php page later.
anybody have any idea please help me.your help would be appreciated.
If you really need to store whole template in database, you can save it using your own created constants e.g. [USERNAME], [EMAIL] and then in php script just use str_replace() on them.
$messageTemplate = 'This is test for [USERNAME]. I am sending mail to [EMAIL].';
$message = str_replace(array('[USERNAME]', '[EMAIL]'), array($username, $email), $messageTemplate);
But you can also divide this string and concatenate it with variables from database as follows:
$message = 'This is test for ' . $username . '. I am sending mail to ' . $email . '.';
You can use something like this:
$input = "This is test for {username}. I am sending mail to {email}.";
$tokens = array("username" => $username, "email" => $email);
$tmp = $input;
foreach($tokens as $key => $token)
{
$tmp = str_replace("{".$key."}", $token, $tmp);
}
echo $tmp;
The variables in the string will not be evaluated as variables automatically just because you are adding it to your php scope. You need to eval the string in order for the variables to be replaced:
$username = 'test';
$email = 'test#test.com';
$str = "This is a test for $username. I am sending mail to some person $email.";
echo $str. "\n";
// This is a test for $username. I am sending mail to some person $email.
eval("\$str = \"$str\";");
echo $str. "\n";
// This is a test for test. I am sending mail to some person test#test.com.
For more information, see http://php.net/manual/en/function.eval.php

WhileLoop through a mysql db list

Ok so long story short, I have a simple mailto function I want to apply/run for every name on a db list. Since it's not working, I removed all the mail stuff from it and to test to make sure the while loop was working with the db, did this
<?php
$connect2db = mysqli_connect('127.0.0.1','root','pass','dbnamehere');
if(!$connect2db){
die("Sorry but theres a connection to database error" . mysqli_error);
}
$sn_query = "SELECT * FROM email_list";
$sn_queryResult = mysqli_query($connect2db, $sn_query) or die("Sorry but theres a connection to database error" . mysqli_error);
$sn_rowSelect = mysqli_fetch_array($sn_queryResult);
$to = $sn_rowSelect;
?>
<br/><br/>
////lower part on page //////<br/><br/>
<?php
while($sn_rowSelect = mysqli_fetch_array($sn_queryResult) ) {
echo "hello there" . " " . $sn_rowSelect['firstname'] . " <br/>";
}
?>
Now this works, it goess through my db and prints out all my first names from the database list. In my noob brain, id think that if i remove the echo lines, and enter the appropriate mailto information, that it would loop just like before, but send mail to each name. so i did this:
<?php
$sn_query = "SELECT email FROM email_list";
$sn_queryResult = mysqli_query($connect2db, $sn_query) or die("Sorry but theres a connection to database error" . mysqli_error);
$sn_rowSelect = mysqli_fetch_array($sn_queryResult);
$to = implode(",",$sn_rowSelect);
$from = $_POST['sender'];
$subject = $_POST['subj'];
$mssg = $_POST['message'];
$headers = "MIME-Version: 1.0rn";
$headers .= "From: $from\r\n";
$mailstatus = mail($to, $subject, $mssg, $headers);
?>
<br/><br/>
//////////<br/><br/>
<?php
while($sn_rowSelect = mysqli_fetch_array($sn_queryResult) ) {
$mailstatus;
if($mailstatus) {
echo "Success";
}else{
echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid\n";
}
}
?>
now this emails the first name on my list, but not the rest.
I don't get any errors so not sure what the problem is. I was going to try an if statement with num_rows but somewhere else, on StackOverflow, someone said that didn't help since the while loop took care of it by itself. (I tried it either way and it still emailed only the first name) I'm trying here but to no avail.
You have not called the mail() function inside your loop. You call it once outside. Instead try something like the following.
Assuming you have retrieved the $to address from your database query (like you did with the firstname in testing), pull it from the rowset, and use it in mail():
while($sn_rowSelect = mysqli_fetch_array($sn_queryResult) ) {
// Get the $to address:
$to = $sn_rowSelect['email'];
// Call mail() inside the loop.
$mailstatus = mail($to, $subject, $mssg, $headers);
if($mailstatus) {
echo "Success";
}else{
echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid\n";
}
}
Note also, that since you call mysql_fetch_array() at the top of your script, your while loop will start with the second row. You should remove the first call to mysql_fetch_array() that occurs before the loop.
$sn_queryResult = mysqli_query($connect2db, $sn_query) or die("Sorry but theres a connection to database error" . mysqli_error);
// Don't want this...
//$sn_rowSelect = mysqli_fetch_array($sn_queryResult);

PHP mail entire page

I have a page that determines the variable ISSET and then acts on instructions. For example if the isset contains 'print' it loads a file via Include Template Path and echos a code on the bottom that prints the window.
eg.
if (isset($_GET['quoteprint'])) {
include(TEMPLATEPATH . '/bookings/booking-quote.php');
echo'<script type="text/javascript">window.print()</script>';
}
Now I would like a similar function to exist but this time to email the contents of that page to the user. I tired this but it does not work. I think the content needs to be converted but I don't know where to start.
else if (isset($_GET['quoteemail'])) {
$emailer = include(TEMPLATEPATH . '/bookings/booking-quote.php');
$to = $current_user->user_email;
$subject = "Your Quote - Dive The Gap" ;
$message = $emailer;
$headers = "From: Dive The Gap Bookings <ask#divethegap.com>" . "\r\n" .
"Content-type: text/html" . "\r\n";
mail($to, $subject, $message, $headers);
}
Any ideas?
Marvellous
The include function does not return the output or content of the script you're including.
See http://php.net/manual/en/function.include.php for more info (example #4 might be interesting for you).
You need to get the entire content of the page, or the part(s) you'd like to e-mail, into a variable. One way of doing this is using PHP's output buffering. A good explanation of how output buffering works can be found here: http://www.codewalkers.com/c/a/Miscellaneous/PHP-Output-Buffering/

Categories