Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to convert from asp to php 1

Status
Not open for further replies.

rogerte

Programmer
Nov 9, 2001
164
GB
I will admit I know absolutely nothing about PHP and having tried following code example from the web am even more confused.

Basically the club I help with has changed hosting from an ASP based one to a PHP based one (cost!), without letting me know.

I wrote the web page several years ago and now need to change the ASP to PHP to allow form data to be emailed to the clubs email address. I will be changing it by adding a repeat email, so will need to amend validation to ensure the email addresses match. I suggested adding a captcha, but the club committee don't want it (yet...)

The ASP is on same page as the form (to allow alerts to be displayed). I haven't found how to do this with PHP

Code:
<form style="margin: 25px; padding: 0px; font-family: Verdana, Arial, Helvetica, sans-serif; 	font-size: 11px;"  method=Post action="">
<p class="leftNormalText">Your name</p>
<input type="text" name="t1" size="40"><br>
<p class="leftNormalText">Your email</p>
<input type="text" name="t2" size="40"><p>

<p class="leftNormalText">Enquiry type</p>
<select name="s1">
<option value="Waiting List Enquiry">Membership Enquiry - New/Waiting List</option>
<option value="Member Enquiry">Membership Enquiry - Existing Member</option>
<option value="Uniform Enquiry">Uniform Enquiry</option>
<option value="Coach Enquiry">Coaching Enquiry</option>
<option value="Other Enquiry">Other Enquiry</option>
</select>


