How to use image as value for radio button

I have created a form in html and images with radio button. For example in gender=>Male, instead of writing word Male, I have used a small male picture. I want this male picture to go in email when the user submits the form. I don't know if this can be done in php. Secondly I am a novice in php.

Please help me and all the thanks in advance.

Regards
Saxena
S SaxenaWitageAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Olaf DoschkeSoftware DeveloperCommented:
1. The radio button HTML part:
There is no image radio button, but you can simply use a radio button without a caption/label and then add an image tag,

2. The PHP form submit/process and create mail part:
Well, any HTML form will never submit an image, all you get is a $_POST or $_GET array with submitted values, you build up the mail HTML in the same way as the HTML form.
Depending on what you get for that gender radio button you render a male or female image into the mail HTML body.

Look at this: http://phpfiddle.org/lite/code/7rmy-gmk5

Bye, Olaf.
1
Dave BaldwinFixer of ProblemsCommented:
HTML forms can only submit (GET or POST) text data.  You can interpret the text to send an image in your server side code which I guess will be PHP.  However, you should know that many email clients block external images until the recipient oks them.
0
Julian HansenCommented:
This is an HTML problem not a PHP one. To build a radio image can be done very simply with html and CSS. What you need however are images that represent both the on and the off state.
The CSS would look something like this
<style type="text/css">
input[type="radio"] {
  display: none;
}
.icon {
  width: 30px;
  height: 30px;
  background-image: url(images/t2780.sprite.png);
  background-repeat: no-repeat;
}
.icon:hover {
	cursor:pointer;
}
.icon.female {
  background-position: 0 -60px;
}
input:checked + .icon.male {
  background-position: 0 -30px;
}
input:checked + .icon.female {
  background-position: 0 -90px;
}
</style>

Open in new window

HTML
  <input type="radio" name="gender" id="male" value="male">
  <label for="male" class="icon male"></label>
  <input type="radio" name="gender" id="female" value="female">
  <label for="female" class="icon female"></label>

Open in new window

Sample sprite
t2780.sprite.pngWorking sample here
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Misty CorningCommented:
Would I be able to just have them labeled instead of pictures?  I needed female and male for gender (the form I sent)
0
Misty CorningCommented:
So I have to have an image set to each of the fields, correct?  It all depends on what image I have set them to?  That's how I'm understanding it.
0
NerdsOfTechTechnology ScientistCommented:
The 'value' parameter can be anything you want it to be: e.g. instead of male and female, it can be gentleman and lady, if they choose either male or female respectively. You can have text next to the radio button as a caption as well:

Gender:<br>
Male:&nbsp;<input type="radio" name="gender" id="male" value="gentleman">
<label for="male" class="icon male"></label>
&nbsp;&nbsp;
Female:&nbsp;<input type="radio" name="gender" id="female" value="lady">
<label for="female" class="icon female"></label>

Open in new window


On your server-side processing script you would get the values of the form and the name.

<?php
echo 'gender: ' . htmlspecialchars($_GET["gender"]); //outputs gentleman for male selection; lady for female selection
?>
0
Misty CorningCommented:
Thank you; however, I meant to "hide" the radio button.  I was able to get the caption next to the buttons.  Does it have to be an image in order to do this?
0
NerdsOfTechTechnology ScientistCommented:
Use CSS from Julian Hansen to hide the button, namely:
<style>
input[type="radio"] {
  display: none;
}
</style>

Open in new window

see #a42355323
0
S SaxenaWitageAuthor Commented:
Thanks Olaf,

I am just trying this solution. I am sure that it will work. I will write again after trying in case I get any problem.

Regards
Saxena
0
NerdsOfTechTechnology ScientistCommented:
Here's another minimal HTML/CSS solution which uses CDN based icons from FontAwesome

