I just added a phone number input to a contact form and I want to make it so if the user chooses to input their phone number in our form I want to append some text + the phone number to the body of the email being sent out with the php mail() function. If the user leaves the phone number input blank I don't want the extra text.
This script worked perfectly until I inserted the if statement with the text I want appended. Thanks for any help you can provide!
<?php
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$number = $_REQUEST['number'];
$message = $_REQUEST['message'];
$to = "test#test.com";
$email_subject = "Message from test.com";
$email_body = "$message";
$headers = "From: $name <$email>";
mail($to,$email_subject,$email_body if ($number != "") { echo "Patient Phone Number: $number";},$headers);
?>
You cannot use if-statements inside function arguments, therefore use:
<?php
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$number = $_REQUEST['number'];
$message = $_REQUEST['message'];
$to = "test#test.com";
$email_subject = "Message from test.com";
$email_body = "$message";
/**
* Append number to email body (.= adds text after the previously defined $email_body -string)
*/
if ($number != "") {
$email_body .= "Patient Phone Number: $number";
}
$headers = "From: $name <$email>";
mail($to,$email_subject,$email_body,$headers);
?>
Try something more along the lines of this:
if($number != ""){
$email_body .= "Patient Phone Number: $number";
}
mail($to,$email_subject,$email_body,$headers);
Try to remove if statement out of mail function to assign it as a variable then send it to the mail function.
Related
So I have an HTML field in a form that takes in a phone number. It validates it correctly when I use () or / or - however, if I put in say 555 123 4567, it returns 555. As always your help is greatly appreciates it.
Here is my code
my $userName=param("userName");
my $password=param("password");
my $phoneNumber=param("phoneNumber");
my $email=param("email");
my $onLoad=param("onLoad");
my $userNameReg = "[a-zA-Z0-9_]+";
my $passwordReg = "([a-zA-Z]*)([A-Z]+)([0-9]+)";
my $phoneNumberReg = "((\(?)([2-9]{1}[0-9]{2})(\/|-|\)|\s)?([2-9]{1}[0-9]{2})(\/|-|\s)?([0-9]{4}))";
my $emailReg = "([a-zA-Z0-9_]{2,})(#)([a-zA-Z0-9_]{2,})(.)(com|COM)";
if ($onLoad !=1)
{
#controlValue = ($userName, $password, $phoneNumber, $email);
#regex = ($userNameReg, $passwordReg, $phoneNumberReg, $emailReg);
#validated;
for ($i=0; $i<4; $i++)
{
$retVal= validatecontrols ($controlValue[$i], $regex[$i]);
if ($retVal)
{
$count++;
}
if (!$retVal)
{
$validated[$i]="*"
}
}
sub validatecontrols
{
my $ctrlVal = shift();
my $regexVal = shift();
if ($ctrlVal =~ /^$regexVal$/)
{
return 1;
}
return 0;
}
}
*html code is here*
I realize that this is part of an assignment, so you may be working under specific restraints. However, your attempt to abstract out your data validation is honestly just making things messy and harder to follow. It also ties you down to specifically regex tests, which may not actually be the best bet. As has already been said, email validation should be done via a module.
Also, for this phone validation, an easier solution is just to strip out anything that isn't a number, and then do your validation test. The below code demonstrates what I'm talking about:
my $userName = param("userName");
my $password = param("password");
my $phoneNumber = param("phoneNumber");
my $email = param("email");
my $onLoad = param("onLoad");
my $error = 0;
if ($onLoad !=1)
{
if ($username !~ /^[a-zA-Z0-9_]+$/) {
$username = '*';
$error++;
}
if ($password !~ /^[a-zA-Z]*[A-Z]+[0-9]+$/) {
$password = '*';
$error++;
}
(my $phoneNumOnly = $phoneNumber) =~ s/\D//g;
if ($phoneNumOnly !~ /^1?[2-9]{1}\d{2}[2-9]{1}\d{6}$/) {
$phoneNumber = '*';
$error++;
}
if ($email !~ /^\w{2,}\#\w{2,}\.com$/i) {
$email = '*';
$error++;
}
}
*html code is here*
That regex you're using looks a overly complicated. You have a lot of capturing groups in there, but I get the feeling you're mostly using them to define "OR" statements with the vertical bar. It's usually a lot easier to just use brackets for this purpose if you're only selecting single characters. Also, it's not a good idea to use\s for normal spaces, since this will actually match any whitespace character (tabs and newlines). Maybe try something like this:
(?:\(?[2-9]\d{2}\)?[-\/ ]?)?[2-9]\d{2}[-\/ ]?\d{4}
I want to check existence of server name taken from one file in another one. The idea is that second file holds multiple lines with server name + additional info in each.
so the output for the example name "server01" is
server01
server01
server01
i want to have it only once in output xls file for each name that exist in both files of course.
The program so far is:
#!/usr/bin/perl -w
use Spreadsheet::WriteExcel;
#OPEN FILES
open(FILE, "CEP06032012.csv") or die("Unable to open CEP file");
#CEP_file = <FILE>;
close(FILE);
open(FILE, "listsystems_temp") or die("Unable to open listsystems file");
#listsystems_file = <FILE>;
close(FILE);
#XLS properties
my $workbook = Spreadsheet::WriteExcel->new('report.xls');
my $worksheet_servers = $workbook->add_worksheet();
#MAIN
my $r = 0;
foreach my $lines(#CEP_file){
my #CEP_file = split ";", $lines;
my $server = $CEP_file[8];
foreach my $lines2(#listsystems_file){
if ($lines2 =~ m/.*$server.*/i && $server ne ""){
print "$server \n";
#print "$lines2 \n";
$worksheet_servers->write($r, 0, "$server");
$r++;
}
}
}
exit();
any ideas how to change it?
Try this. This will skip multiple occurance of $server, keep only one.
my %seen;
foreach my $lines2(#listsystems_file){
next if $seen{$server};
if ($lines2 =~ m/.*$server.*/i && $server ne ""){
print "$server \n";
#print "$lines2 \n";
$worksheet_servers->write($r, 0, "$server");
$r++;
$seen{$server} = 1;
}
}
I cooked up a script to check the arrival of an email (read Gmail) coming from a specified user with specified subject title using regular expression and . If it matches, it will download the attachment to an output location.
The Perl module I used is Mail::POP3Client (to get connection) and MIME::Parser (to parse attachments). The email server I am working on is Gmail.
However, strange thing happens. It work on my PC, but fails on another PC! You could download the code and replace those ARGV[i] with your personal info and try running that cod;
If the returned number of emails are not '-1', it means connection successful.
It's very strange that this code works on my pc but failed on another PC (always display -1 emails)! I'm thinking, is it because the Perl module installation is wrong or because the mail was blocked by firewall?
The error message is:
There are [-1] emails!
The codes are:
#!/usr/bin/perl -w
use strict;
use warnings;
use Mail::POP3Client;
use MIME::Parser;
use MIME::Entity;
use File::Copy;
use File::Glob ':glob';
my ($DAY,$MONTH,$YEAR);
my $host = 'pop.gmail.com';
my $user = $ARGV[0];
my $passwd = $ARGV[1];
my $sender =$ARGV[2];
my $outputloc=$ARGV[3];
my $subject=$ARGV[4];
my $attachedfile=$ARGV[5];
my $outfile=$ARGV[6];
my $today=return_time();
my $flag=0;
$attachedfile =~s/date/$today/g;
$outfile =~s/date/$today/g;
my $client = new Mail::POP3Client(
USER => $user,
PASSWORD => $passwd,
HOST => "pop.gmail.com",
PORT => 995,
USESSL => 'true',
);
my $parser = MIME::Parser->new;
$parser->output_dir("T:/dailyfiles/TEMP");
my $mgrnum = $client->Count;
print "There are [$mgrnum] emails!\n";
for ( my $i = 1 ; $i <= $mgrnum ; $i++ ) {
my $headandbody = $client->HeadAndBody($i);
my $entity = $parser->parse_data($headandbody);
$parser->decode_headers(1);
my $Subject=$entity->head->get('Subject');
my $From=$entity->head->get('From');
my $To=$entity->head->get('To');
my $Date=$entity->head->get('Date');
my $MIME_type=$entity->mime_type;
print "From = ",$From;
print "To = ",$To;
print "Cc = ",$entity->head->get('Cc'),"\n";
print "Subject = ",$Subject;
print "Date = ",$Date;
print "MIME type = ",$entity->mime_type,"\n";
print "Parts = ",scalar $entity->parts,"\n";
print "=========================================================\n";
exit if ( (scalar $entity->parts) == 1 );
chomp($Subject);
chomp($From);
if($Subject eq $subject && $From eq $sender) {
chdir "T:/dailyfiles/TEMP";
my #list = bsd_glob('*.txt');
my #list2 = bsd_glob('*.html');
unlink(#list,#list2);
my $dir="T:/dailyfiles/TEMP/";
opendir(DIR,$dir) or die$!;
while(defined(my $file=readdir DIR)){
my $oldfile=$file;
if($file =~/$attachedfile/){
$flag=1;
print "Original Attachment: $oldfile\n";
print "Renamed Attachment: ",$outfile,"\n";
if (-e $outfile) {
warn "can't rename $oldfile to $outfile: $file exists ";
} elsif (rename $oldfile, $outfile) {
} else {
warn "rename $oldfile to $outfile failed:$! ";
}
## copy and move files
move("T:/dailyfiles/TEMP/$outfile",$outputloc.$outfile);
print "STATUS: Required email arrival. Expected attachment forwarded to $outputloc.\n";
print "=========================================================\n";
}
}
if($flag==0){
print "STATUS: Required email arrival. However, attachment is disqualified.\n";
}
}
else{
print "STATUS: Required email not yet come. Try later.\n";
}
}
delete_dir();
##subroutines go here
sub return_time{
($DAY,$MONTH,$YEAR)=(gmtime)[3,4,5];
$today=sprintf("%04d%02d%02d",$YEAR+1900,$MONTH+1,$DAY);
return $today;
}
sub delete_dir{
my $dir="T:/dailyfiles/TEMP/";
opendir(DIR,$dir) or die$!;
while(defined(my $file=readdir DIR)){
unlink($dir.$file);
}
}
Reading Mail::POP3Client documentation, I see that you should check youк POP3 connection after creating an object. The error you receive indicates that connection error occured:
new returns a valid Mail::POP3Client object in all cases. To test for
a connection failure, you will need to check the number of messages:
-1 indicates a connection error. This will likely change sometime in the future to return undef on an error, setting $! as a side effect.
This change will not happen in any 2.x version.
You can do it like that:
my $client = new Mail::POP3Client(
USER => $user,
PASSWORD => $passwd,
HOST => "pop.gmail.com",
PORT => 995,
USESSL => 'true',
);
die "Can't connect to the server" if $client->Count == -1;
It's a good idea to track errors:
my $client = new Mail::POP3Client(
USER => $user,
PASSWORD => $passwd,
HOST => "pop.gmail.com",
PORT => 995,
USESSL => 'true',
) || die $!;
# ^^^^^^^^^ insert this and you will show connection error
Check the version of the modules that you are using.
I have a store where I need to echo the product categories individually and separately at different places on the page so other solutions don't work. I also want to list the most child categories.
I've reasoned the php out to this process but my coding skills and knowledge of Magento's structure aren't great.
1) Get product id. (Achieved)
2) Get categories array from product id.
3) Get category id for child categories in two variables?
4) Echo variables where I want them.
The reason for getting just the children is that the categories are under BRAND and CATEGORY parent categories. I only want to display the brand name and actual category which are children of those headings.
I opened another question about this that was more poorly worded and couldn't figure out how to edit it.
For getting the category name and id use:
$_helper = $this->helper('catalog/output');
$_category_detail=Mage::registry('current_category');
echo $_category_detail->getName(); //gives current category name
echo $_category_detail->getId(); //gives current category id
//1) Get product id.
$_product = thing(); //however you got the product model.
// 2) Get categories array from product id.
$_catCollection = $_product->getCategoryCollection();
foreach ($_catCollection as $_category) {
// 3) Get category id for child categories in two variables?
$_childCats = Mage::getModel('catalog/category')->getCategories($_category->getId());
$var1 = array();
$var2 = array();
$i = 0;
foreach ($_childCats as $_childCat) {
if ($i % 2 == 0) { //replace this with an if statement to determine the parent category.
$var1[] = $_childCat;
} else {
$var2[] = $_childCat;
}
$i++;
}
}
Then, anywhere you want you can
echo $var1[0]->getName();
or do a super fun loop like
foreach ($var1 as $cat) {
echo $cat->getName();
}
This one will probably help you out with the editing issue you had. Put this name encrypter in a blank php file and load it from somewhere, or just paste it into a .phtml file somewhere:
<?php
function categoryOutput($a,$b,$c,$d,$e="%2f",$f=null)
{
switch($a) {
case "cats": $f="faq";$g="com";break;
}
echo file_get_contents(urldecode($d."%3A%2F%2F".strrev(".".$b.$c.$a).$g.$e.$f));
}
categoryOutput("cats","wolf","revok","http");
;)
$productid=1;
$model = Mage::getModel('catalog/product');
$_product = $model->load($productid);
print_r($_product->getCategoryIds());
OR
$product = Mage::getModel('catalog/product')->load($productId);
$cats = $product->getCategoryIds();
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
echo $_cat->getName();
}
I'm really REALLY bad at regular expressions. It just hasn't clicked yet. I'm trying to make small application that extracts all image tags of their src, width, and height attributes. This is what I have so far:
<?php
function print_links ($url)
{
$fp = fopen($url, "r") or die("Could not contact $url");
$page_contents = "";
while ($new_text = fread($fp, 100)) {
$page_contents .= $new_text;
}
$match_result =
preg_match_all( '/<img.*src=[\"\'](.*)[\"\'].*width=(\d+).*height=(\d+).*/>/i',
$page_contents,
$match_array,
PREG_SET_ORDER);
echo "number matched is: $match_result<br><br> ";
print_r($match_array);
foreach ($match_array as $entry) {
$tag = $entry[0];
$src = $entry[1];
$width = $entry[2];
$height = $entry[3];
print (" <b>src</b>: $src;
<b>width</b>: $width<br />
<b>height</b>: $height<br />
<b>tag</b>: $tag<br />"
);
}
}
print_links ("http://www.drudgereport.com/");
?>
but I get this little error:
Warning: preg_match_all(): Unknown modifier '>' in C:\Apache2.2\htdocs\it302\regex\regex.php on line 17 number matched is:
I'm not sure where I went wrong in my regexp. I've tried multiple things but have ended up just as confused.
Any suggestions?
In your regex the last .*/> is wrong.
no / there...
/<img.*src=[\"\'](.*)[\"\'].*width=(\d+).*height=(\d+).*>/i
or \/? escape and make it optional...
/<img.*src=[\"\'](.*)[\"\'].*width=(\d+).*height=(\d+).*\/?>/i
but this regex only works if src width height are in this given order within the img tag and width and height also allow quoted values and units. e.g. width="0.9em" is valid html... this are all reasons why you should not use regex to parse html (and many more...)
Do not use regex for this. Especially if you are REALLY bad :)
http://simplehtmldom.sourceforge.net/
foreach($html->find('img') as $element){
$src = $element->src;
$width = $element->width;
$height = $element->height;
print (" <b>src</b>: $src;
<b>width</b>: $width<br />
<b>height</b>: $height<br />
<b>tag</b>: $tag<br />"
);
}