<p class="leftNormalText">Your message</p>
<textarea rows="6" name="st" cols="80"></textarea><p>
<input type=submit value=Submit></form>
<%
if request.servervariables("REQUEST_METHOD")= "POST" then
 Dim JMail, intComp, strReferer, strServer, strClientIP, strServerIP, blnSpam
  Dim stname,st
  Dim t1name,t1,t2name,t2, s1
  Dim i

  t1name = "Sender's name"
  t1 = Request.Form("t1")
  t2name = "Sender's email"
  t2 = Request.Form("t2")
  stname = "Message"
  st = Request.Form("st")
  s1 = Request.Form("s1")
  if (len(t2) > 0) and (len(t1)>0) and (len(st)>0) Then
    Set JMail = Server.CreateObject("JMail.SMTPMail")

    strReferer = request.servervariables("HTTP_REFERER")
    strServer = Replace(request.servervariables("SERVER_NAME"),"[URL unfurl="true"]www.","")[/URL]
    strClientIP = request.servervariables("REMOTE_ADDR")
    strServerIP = request.servervariables("LOCAL_ADDR")

    intComp = inStr(strReferer, strServer)

    If intComp > 0 Then
      blnSpam = False
    Else

      ' Spam Attempt Block
      blnSpam = True
    End If

    JMail.ServerAddress = "smtp." & strServer & ":25"
    JMail.AddRecipient "info@oursportsclub.org.uk"

    JMail.Sender = "info@oursportsclub.org.uk"

    JMail.Subject = s1 & " From Website"

    JMail.Body = t1name & vbcrlf&_
    t1 & vbcrlf&_
    t2name & vbcrlf&_
    t2 & vbcrlf&_
    stname & vbcrlf&_
    st & vbcrlf&_
    now()

    if NOT blnSpam Then
      JMail.Execute
      strResult = "Mail Sent."
      Response.Write("<" & "script language=""javascript"">")
      Response.Write("alert(""" & strResult & """);<" & "/script>")
    Else
      strResult = "Mail Could Not Be Sent."
      Response.Write("<" & "script language=""javascript"">")
      Response.Write("alert(""" & strResult & """);<" & "/script>")
    End If
    Set JMail = Nothing 
  Else
    strResult = "Please Ensure All Fields Are Completed"
    Response.Write("<" & "script language=""javascript"">")
    Response.Write("alert(""" & strResult & """);<" & "/script>")
	End If	
End If
%>

Can anyone give me some pointers as to the way to convert this to PHP?
 
Sorry, I forgot to add my attempt so far

Code:
<? 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $t1name="Sender's name";
  $t1=$_POST["yourname"];
  $t2name="Sender's email";
  $t2=$_POST["mail"];
  $t3=$_POST["mailconf"];
  $stname="Message";
  $st=$_POST["messtitle"];
  $s1=$_POST["MessText"];
  if ((strlen($t2) > 0) && ((strlen($t3) > 0)  && (strlen($t1) > 0) && (strlen($st) > 0)) {
	  if st3 = st2 {		  
      $strReferer=$_SERVER["HTTP_REFERER"];
      $strServer=str_replace("www.","",$_SERVER["SERVER_NAME"]);
      $strClientIP=$_SERVER["REMOTE_ADDR"];
      $strServerIP=$_SERVER["LOCAL_ADDR"];
      $intComp=_instr(0,$strReferer,$strServer,0);
      if ($intComp > 0) {
        $blnSpam=false;
      }
      else {
        // Spam Attempt Block
        $blnSpam=true;
      }
      //$JMail->ServerAddress="smtp.".$strServer.":25";
      //$JMail->AddRecipient("info@oursportsclub.org.uk");
      //$JMail->Sender="info@oursportsclub.org.uk";
      //$JMail->Subject=$s1." From Website";
      //$JMail->Body=$t1name."\r\n".$t1."\r\n".$t2name."\r\n".$t2."\r\n".$stname."\r\n".$st."\r\n".time();
      //if (!$blnSpam) {
        //$JMail->Execute;
        //$strResult="Mail Sent.";
        //echo "<script language=\"javascript\">";
        //echo "alert(\"".$strResult."\");</script>";
      }
        else {
        $strResult="Mail Could Not Be Sent.";
        echo "<script language=\"javascript\">";
        echo "alert(\"".$strResult."\");</script>";
        }
      $JMail=NULL;
    }
		else {
    $strResult="E-mail addresses do not match";
    echo "<script language=\"javascript\">";
    echo "alert(\"".$strResult."\");</script>";
  }
  else {
    $strResult="Please Ensure All Fields Are Completed";
    echo "<script language=\"javascript\">";
    echo "alert(\"".$strResult."\");</script>";
  }
}

function _instr($start,$str1,$str2,$mode) {
if ($mode) { $str1=strtolower($str1); $str2=strtolower($str2); }
$retval=strpos($str1,$str2,$start);
return ($retval===false) ? 0 : $retval+1;
}
?>

I assume it must use the mail() function, but as I can't test it yet.

Need to amend it so it sends the email to the info@ address and also sends a copy to the person who raised the request

Thanks
 
I think you need to get yourself a book on PHP. If you can do ASP, PHP should not be a real problem. PHP is quite a C ish language so if you know C you should be well away.
This forum is realy about helping out existing PHP developers.
For a book I'd avoid the dummy series as they tend not to give you enough detail. I have ab earlier copy of which is quite good.
General pointers are diffucult, you gave got a good start by picking up the post variables but you don't validate them which is bad news, this is why I recomend a good book so you can get the job done correctly.
and I'd have a serious word with who ever changed host !
 
Thanks ingresman,

Not a C programmer - I came from Clipper/Delphi worlds.

I did have a few words about changing hosting, but by then it had all happened.
 
rogerte

to get you started here is a transformation of your asp code, tidied up with some php good practices, but not all.

i have not incorporated your referrer check as it it's a bit crude. but i have implemented a nonce check instead. there are better ways to do this (js delivery), but this at least adds a slight computational price to bot attacks and I suspect your site is not high enough traffic to interest bots too much.

the code is commented for ease of understanding. but that is no substitute for following ingresman's advice

note: the code is typed straight into an editor. i have only briefly tested it.
Code:
<?php
/*
 * profile the options array for multiple use
 */
$arrayOpts = array(
"Waiting List Enquiry" => "Membership Enquiry - New/Waiting List",
"Member Enquiry"=>"Membership Enquiry - Existing Member",
"Uniform Enquiry"=>"Uniform Enquiry",
"Coach Enquiry"=>"Coaching Enquiry",
"Other Enquiry"=>"Other Enquiry"
);

/*
 * if the post array is set then the form has been submitted
 */ 
if (isset($_POST['t1'])):
	/*
	 * if any fields are blank, or an illegal value for the s1 array is submitted, flash an error and try again
	 */ 
	if (empty($_POST['t1']) || empty($_POST['t2']) || empty($_POST['s1']) || !in_array($_POST['s1'], array_keys($arrayOpts))):
		displayForm('There was an error. Please try again.');
	endif;
	
	/*
	 * if this is a bot attempt or a 'refresh' submission ignore and display the form
	 */ 
	if (!nonce()):
		displayForm();
	endif;
	
	/*
	 * construct the email message
	 */
	$to = "info@oursportsclub.org.uk";
	$from = "info@oursportsclub.org.uk";
	$subject = $_POST['s1'] . " From Website";
	$time = date('r');	
	$message = <<<TEXT
Name:	{$_POST['t1']}
Email:	{$_POST['t2']}
Request Type:	{$_POST['s1']}
Message:	{$_POST['st']}
Timestamp:	$time
TEXT;

	/*
	 * send the email message.  note that this may need configuring in php.ini
	 */
	$r = mail($to, $subject, $message, "From: $from\r\n");
	if ($r):
		echo "Your enquiry has been safely received and will be processed shortly"; //normally you would redirect to some success page or show some nice confirmation
	endif;
else:
	displayForm();
endif;

/*
 * this displays the enquiry form
 */
function displayForm ($message = ''){
	global $arrayOpts;
	$opts = '';
	/*
	 * reuse the options array for efficiency
	 */
	foreach ($arrayOpts as $val=>$text):
		$opts .= "\t<option value='$val'>" . htmlspecialchars($text) . "</option>\n";
	endforeach;
	/*
	 * display an error message if one is provided
	 */
	$message = empty($message) ? '' : '<div style="background-color:red; border:dotted black thin">'.$message.'</div>';
	
	/*
	 * grab a nonce to prevent back button/bot etc submission
	 */
	$nonce = getFieldNonce();	
	
	/*
	 * construct the form
	 */
	$form = <<<FORM
$message
<form style="margin: 25px; padding: 0px; font-family: Verdana, Arial, Helvetica, sans-serif;     font-size: 11px;"  method=Post action="">
<p class="leftNormalText">Your name</p>
<input type="text" name="t1" size="40"><br>
<p class="leftNormalText">Your email</p>
<input type="text" name="t2" size="40"><p>

<p class="leftNormalText">Enquiry type</p>
<select name="s1">
$opts
</select>
<p class="leftNormalText">Your message</p>
<textarea rows="6" name="st" cols="80"></textarea><p>
<input type="submit" value="Submit" name="xSubmit">
$nonce
</form>

FORM;
	/*
	 * output the form and kill the script to stop further execution
	 */ 
	echo $form;
	exit;
}

/*
 * returns a form field with a nonce
 */
function getFieldNonce(){
	$nonce = getNonce();
	return '<input type="hidden" value="' . $nonce . '" name="nonce" />';
}

/*
 * returns and stores the current nonce
 */
function getNonce(){
	if (session_id() == '') session_start();
	if (!isset($_SESSION['nonce'])) $_SESSION['nonce'] = md5(uniqid('nonce_', true)); 
	return $_SESSION['nonce'];	
}

/*
 * checks that the submitted nonce is valid
 */
function nonce(){
	if(session_id() == '') session_start();
	if (!isset($_POST['nonce'])) return false;
	if (!isset($_SESSION['nonce'])) return false;
	if ($_POST['nonce'] !== $_SESSION['nonce']) return false;
	unset($_SESSION['nonce']);
	return true;
}
?>
 
jpadie,

Thanks for that you are a star - shows what a lot I have to learn.

I must admit never even thought about using nonce.

Now to go through and really rty to understand it!

Cheers

Roger
 
do post back if anything is not clear.

one thing that may be confusing/strange to asp programmers is the difference between single and double quotes and the use of the heredoc and nowdoc string syntaxes. there are excellent descriptions in the php manual for these.

other than that, there is little structural difference between the asp code you posted and that above. php uses slightly different syntax for control structures, using curlybraces or the alternate (colon) syntax.
 
jpadie,

I have been through the code and now think I understand it.

However Iam sitting here with a PHP tutorial book, and one thing I can't find is an explanation of the <<<TEXT .... TEXT; and <<<FORM ... FORM;

I assume it is some way of assigning a block of mixed items to a variable, and the TEXT (or FORM) just act as delimiters to that block(?)

Thanks

Roger
 
thought that might happen. that's why i posted above that you should look in the manual to learn about quotes and heredoc/nowdoc. here is the manual reference.
 
Life was so much simpler when I just stuck to Clipper and PASCAL/Delphi!!!!
 
took me a few days to get up to speed with php from previous (1980s) experience with pascal/fortran/basic and latterly (1990s) VB/VBA. never played with clipper/delphi: aren't they just db manipulation languages?
 
Delphi is basically Pascal with a GUI front end. It's what Visual Basic should have been!

Clipper was originally derived from dBase3, a DML, but was extended to become a language in its' own right that could do almost everything you could think of - in DOS!

Between them Delphi and Clipper (still!!) are keeping me in gainful employment.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top