<html>
<body>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
.container {
    display: inline;
    position: relative;
    cursor: pointer;
    font-size: 22px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.container input ~ .checkmark {
	padding: 5px;
}

/* pink hover over female */
.container:hover input ~ .fa-female,
.container input:checked ~ .fa-female {
    background-color: #FCC;
}

/* light blue hover over male */
.container:hover input ~ .fa-male, 
.container input:checked ~ .fa-male
{
    background-color: #CCF;
}

</style>

<form>
<label class="container">
<input type="radio" name="gender" value="female" style="display: none" />
<i class="checkmark fa fa-female fa-fw" aria-hidden="true"></i>
</label>
<label class="container">
<input type="radio" name="gender" value="male" style="display: none" />
<i class="checkmark fa fa-male fa-fw" aria-hidden="true"></i>
</label>
</form>
</body>
</html>

Open in new window


https://jsfiddle.net/ehggpjs1/1/

http://fontawesome.io/icons/
0
Julian HansenCommented:
Does it have to be an image in order to do this?
No it can be text but your original question was about if you could make it a picture instead of text so we seem to be going around in circles a bit.
With reference to your opening question do you want to use pictures or not?
0
S SaxenaWitageAuthor Commented:
Hello Olaf,

Following is my php. As you can see that I am using table so that I get the form in tabular format. Do you want me to add your code in place of  ".$_POST['grade']." ?
Regards
Saxena

<?php
/**
* Simple example script using PHPMailer with exceptions enabled
* @package phpmailer
* @version $Id$
*/

require 'class.phpmailer.php';

try {
$mail = new PHPMailer(true); //New instance, with exceptions enabled

$to = "emailAddrss@domain.com";
$mail->AddAddress($to);
$mail->From = $_POST['email'];
$mail->FromName = $_POST['name'];
$mail->Subject = "Contact Form";

$body = "<table>
<tr>
<th colspan='2'>Contact Form</th>
</tr>

<tr>
<td style='font-weight:bold'>Full Name:</td>
<td>".$_POST['name']."</td>
</tr>

<tr>
<td style='font-weight:bold'>E-Mail:</td>
<td>".$_POST['email']."</td>
</tr>

<tr>
<td style='font-weight:bold'>Mobile:</td>
<td>".$_POST['mobile_number']."</td>
</tr>

<tr>
<td style='font-weight:bold'>Age:</td>
<td>".$_POST['age']."</td>
</tr>

<tr>
<td style='font-weight:bold'>City: </td>
<td>".$_POST['city']."</td>
</tr>

<tr>
<td style='font-weight:bold'>Select Method: </td>
<td>".$_POST['method']."</td>
</tr>

<tr>
<td style='font-weight:bold'>Grade of Baldness: </td>
<td>".$_POST['grade']."</td>
</tr>

<table>";

$body = preg_replace('/\\\\/','', $body); //Strip backslashes
$mail->MsgHTML($body);

$mail->IsSMTP(); // tell the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP server port
//$mail->Host = "saxena@aspirehairrestoration.com"; // SMTP server
//$mail->Username = "name@domain.com"; // SMTP server username
//$mail->Password = "password"; // SMTP server password

$mail->IsSendmail(); // tell the class to use Sendmail
$mail->AddReplyTo("saxena@aspirehairrestoration.com");
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->WordWrap = 80; // set word wrap
 

$mail->IsHTML(true); // send as HTML
$mail->Send();
echo 'Thank You. Your form has been submitted. Please check your mail for details.';
} catch (phpmailerException $e) {
echo $e->errorMessage();
}


?>
0
NerdsOfTechTechnology ScientistCommented:
You just add another cell for 'gender' of course :)

see lines 59-62

Warning: it looks like you are using raw inputs and can be susceptible to a cross-side scripting attack AKA a XSS attack. Make sure you sanitize the inputs before outputting them.

<?php
/**
* Simple example script using PHPMailer with exceptions enabled
* @package phpmailer
* @version $Id$
*/

require 'class.phpmailer.php';

