How to connect to a SQL DB with PHP in Bluemix - db2

I am binding a service to my database and I found the following code online:
$services_json = json_decode($json,true); <br/>
$sqldb = $services_json["sqldb"]; <br/>
if (empty($sqldb)) { <br/>
echo "No sqldb service instance bound. Please bind a sqldb service instance before"; <br/>
return; <br/>
} <br/>
<br/>
$sqldb_config = $services_json["sqldb"][0]["credentials"]; <br/>
<br/>
// create DB connect string <br/>
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};"; <br/>
$conn_string .= "DATABASE=" . $sqldb_config["db"] . ";"; <br/>
$conn_string .= "HOSTNAME=" . $sqldb_config["host"] . ";"; <br/>
$conn_string .= "PORT=" . $sqldb_config["port"] . ";"; <br/>
$conn_string .= "PROTOCOL=TCPIP;"; <br/>
$conn_string .= "UID=" . $sqldb_config["username"] . ";"; <br/>
$conn_string .= "PWD=" . $sqldb_config["password"] . ";"; <br/>
<br/>
// connect to database <br/>
$conn = db2_connect($conn_string, '', ''); <br/>
I am not getting any response or I don't know db2_connect statement execute or not.
Please help me.

I think you need to check your database which bind to your project or not using cf command or use gui also.

If you want to know if the connection was successful or not then add the following code after the db2_connect call:
if ($conn) {
echo "Connection succeeded.";
}
else {
echo "Connection failed.";
}

db2_connect returns false if connection failed, otherwise returns the connection resource to use.
http://php.net/manual/en/function.db2-connect.php
In case of error you can use
db2_conn_err to get the error got in the last connecting attempt

Related

mail(): SMTP server response: 550-"JunkMail rejected

