PHP: Include contents of tile - preserve $_POST variables - php

I've got a script that sends out emails.
It goes through a for loop, where it finds all subscribers, gets their name and sets a POST var with their name in it.
Next I've got a separate PHP file which contains the markup of the email and content.
It has a $_POST['fname'] var which is the users name and needs to be updated dynamically.
The problem is I'm unsure how to grab the contents of my email file (template.php) and add it into the email processing file (bulk_send.php) so that the $_POST['fname'] var can be dynamically updated. Here's the code.
foreach ($emailList as &$value) {
$getSubscriber = mysql_query("SELECT * FROM subscribers WHERE email = '$value' ");
while($row = mysql_fetch_assoc($getSubscriber)){
$_POST['fname'] = $row['fname'];
$_POST['lname'] = $row['lname'];
}
//WHERE IM STUCK
$bodyText = ***INCLUDE template.php .....***
//Code that will send out the email with $bodyText as the body of the email
}
The contents of our template.php is something simple - lets just say something like:
<div><?php echo $_POST['fname')." ".$_POST['lname]; ?></div>
How could I include template.php file appropriately in the Foreach loop above so that the POST vars are updated with each iteration?

You can't quite directly set a variable equal to the contents of another file using include as suggested by Mr.coder in a comment.
You can think of include as copying and pasting the contents of the included file. Based on your template.php, it would be as if your code were:
while($row = mysql_fetch_assoc($getSubscriber)){
$_POST['fname'] = $row['fname'];
$_POST['lname'] = $row['lname'];
}
?><div><?php echo $_POST['fname']." ".$_POST['lname']; ?></div><?php
That would simply dump the div contents out to the browser, which is probably not what you want. Instead, I'd suggest building into your template a function which would create the message text you desire based on parameters fed to the function. Then you would include your template at the top of your page and call the function when needed. It would look more like this:
include('template.php');
foreach ($emailList as &$value) {
$getSubscriber = mysql_query("SELECT * FROM subscribers WHERE email = '$value' ");
while($row = mysql_fetch_assoc($getSubscriber)){
$_POST['fname'] = $row['fname'];
$_POST['lname'] = $row['lname'];
}
//WHERE IM STUCK
$bodyText = makeBodyText($_POST['fname'], $_POST['lname']);
//Code that will send out the email with $bodyText as the body of the email
}
Your template.php would then look something like this:
function makeBodyText($fname, $lname)
{
return '<div>' . $fname .' '. $lname . '</div>';
}
Alternatively, because the included file does operate in the same scope as where it where was called, and because it does support the concept of a return value (thanks to user #kokx for that insight), you could make your template.php like this:
return '<div>' . $_POST['fname'] .' '. $_POST['lname] . '</div>';
And then you could use it as follows:
$bodyText = include 'template.php';
However, that significantly limits the flexibility of template.php. Also, it would potentially output bad information if called directly (from a browser, rather than as an include). So I would not recommend this method.
Now all that aside, it seems odd to me that you are modifying the contents of $_POST. That strikes me (and others) as bad practice.

Related

Using PHP code in the value of a variable

I am trying to send an email in PHP where the content of the email has some conditional checks and some database query lookups.
What I would like to acheive is having my email code as a variable (similar to below) so that I can sent mail() the content to the relevant people.
$emailContent = "<p>My email content</p>";
However the value of this variable would have some code like this:
<table>
<?php
$get_course_units = "SELECT * FROM course_units where course_units.course_code = {$courseCodeExtract}";
$course_units_results = $conn->query($get_course_units);
if ($course_units_results->num_rows > 0) {
while ($courseUnits = $course_units_results->fetch_assoc()) {
?>
<tr>
<td><?php echo $courseUnits["unit_code"]; ?> – <?php echo $courseUnits["unit_name"]; ?> </td>
</tr>
<?php
} //end loop for course units
} //end if for course units
?>
</table>
How should I continue?
Split up your script into an html template file and your php logic.
Use shortcodes in your templates where you want to have custom information and then use str_replace to replace that content with the actual values.
$template_string = file_get_contents('myfile.html');
$shortcodes = array("{{FNAME}}","{{LNAME}}","{{OTHER_STUFF}}");
for(/* all the people you want to mail */){
$custom_info = get_custom_info(/* person */); //eg returns assoc array
$result = $template_string;
foreach($shortcodes as $code){
$result = str_replace($code, $custom_info[$code], $result);
}
//do what you want with result and mail it
}
In the example above, get_custom_info would be returning an associative array with the same values as the shortcodes array, just for convenience.
Now anywhere I put {{FNAME}} in my html, it will be replaced with the value I get back from the custom info function.
You can easily extend this to scrape the template and look for {{ and }} (or whatever shortcode syntax you want) anddetermine what variables you will need from your custom info, shaping the query to only give you what you actually need.
Not sure if this is the best way, but it seems to work pretty well. (also best way is subjective, so might want to ask questions a little differently)

Using CodeIgniter's word_censor() to replace values in a file

I would like to know if this is the best practice with CI or if there is some better way.
In my project I am sending a confirmation email during the registration process. I have a HTML and TXT template. They both consist of something like this:
Hello {USERNAME}, please click on the activation link below to finish the registration. Link: {LINK}
And in my method I open the templates using the file helper and then replace the {} strings with the actual values using the text helper's word_censor() method like this:
$tmpName = '{USERNAME}';
$tmpLink = '{LINK}';
$name = 'Jon' //retrieved from registration from
$link = 'mysite.com/activate/239dwd01039dasd' //runs the activate function providing the unique ID as an argument
$template = word_censor($template, $tmpName, $name);
$template = word_censor($template, $tmpLink, $link);
return $template
Then I just take the $template and put it inside the CI's mail helper like this:
$this->email->message($template);
What I would like to know is if this is the best way to replace contents of html/txt files with my own values or if there is any better and more efficient way to achieve the same result. I just don't like that I am using the word_censor() function to do something other than what it was intended for..
The better way is to store the email template as a view file.
view
Hello <?php echo $username; ?>, please click on the activation link below to finish the registration. Link: <?php echo $link; ?>
Controller
$data['username'] = 'Jon';
$data['link'] = 'mysite.com/activate/239dwd01039dasd';
$email_template = $this->load->view('myfile', $data, true);
$this->email->message($email_template);
Setting the third parameter on view() to true will return the template rather then echo it out.

Receiving JQuery $.post data and returning specific results with PHP

I'm trying to make a dynamic website on a single webpage and I'm almost there. All that's left is to do some php coding.
Here is a few lines of code from my "index.php"
$('.open').click(function(){
current = $(this).html();
$.post("source.php", {name: current}, function(src){
$('#codeBox').html(src);
});
});
How do I check the value of "current" in my php file and return data specific to the link I click on?
Simply check the POST parameters :
$name = $_POST['name'];
Don't forget to sanitize your inputs.
What's the content of you .open element ? Maybe it would be preferable to check the element's id, compare the html make me surprising.
$val = $_POST["name"];
$a = array();
switch($val) {
case 'some val':
$a['something'] = "something else";
print json_encode($a);
break;
...
}
<?PHP
// $_POST['name'], this will give you the value of name in the php file
echo $_POST['name']; // this will output it
?>
Try this
$current = $_POST["name"];
using $current you can return the data conditionally.

How do I place a unique ID in my PHP confirmation page?

I have a PHP script that emails me the results from a form that generates a unique ID number. The PHP script executes a confirmation page. I'm trying to place the unique ID on the confirmation page: quote_confirm.php. I already tried this in the conformation page:
<?php
$prefix = 'LPFQ';
$uniqid = $prefix . uniqid();
$QuoteID = strtoupper($uniqid);
."<tr><td class=\"label\"><strong>Quote ID:</strong></td><td>".$QuoteID."</td></tr>\n"
First off, uniqid() has a prefix parameter, so your line $uniqid = $prefix . uniqid(); should actually be $uniqid = uniqid($prefix);
Also, are you receiving an error? What is the output?
From what I can understand it is something like this:
form -> mail + output page
So there is mail()-like function and after that some output.
If the variable($uniqid) is set you have to make sure it's not overwritten or unset by something else before the actual output. You have to also check the scope of variable.
There is no mistake in the code you posted.
But speaking of style:
I also recommend using using $uniqid = uniqid($prefix) instead of $uniqid = $prefix. uniqid();.
And the following line is strange:
."<tr><td class=\"label\"><strong>Quote ID:</strong></td><td>".$QuoteID."</td></tr>\n"
Write it as "<tr><td class=\"label\"><strong>Quote ID:</strong></td><td>$QuoteID</td></tr>\n" (if you insist on using "") and if the function is echo (example: echo $something not $content .= $something) use , instead of . .
Full example:
echo 'Constant text without variables', $variable, "String with a $variable and a newline \n";

Get user input from form, write to text file using php

As part of a subscriber acquisition I am looking to grab user entered data from a html form and write it to a tab delimited text file using php.The data written needs to be separated by tabs and appended below other data.
After clicking subscribe on the form I would like it to remove the form and display a small message like "thanks for subscribing" in the div.
This will be on a wordpress blog and contained within a popup.
Below are the specific details. Any help is much appreciated.
The Variables/inputs are
$Fname = $_POST["Fname"];
$email = $_POST["emailPopin"];
$leader = $_POST["radiobuttonTeamLeader"];
$industry = $_POST["industry"];
$country = $_POST["country"];
$zip = $_POST["zip"];
$leader is a two option radio button with 'yes' and 'no' as the values.
$country is a drop down with 40 or so countries.
All other values are text inputs.
I have all the basic form code done and ready except action, all I really need to know how to do is:
How to write to a tab delimited text file using php and swap out the form after submitting with a thank you message?
Thanks again for all the help.
// the name of the file you're writing to
$myFile = "data.txt";
// opens the file for appending (file must already exist)
$fh = fopen($myFile, 'a');
// Makes a CSV list of your post data
$comma_delmited_list = implode(",", $_POST) . "\n";
// Write to the file
fwrite($fh, $comma_delmited_list);
// You're done
fclose($fh);
replace the , in the impode with \t for tabs
Open file in append mode
$fp = fopen('./myfile.dat', "a+");
And put all your data there, tab separated. Use new line at the end.
fwrite($fp, $variable1."\t".$variable2."\t".$variable3."\r\n");
Close your file
fclose($fp);
// format the data
$data = $Fname . "\t" . $email . "\t" . $leader ."\t" . $industry . "\t" . $country . "\t" . $zip;
// write the data to the file
file_put_contents('/path/to/your/file.txt', $data, FILE_APPEND);
// send the user to the new page
header("Location: http://path/to/your/thankyou/page.html");
exit();
By using the header() function to redirect the browser you avoid problems with the user reloading the page and resubmitting their data.
To swap out the form is relatively easy. Make sure you set the action of the form to the same page. Just wrap the form inside a "if (!isset($_POST['Fname']))" condition. Put whatever content you want to show after the form has been posted inside the "else{}" part. So, if the form is posted, the content in the "else" clause will be shown; if the form isn't posted, the content of the "if (!isset($_POST['Fname']))", which is the form itself will be shown. You don't need another file to make it work.
To write the POSTed values in a text file, just follow any of the methods other people have mentioned above.
This is the best example with fwrite() you can use only 3 parameters at most but by appending a "." you can use as much variables as you want.
if isset($_POST['submit']){
$Fname = $_POST["Fname"];
$email = $_POST["emailPopin"];
$leader = $_POST["radiobuttonTeamLeader"];
$industry = $_POST["industry"];
$country = $_POST["country"];
$zip = $_POST["zip"];
$openFile = fopen("myfile.ext",'a');
$data = "\t"."{$Fname}";
$data .= "\t"."{$email}";
$data .= "\t"."{$leader}";
$data .= "\t"."{$industry}";
$data .= "\t"."{$country}";
$data .= "\t"."{$zip}";
fwrite($openFile,$data);
fclose($openFile);
}
Very very simple:
Form data will be collected and stored in $var
data in $var will be written to filename.txt
\n will add a new line.
File Append Disallows to overwrite the file
<?php
$var = $_POST['fieldname'];
file_put_contents("filename.txt", $var . "\n", FILE_APPEND);
exit();
?>

Categories