try {
$mail = new PHPMailer(true); //New instance, with exceptions enabled

$to = "saxena@aspirehairrestoration.com";
$mail->AddAddress($to);
$mail->From = $_POST['email'];
$mail->FromName = $_POST['name'];
$mail->Subject = "Contact Form";

$body = "<table>
<tr>
<th colspan='2'>Contact Form</th>
</tr>

<tr>
<td style='font-weight:bold'>Full Name:</td>
<td>".$_POST['name']."</td>
</tr>

<tr>
<td style='font-weight:bold'>E-Mail:</td>
<td>".$_POST['email']."</td>
</tr>

<tr>
<td style='font-weight:bold'>Mobile:</td>
<td>".$_POST['mobile_number']."</td>
</tr>

<tr>
<td style='font-weight:bold'>Age:</td>
<td>".$_POST['age']."</td>
</tr>

<tr>
<td style='font-weight:bold'>City: </td>
<td>".$_POST['city']."</td>
</tr>

<tr>
<td style='font-weight:bold'>Select Method: </td>
<td>".$_POST['method']."</td>
</tr>

<tr>
<td style='font-weight:bold'>Grade of Baldness: </td>
<td>".$_POST['grade']."</td>
</tr>

<tr>
<td style='font-weight:bold'>Gender: </td>
<td>".$_POST['gender']."</td>
</tr>

<table>";

$body = preg_replace('/\\\\/','', $body); //Strip backslashes
$mail->MsgHTML($body);

$mail->IsSMTP(); // tell the class to use SMTP
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP server port
//$mail->Host = "saxena@aspirehairrestoration.com"; // SMTP server
//$mail->Username = "name@domain.com"; // SMTP server username
//$mail->Password = "password"; // SMTP server password

$mail->IsSendmail(); // tell the class to use Sendmail
$mail->AddReplyTo("saxena@aspirehairrestoration.com");
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->WordWrap = 80; // set word wrap
  

$mail->IsHTML(true); // send as HTML
$mail->Send();
echo 'Thank You. Your form has been submitted. Please check your mail for details.';
} catch (phpmailerException $e) {
echo $e->errorMessage();
}


?>

Open in new window

0
Olaf DoschkeSoftware DeveloperCommented:
Do you want me to add your code in place of  ".$_POST['grade']." ?
You said you want the male (or female) picture in the mail, that would need the echo of the mail or female picture as src of an img tag.

I needed female and male for gender (the form I sent)

You only want the word male or female, then all you need to put in is another block of code you already have for all the other fields...

<tr>
<td style='font-weight:bold'>Gender:</td>
<td>".$_POST['gender']."</td>
</tr>

Open in new window


The way radio inputs work is:
1. You create multiple input items with same name, notice I made two inputs:
<input type="radio" name="gender" value="male">
<input type="radio" name="gender" value="female">

Open in new window

What you get in $_POST('gender') then is either nothing (if no gender was selected) or "male" or "female", those possible values of  $_POST['gender'] simply come from the values of the input.

The type "radio" means a group of options, of which a selection automatically unchecks previous selection of the same group, and the group of options is defined via naming several inputs with the same name, here 'gender'. That's becoming the name or key of the $_POST[] array element, that is $_POST['gender']. And the value of the value attribute of the input tag becomes the value of $_POST['gender']. It's that simple and straight forward. Since an attribute of an HTML tag can only be a text, you only get text

Therefore the part of my code showing your choice - the switch statement - is echoing an img tag with the same image as was shown to the user for the mail or female radio button. What the user actually picks is not the image, but he selects the input radio with its value and that is sent.

Julian has shown you a way to have the input as image instead of the radio button. He removes the radio button itself via CSS:
input[type="radio"] {
  display: none;
}

Open in new window


Like me, he also choose to set the values of the inputs to "male" and "female", so aside of another visual representation of the form, it still just sends over the values "male" or "female" to the script processing the form submit via the $_POST variable. That's all there is to it. Besides that he uses the possibility to display just a part of an image, which may be over your head of understanding HTML.

Your mail creation code produces HTML, you mainly do one big multi-line assignment of an HTML string to the $body variable. To put in an image there, you need a section with an <img> tag. So take a look at my code. I used some publicly available image URL for source, you will use your image as a URL to your servers image directory or subdomain, or wherever you have your pictures on your site. That the way you put images in HTML, as a img tag or "command" to display that image.

The difference of just displaying the word within $_POST['gender'] or a corresponding image within a table cell (td), is this:
<td>".$_POST['gender']."</td> => <td>male</td>
<td><img src='/yourimagesdirectory/".$_POST['gender'].".jpg'></td> => <td><img src='/yourimagesdiectory/male.jpg'></td>

Open in new window

You just need to take care, that you have jpg filesnames male.jpg and female.jg in http://yourdoamin.com/yourimagefolder.

Anyway, my code tells you the mapping can be any file name and URL, the switch just does one of the echos depending on which value $_POST['gender'] has, using the words male and female as file names is just the simplest option. As you can see the images might even come from elsewhere.

Bye, Olaf.
1
S SaxenaWitageAuthor Commented:
Thanks Olaf,