I Would like to send email using contact form in my company website,
I was set the email configuration in php, here is my form :
<form action="sendmail.php" method="post" class="form form--contacts">
<input type="text" name="name" class="form__input" placeholder="Name" required>
<input type="email" name="email" class="form__input" placeholder="Email" required>
<input type="text" name="subject" class="form__input" placeholder="Subject" required>
<textarea class="form__textarea" name="text" placeholder="Text"></textarea>
<input class="form__btn" name="send" type="submit" value="Send">
</form>
and here is sendmail.php :
<?php
if($_POST['send']){
$admin = 'myname#mydomain.co.id';
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
$subject = htmlentities($_POST['subject']);
$text = htmlentities($_POST['text']);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From:'.$name.' <'.$email.'>' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$pengirim = 'From: '.$name.' <'.$email.'>';
if(mail($admin, $subject, $text, $headers)){
echo 'SUCCESS: Mail Successfully sending';
}else{
echo 'ERROR: Error Sending Email';
}
}else{
header("Location: index.php");
}
?>
There might be few reasons for junk mail detection.
First, you don't have "To: " in your headers.
Second, you rely on your system mail and you have no control over from which account you are sending mail from. If your "From:" header is different than your actual "mail from:" in your SMTP connection it's a red flag for spam filter.
You should try using PHPMailer instead of built in function. ( https://github.com/PHPMailer/PHPMailer ) or other alternative.
Some info may be found in this post: Sending email with PHP from an SMTP server

How can we send the table data to mail using php?

i am displaying the daily report submitted by the user now i want to mail the same to email when the send email button is clicked. how can i do that in PHP ?
i used the following code
extract($_REQUEST);
if(isset($send_mail)){
$edata= $_POST['send_msg'];
echo "<script type='text/javascript'>alert('$edata');</script>";
$ka_semail=$_SESSION['user_email'];
$subject = "Report";
$body = $edata;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Info <'.$ka_semail.'>' . "\r\n";
$mchk= mail($ka_semail, $subject, $body, $headers);
if(isset($mchk)){
echo "<script type='text/javascript'>alert('Your data Sent sucessfully');</script>";
header("location:reports.php");
}
}
?>
<body>
<div id="main">
<header>
<div id="logo">
<div id="logo_text">
<a href="index.html">
<div style="background:#2A0000"><img src="images/kreamsoftlogo.png"/></a></div>
</div>
</div>
<?php include'nav.php'; ?>
</header>
<div id="site_content">
<div id="email-data">
<div id="content">
<div class="content" style="min-height:385px; width: 100%" >
<h1>Daily Report </h1>
<?
$current_date = date("d/m/Y");
$current_user = $_SESSION['user_login'];
$find = mysql_query("select * from k_dailyreport where kr_user='$current_user' AND kr_date='$current_date'");
?>
<div class="content_item">
<ul>
<?php
$numrow=mysql_num_rows($find);
if($numrow>0){
$sino = 0;
echo "<table border='0' width='100%'>";
echo "<tr class='head'>";
echo "<th>S.No</th>";
echo "<th>Project</th>";
echo "<th>Process</th>";
echo "<th>Process Date</th>";
echo "<th>Current Duration</th>";
echo "</tr>";
$sno=0;
while($row = mysql_fetch_array($find)){
$sno=$sno +1;
$sino++;
$cls = ($sino%2==0) ? "even" : "odd";
echo "<tr class='t1'>";
echo "<td>$sno</td>";
echo "<td>".$row['kr_project']."</td>";
echo "<td>".$row['kr_process']."</td>";
echo "<td>".$row['kr_rtime']."</td>";
echo "<td>".$row['kr_ctime']."</td>";
}?></td>
<?php
echo "</tr>";
?><form name="test" method="post"enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>">
<p style='padding-top: 15px;margin-right: 50px; float:right'><input class='submit' id="sendEmail" type="submit" name='sendmail' value='Send Mail' />
<input type="hidden" name="send_mail" value="send_mail" />
<input type="hidden" name="send_msg" value="<?php
$numrow=mysql_num_rows($find);
if($numrow>0){
$sino = 0;
echo "<table border='0' width='100%'>";
echo "<tr class='head'>";
echo "<th>S.No</th>";
echo "<th>Project</th>";
echo "<th>Process</th>";
echo "<th>Process Date</th>";
echo "<th>Current Duration</th>";
echo "</tr>";
$sno=0;
while($row = mysql_fetch_array($find)){
$sno=$sno +1;
$sino++;
$cls = ($sino%2==0) ? "even" : "odd";
echo "<tr class='t1'>";
echo "<td>$sno</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "<td>".$row[3]."</td>";
echo "<td>".$row[3]."</td>";
echo "</tr>";
}echo "</table>";}?>" /></p>
</form>
<?
}else{
?>
<center><img style="text-align:center" src="images/no_record.gif" /></center>
<?
}
echo "</table>";
?>
</li>
</ul>
</div>
</div> </div>
</div>
</div>
i want to mail the entire table with data
Without knowing anything about your code, I can perhaps at least guess as to the structure of what builds this table. Maybe something along the lines of this?:
writeTableHeader();
foreach ($values as $value) {
writeTableRow($value);
}
writeTableFooter();
Maybe even abstracted into its own higher-level function?:
function writeTable($values) {
$result = '';
$result .= buildTableHeader();
foreach ($values as $value) {
$result .= buildTableRow($value);
}
$result .= buildTableFooter();
return $result;
}
Any such function or abstraction can be used to construct the HTML for the email body as well...
// ... previously building the overall email body
$mailBody .= writeTable($values);
// ... maybe some more email body elements as well
mail($to, $subject, $mailBody);
Styling the email will be another story, of course. It's best not to rely on linked resources in an HTML email, those tend not to be requested by mail clients as they're often abused by spammers and the like. You can perhaps include the style sheet(s) as an "embedded resource" in the email, though in most cases I think inline styling is probably best for emails. (Some mail clients might not even load an embedded resource, at least not without first prompting the user, which isn't an ideal user experience.)
Assuming you don't want to duplicate much code, the above method can be abstracted using the Form Template Method refactoring pattern (example here, among others).
I guess the point I'm getting at is that the email doesn't send the web page, but rather the web page and the email are both independent "views" of the underlying data. Common code between them can be abstracted and shared of course, but trying to re-use a webpage itself in an email is over-complicating the situation.

php email script not working correctly

I have a form on my website:
<form name="contact" action="contact.php" method="post">
<label for="name">Name:</label><br/><input type="text" name="name" id="name"><br/>
<label for="email">Email:</label><br/><input type="text" name="email" id="email"><br/>
<label for="comment">Question:</label><br/><textarea name="comment" id="comment"></textarea><br/>
<input type="submit" value="Send" id="submit">
</form>
This is the script it submits the data to:
<?php
header("Refresh: 3;url=http://www.xyz.com/");
if(isset($_POST['email'])) {
$email_to = "xxxx#gmail.com";
$email_subject = "Enquiry";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['name']) ||
!isset($_POST['email']) ||
!isset($_POST['comment'])){
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$name = $_POST['name']; // required
$email = $_POST['email']; // required
$comment = $_POST['comment']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
if(strlen($comment) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email)."\n";
$email_message .= "Comment: ".clean_string($comment)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>
For some reason the script outputs that the message was sent successfully but when I check my inbox there is no new emails. I don't know what is going on, can anyone help me?
Mail function has errors turned off
#mail($email_to, $email_subject, $email_message, $headers);
remove # from this and add simple if
if(mail($email_to, $email_subject, $email_message, $headers))
{
echo 'mail was sent'; //success message here
}
else
{
echo 'there were errors during sending mail'; //error message there
}
When you find out what errors occur then you can remove them. It can be problem with configuration of SMTP server.
You can set some settings affecting mail() function in php.ini
Read more here.
Moreover, this Thank you for contacting us. We will be in touch with you very soon. message is shown always it doesn't check if something is wrong it is just shown.

Perl Form Validation using CGI scripting

I'm trying to achieve one last task for my assignment is to validate the form before submit it to the another CGI program.
What happen is that I have a simple CGI program that will ask user to input the data
#!/usr/bin/perl -w
use CGI qw/:standard/;
# Standard HTTP header
print header();
# Write information to data file and produce a form
&printForm();
# Finish HTML page
print end_html();
# This sub will create a form to access the print_fortune.cgi script
sub printForm
{
print qq~
<html>
<head><title>My Search Engine</title>
</head>
<body>
<form action="b1.cgi" method="GET">
What is your e-msil address? <input type="text" name="passing" size=40>
<input type="submit" value="send address">
<input type="hidden" name="form" value="insert" />
</form>
<form method="get" action="b1.cgi" enctype="application/x-www-form-urlencoded">
<input type="text" name="search" value="" size="30" /><br />
<label><input type="radio" name="option" value="name" checked="checked" />name</label>
<label><input type="radio" name="option" value="author" />author</label><label>
<input type="radio" name="option" value="url" />url</label>
<label><input type="radio" name="option" value="keyword" />keyword</label>
<input type="submit" name=".submit" value="Search" />
<input type="hidden" name="passing" value="http://default.com" />
<div><input type="hidden" name="form" value="search" /></div></form>
</body>
So the above program contains two forms. One is to add new data to the database and the other one is to search from the database.
#!/usr/bin/perl
print "Content-type: text/html\n\n";
use LWP::Simple;
use CGI;
use HTML::HeadParser;
use DBI;
my $serverName = "";
my $serverPort = "";
my $serverUser = "";
my $serverPass = "";
my $serverDb = "";
my $serverTabl = "";
$cgi = CGI->new;
my $pass = $cgi->param('passing');
$URL = get ("$pass");
$head = HTML::HeadParser->new;
$head->parse("$URL");
my $methods = $cgi->param('form');
if ($methods eq "insert"){
insert_entry();
}
show_entries();
sub insert_entry {
my ($dbh, $success, $name, $author, $url,$temp);
$dbh = DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass);
$name = $head->header('X-Meta-Name');
$author = $head->header('X-Meta-Author');
$url = $cgi->param('passing');
$temp = $head->header('X-Meta-Keywords');
#keyword = split(/,/,$temp);
$success = $dbh->do("INSERT INTO $serverTabl(name,author,url,keyword1,keyword2,keyword3,keyword4,keyword5) VALUES(?,?,?,?,?,?,?,?)", undef,$name,$
author,$url,$keyword[0],$keyword[1],$keyword[2],$keyword[3],$keyword[4]);
$dbh->disconnect;
if($success != 1) {
return "Sorry, the database was unable to add your entry.
Please try again later.";
} else {
return;
}
}
sub show_entries {
my ($dbh, $sth, #row);
my $search = $cgi->param('search');
my $option = $cgi->param('option');
$dbh = DBI->connect("DBI:mysql:database=$serverDb;host=$serverName;port=$serverPort",$serverUser,$serverPass);
$sth = $dbh->prepare("SELECT *
FROM $serverTabl
WHERE $option LIKE '%$search%'");
$sth->execute;
print "Existing Entries",HR;
while(#row = $sth->fetchrow_array) {
$row[5] = scalar(localtime($row[5]));
print "<table border='2'><tr>";
print "<td>" . $row[0] . "</td>";
print "<td>Name" . $row[1] . "</td>";
print "<td>Author" . $row[2] . "</td>";
print "<td>URL" . $row[3] . "</td>";
print "<td>Keyword1" . $row[4] . "</td>";
print "<td>Keyword2" . $row[5] . "</td>";
print "<td>Keyword3" . $row[6] . "</td>";
print "<td>Keyword4" . $row[7] . "</td>";
print "<td>Keyword5" . $row[8] . "</td>";
print "</tr></table>";
}
$sth->finish;
$dbh->disconnect;
}
So now the question is how can I do a regular expression for the form submission before it goes to the second program?
I want to do validation for
name allows spaces but only alphabetical characters
author allows spaces but only alphabetical characters
keywords allows no spaces and only alphabetical characters
url only allows alphanumerical characters and the following :/.~?=+& No two periods can exist consecutively.
I'm really sorry but I'm really new to Perl. We are only been taught about PHP, but Perl almost nothing....
The perluniprops Perl document lists all the \p regular expression properties.
For a string that contains only letters, you want
/^[\p{Alpha}]+$/
For a string that contains only letters and spaces you want
/^[\p{Alpha}\x20]+$/
To match a URL the documentation of the URI module gives this as an official pattern to match a URL
m|^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$|
Be sure to cite the references in your work to get extra marks!

Contact form submit script - HTML email problem

I have a contact form script and when the user submits it, they get an email and I get one. But there's a problem with the "message" textarea in the HTML email. It puts it all in one line.
See how I type it out:
And then in the email sent to me (HTML) its all in one line:
As you can see it is all in one line. How can I get it to not be in this line?
This is my code:
<?php
// load the variables form address bar
$subject = $_POST["subject"];
$message = $_POST["message"];
$from = $_POST["from"];
$name = $_POST["name"];
$verif_box = $_POST["verif_box"];
// remove the backslashes that normally appear when entering " or '
$message = stripslashes($message);
$subject = stripslashes($subject);
$from = stripslashes($from);
$name = stripslashes($name);
$emailContent = "Hello Nathan,
".$name." is trying to contact WeeBuild Support. Here's what they submitted:
<br /><br />
<div style='background-color:#ccc;padding:10px;border:1px solid grey;'>
Name: <strong>".$name."</strong>
<br /><br />
Email: <strong>".$from."</strong>
<br /><br />
Subject: <strong>".$subject."</strong>
<br /><br />
Message:
<br /><br />
<strong>".$message."</strong>
<br /><br /><br />
Their IP Address: <strong>".$_SERVER['REMOTE_ADDR']."</strong>
</div>
<br /><br />
To email them back, simply reply to this message.";
$emailContents = "Hello ".$name.",
Thank you for contacting WeeBuild Support! This email is to let you know that we have received your support request and that we will reply soon.
For your record, here is what you submitted:
-----------------------------------------------------------------------------
Your Name: ".$name."
Your Email: ".$from."
Subject: ".$subject."
Message:
".$message."
-----------------------------------------------------------------------------
In the meanwhile, make sure to add support#weebuild.biz to your contact list/safe senders list so our emails don't end up in your junk folder.
We will be with you shortly!
Kind regards,
WeeBuild Support Team
www.WeeBuild.biz";
$emailContent = stripslashes($emailContent);
$emailContents = stripslashes($emailContents);
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $from . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// check to see if verificaton code was correct
if(md5($verif_box).'a4xn' == $_COOKIE['tntcon']){
// if verification code was correct send the message and show this page
mail("nathan#weebuild.biz", 'WeeBuild Contact Form: "'.$subject.'"', $emailContent, $headers);
mail($from, 'Thank you for contacting WeeBuild Support!', $emailContents, "From: support#weebuild.biz");
// delete the cookie so it cannot sent again by refreshing this page
setcookie('tntcon','');
} else if(isset($message) and $message!=""){
// if verification code was incorrect then return to contact page and show error
header("Location: index.php?name=$name&subject=$subject&from=$from&message=".urlencode($message)."&wrong_code=true");
exit;
} else {
echo "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">
<html><head>
<title>Access Denied</title>
<style type=\"text/css\">
body {
font-family: Arial, sans-serif;
}
</style>
</head><body>
<h1>Access Denied</h1>
<p>This page cannot be accessed directly. The needed variables to submit were not provided.</p>
</body></html>";
exit;
}
?>
Note: $emailContent is the email that goes to me and $emailContents is the email that goes to the user.
I tried using the str_replace() and that just caused parsing problems and I could not get that to work. I'm sure I wasn't using it right.
Can someone help me with this? Any help is highly appreciated.
use nl2br();
So edit this snippet
Message:
".$message."
to
Message:
".nl2br($message)."
You can use nl2br() function on $message to change newlines into <br /> tags.