Sorry for the delayed reply as I was little engaged with Julian, who really has helped me a lot. I tried the solution you gave me initially but I am not getting the images. My html and php is as follows:

<form name="contactForm" action="php/email_handler.php" method="POST">
    <table>
<tbody>
<tr>
<th>Grade of Baldness*:</th>
<td><input id="bald" class="form-control" name="grade"  required type="radio" value="2" required/>2<img 

src="http://www.aspirehairrestoration.com/wp-content/uploads/2011/09/grade_2.png" alt="no image"></td>
<td><input class="form-control" name="grade" value="3" required type="radio"/>3<img 

src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_3.png" alt="no image"></td>
<td><input class="form-control" name="grade"  required type="radio" value="4"/>4<img 

src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_4.png" alt="no image"></td>
<td><input class="form-control" name="grade" required="" type="radio" value="5"/>5<img 

src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_5.png" alt="no image"></td>
<td><input class="form-control" name="grade" required="" type="radio"value="6"/>6<img 

src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_6.png" alt="no image"></td>
<td><input class="form-control" name="grade" required="" type="radio" value="7"/>7<img 

src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_7.png" alt="no image"></td>
</tr>
</tbody>
</table>
    <input class="button" type="submit" value="Calculate" />
</form>
<?php 
echo "grade:";
switch (isset($_POST['grade']) ? $_POST['grade'] : 'none')
{
    case '2':
    echo('<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2011/09/grade_2.png">');
    break;
    case '3':
    echo('<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_3.png">');
    break;
    case '4':
    echo('<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_4.png">');
    break;
    case '5':
    echo('<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_5.png">');
    break;
    case '6':
    echo('<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_6.png">');
    break;
    case '7':
    echo('<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_7.png">');
}
?>

Open in new window

0
Julian HansenCommented:
Can you explain what you expected the script in your last post to do.
0
S SaxenaWitageAuthor Commented:
Hi Julian,

If you remember my other question, in my form I have given value for each radio button and an image to display in the form. When the form is submitted, the radio button value comes to me. What I want is that the radio button value as well as the image that is assigned to that value, both should come to me.
0
Julian HansenCommented:
Don't think of it like that - rather use the value that is submitted by the form (radio button) is a key to all the data you need on the server.

You use the submitted value to work out which image to use.
1
Olaf DoschkeSoftware DeveloperCommented:
Having the code of both form and form evaluation is ok, but is it really that way? Is that code email_handler.php?

In my phpfiddle I showed you can use a switch to specify the image source for every case. In case the values are 2-7, why don't you simply use this as part of the image file name as is?

Your code actually works as is, when I put it into phpfiddle: http://phpfiddle.org/lite/code/5r47-mf6i
The only thing I changed is the form action set to "#", which in short means the same script creating the form evaluates the form submit.

So I assume you only have split code in HTML form and the email_handler.php. Of course, the code creating the mail has to be in the script called by the action of the form.

Besides that, as said you can simplify creating the image src without switch here:

if (isset($_POST['grade']))
{
    echo('<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2011/09/grade_".$_POST['grade'].".png">');
}

Open in new window


It's recommended to check the submitted value range is really within expected and allowed image numbers, as anyone wanting to hack the server simply would submit anything else but 2-7, eg javascript code. For that matter, while it is very verbose, the switch statement really checks the values are correct and displays no image for any other submitted value than "2" to "7". So you can stay with it, too.

Perhaps just look into access log on your server to see what is called by the form action if you start with action="php/... vs starting with action="/php/... vs starting with action="~/php/... or action="./php...

If you want to be sure what script is called use an absolute URL, it just makes it harder to test with localhost.

Bye, Olaf.
0
S SaxenaWitageAuthor Commented:
Thanks Olaf,

I will try your simplified code and get back.

Bye, Saxena
0
NerdsOfTechTechnology ScientistCommented:
I recommend that you sanitize the POST variables as well (process and filter the inputs to make them safe) to prevent an XSS attack.
0
Olaf DoschkeSoftware DeveloperCommented:
I second NerdsOfTech about sanitation, take a look at http://php.net/manual/de/function.filter-input-array.php

Also, since you depend on an existing image, check whether the src you compute actually exists, eg after sanitizing the $_POST array:

$src=http://www.aspirehairrestoration.com/wp-content/uploads/2011/09/grade_".$_POST['grade'].".png"
if (file_exists($src)) => ...echo img tag...

Open in new window


Also, you'll finally need this inside your $body variable later put as mail body, not echoed to the browser output HTML.

Bye, Olaf.
0
S SaxenaWitageAuthor Commented:
Can you please teach me how to sanitize and filter. I am learning php from experts like you people.

Regards
Saxena
0
Olaf DoschkeSoftware DeveloperCommented:
Could we do that in a separate question? It really is aseparate topic and deserves an onw entry in EEs knowledgebase.

If you now have solved the problem of adding the selected image to a mail body, could you please close the question? Or clarify what's still not working and missing aside of the sanitizing user input?

Bye, Olaf.
0
NerdsOfTechTechnology ScientistCommented:
Sanitation puts restrictions AKA filters on the input to limit WHAT can be outputted or parsed via script.

I personally like filtering inputs to the 'most restrictive subset' possible.

For 'grade' in your case I reduced the input to a single character between 2-7. Without filtering, an attacker could manually post to your form processing page (in the ACTION statement of your HTML FORM) and use malicious inputs; for example if the attacker posted 'abc' as the 'grade' input, the file 'abc.png' would be displayed. This could expose the file system if the attacker used '..' and other inputs to manipulate the possible output.

<?php
$_POST['grade'] = '<script>window.alert("XSS attack")</script>;123456789';
echo $_POST['grade']; //without sanitation, an XXS attack is possible.

// regular expression; find FIRST number between 2-7 ONLY
$re = '/[2-7]{1,1}/'; 
$str = $_POST['grade'];
$match = preg_match($re, $str, $matches);
if($match){ //match found return the SINGLE character between 2 and 7
    echo('<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2011/09/grade_".$matches[0].".png">');
}else{
    //grade is empty or invalid
}
?>

Open in new window

If you run the above code, the message 'XSS attack' will popup on your screen. The second part is the actual sanitation where the input is filtered to a single character '2' which matches the first character {1,1} that matches characters between 2 through 7 [2-7].
0
NerdsOfTechTechnology ScientistCommented:
Sanitation is cleaning an input of all unwanted characters; especially those that could create an attack. Depending on the circumstances, some characters should be encoded, while some should be removed. It is because some characters have a special meaning in certain contexts, in others some characters create an error (e.g. say you had an input that generated a redirect, if the input had a space in it, you would want to encode it as %20; otherwise, it would be an invalid URL). PHP has many pre-built filters in PHP 5.2+ and some from 7+ that are handy. These help with some of the standardized cleanups (e.g. filter an email input for only valid characters in an email)

http://php.net/manual/en/function.filter-var.php
http://php.net/manual/en/filter.filters.sanitize.php

Input sanitation is important in almost all cases. This is because in most cases, the input is being used or stored (e.g. displayed, or used in a database search, etc.). Attackers can employ certain attacks depending on the circumstances involved (e.g. if an input is used to search a database, an unfiltered, malformed input could cause an SQL injection attack; or with a form that displays raw inputs, a malformed script input could cause an XSS attack). Raw meaning not sanitized.

Validation is a similar concept that makes sure the input complies to a certain pattern (e.g. making sure an email address is formatted correctly).

Both concepts are very important.
0
S SaxenaWitageAuthor Commented:
Hello Olaf,

Sorry for delayed reply as I had some deadlines to meet. I tried your simplified solution. Following is my php:

<td>if (isset($_POST['grade']))
{
    echo('<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2011/09/grade_".$_POST['grade'].".png">');
}</td>

Open in new window


But after submitting the form I am getting the following error.
( ! ) Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\wamp64\www\calculator_form\php\email_handler_1.php on line 67

Line 67 is the one that I have written above.

Regards
Saxena
0
Olaf DoschkeSoftware DeveloperCommented:
You mix HTML and PHP without using the <?php and ?> tags to mark what is PHP. Also look back to post ID 42362842 in the last code section of it, I changed my echo code to your already existing assignment code to $body. This requires no echo but string concatenation.

The echo is just there to demonstrate the img tag rendered in the browser, you want it in your email, thus you want it in your $body variable.

It's really just a small step to change from echo to string concatenation, it's like here:

<p><?php echo $someexpression; ?></p>

Open in new window

vs
<?php
...
$paragraph= "<p>".$someexpression."</p>";
...
?>

Open in new window

And then at some point echo the $paragraph variable or use it as a parameter of eg the $mail->MsgHTML() setter.

You're working on something I already did for you earlier. You've got to get a bit of understanding on how things relate, you're more like copy&pasting things until they work. Any echo always just goes to the output arriving at a browser, to get that output into a variable you use dot (string concatenation) to other string parts to add it together and in the end assign that string to the $body variable used in the mail, instead of echoing it. So echo can't be part of the solution 1:1, can it?

As you have a hard time making these observations and conclusions, you lack a serious skill to program anything, even if it's taught to you in baby steps. I'll try once more here:

Yyou have something like this in your current mail generating code:
$body = "<table>
<tr>...

Open in new window


This is where it all start, it goes on for many lines and ends in

...<table>";

Open in new window


All these lines in the editor are one line of PHP code, it's an assignment of a string value to $body via the = operator. You can't have an echo inside an assignment.

You want the image (<img>) tag to go in there to become part of $body and get into the mail HTML body.

What you have in there is lines like this:
<td>".$_POST['age']."</td>

Open in new window


They just end up as a td (table data tag) containing some simple text or number, in the case of the age.
Putting in this
<td>".$_POST['grade']."</td>

Open in new window

You would just get the grade number in your mail. You want more this time, you want that grade number as just the last part of your image file name or URL, which in itself also is just the value of the src attribute of an image tag.

So what you need there is, as I already gave back 4 days ago:

<td><img src='/yourimagesdirectory/".$_POST['gender'].".jpg'></td>

Open in new window

And since you now posted your image URLs in your sample code, this more concretly is:


<td><img src='http://www.aspirehairrestoration.com/wp-content/uploads/2011/09/grade_".$_POST['grade'].".png'></td>

Open in new window


Now if that still doesn't work, you most likely miss your HTML form having the necessary radio input tags named "grade" and so $_POST['grade'] is not set.

Bye, Olaf.
0
NerdsOfTechTechnology ScientistCommented:
The closing and starting double quotes should've been single quotes to encapsulate the string.

Next, the PHP tag should be there if it is being mixed in with HTML.

Optional syntax:
echo is not actually a function (it is a language construct), so you are not required to use parentheses with it.
http://php.net/manual/en/function.echo.php


Fixed code:
<td>
<?php 
if (isset($_POST['grade']))
{
    echo '<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2011/09/grade_'.$_POST['grade'].'.png">';
}
?>
</td>

Open in new window


Don't forget to sanitize those inputs to avoid a XSS attack.
0
Olaf DoschkeSoftware DeveloperCommented:
I think S Saxena put my echo into the code you reposted already, so this is part of the one lengthy $body assignment of the HTML string. It doesn't get obvious from the single posted line.

So let me simply post the full assignement including the new section for the img tag:

$body = '<table>
<tr>
<th colspan="2">Contact Form</th>
</tr>

<tr>
<td style="font-weight:bold">Full Name:</td>
<td>'.$_POST['name'].'</td>
</tr>

<tr>
<td style="font-weight:bold">E-Mail:</td>
<td>'.$_POST['email'].'</td>
</tr>

<tr>
<td style="font-weight:bold">Mobile:</td>
<td>'.$_POST['mobile_number'].'</td>
</tr>

<tr>
<td style="font-weight:bold">Age:</td>
<td>'.$_POST['age'].'</td>
</tr>

<tr>
<td style="font-weight:bold">City: </td>
<td>'.$_POST['city'].'</td>
</tr>

<tr>
<td style="font-weight:bold">Select Method: </td>
<td>'.$_POST['method'].'</td>
</tr>

<tr>
<td style="font-weight:bold">Grade of Baldness (numeric): </td>
<td>'.$_POST['grade'].'</td>
</tr>

<tr>
<td style="font-weight:bold">Grade of Baldness (image): </td>
<td><img src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_'.$_POST['grade'].'.png"></td>
</tr>

<table>';

Open in new window


Notice: I changed the assignment to make use of single quote string delimiters as the outmost delimiters, not only but also, because the HTML within can then be written with the typical double quoted attributes. You better replace all these lines with this whole assignment as most single and double quotes are switching places.

NerdsOfTech has a point in that aspect, though it's a bit of a decision of which camp you're in. Single quoted strings mean you can't simply write variables within the string, so they are put in as their value, but you don't do so anyway.

What's missing now is the check, whether $_POST['grade'] is set. I still think the topic of sanitizing input deserves a separate thread and shouldn't be just a side answer. In that sanitizing, you would move $_POST data into single variables via filter_input() or a new array via filter_input_array(). This'll take a bit more than one line of explanation.

Bye, Olaf.
0
S SaxenaWitageAuthor Commented:
Hello Olaf,

After suggestions from Julian, following is my final php.

$mail->From     = $from;
  $mail->FromName = 'Aspire';
  $mail->Subject  = "Cost Calculator Form";
  
  // WE EXTRACT THE FORM VARIABLES TO SAFE VERSIONS 
  $name   = isset($_POST['name'])          ? $_POST['name']          : '(no name specified)';
  $email  = isset($_POST['email'])         ? $_POST['email']         : false;
  $mobile = isset($_POST['mobile_number']) ? $_POST['mobile_number'] : '(no mobile specified)';
  $age    = isset($_POST['age'])           ? $_POST['age']           : '(no age specified)';
  $city   = isset($_POST['city'])          ? $_POST['city']          : '(no city specified)';
  $method = isset($_POST['method'])        ? $_POST['method']        : '(no method specified)';
  $grade  = isset($_POST['grade'])         ? $_POST['grade']         : 0;

  // SET UP THE FORM USING HEREDOC
  $body = <<< HTML
<table>
  <tr>
    <th colspan='2'>Contact Form</th>
  </tr>
  <tr>
    <td style='font-weight:bold'>Full Name:</td>
    <td>{$name}</td>
  </tr>
  <tr>
    <td style='font-weight:bold'>E-Mail:</td>
    <td>{$email}</td>
  </tr>
  <tr>
    <td style='font-weight:bold'>Mobile:</td>
    <td>{$mobile}</td>
  </tr>
  <tr>
    <td style='font-weight:bold'>Age:</td>
    <td>{$age}</td>
  </tr>
  <tr>
    <td style='font-weight:bold'>City: </td>
    <td>{$city}</td>
  </tr>
  <tr>
    <td style='font-weight:bold'>Select Method:</td>
    <td>{$method}</td>
  </tr>
  <tr>
    <td style='font-weight:bold'>Grade of Baldness:</td>
    <td>{$grade}</td>
  </tr>
<table>
HTML;

Open in new window


And this is my html:

<tr>
<th>Grade of Baldness*:</th>
<td><input id="bald" class="form-control" name="grade"  required type="radio" value="2" required/>2<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2011/09/grade_2.png" alt="no image"></td>
<td><input class="form-control" name="grade" value="3" required type="radio"/>3<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_3.png" alt="no image"></td>
<td><input class="form-control" name="grade"  required type="radio" value="4"/>4<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_4.png" alt="no image"></td>
<td><input class="form-control" name="grade" required="" type="radio" value="5"/>5<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_5.png" alt="no image"></td>
<td><input class="form-control" name="grade" required="" type="radio"value="6"/>6<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_6.png" alt="no image"></td>
<td><input class="form-control" name="grade" required="" type="radio" value="7"/>7<img src="http://www.aspirehairrestoration.com/wp-content/uploads/2017/11/grade_7.png" alt="no image"></td>
</tr>

Open in new window


I already tried the solution you have given above but received the error message I already posted yesterday. Please tell me what wrong I am doing.

Regards
Saxena
0
Olaf DoschkeSoftware DeveloperCommented:
Did you really try my newest posted $body assignment? Not the echo variant. My post I referred to seems deleted, I don't know why.

Stay with Julians HEREDOC solution, it's fine.

Notice I made phpfiddle samples, which run on that site and I think you can't send mail from there (that would allow the site to be misused), so the option I had to demo how to put together an img tag string and to echo it, so the browser shows it. The only interesting part ever was after "echo", the expression creating the img tag you need in your mail.

Bye, Olaf.
0
NerdsOfTechTechnology ScientistCommented:
The single quote comment made earlier by me wasn't a suggestion but rather a correction of Olaf's previous code that threw the error (missing single quotes).
0
NerdsOfTechTechnology ScientistCommented:
The OP question was initially solved by Julian (working sample), Olaf, and Dave; then, auxiliary questions seemed to arise from the thread regarding security and syntax. In light of this, I propose this split.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
CSS

From novice to tech pro — start learning today.