Cant mail a couple of variables and strings - php

So I am developing a script that will eventually be run as a shell to detect ip address changes by comparing the current ip (
//get_ip.php
<?php
$current_ip = file_get_contents('http://www.ipaddresscheck.comlu.com/ip.php');
?>
)
(if anyone is interested, http://www.ipaddresscheck.comlu.com/ip.php will return ONLY the public IP of your machine/ router)
to the latest one recorded in mysql. Right now, I can't even email out a fake old IP and a real current ip. When i try to email the old and new IPs, it will only work I i put the old ip variable in the spot for the current or nothing at all. it should say
The old IP adresss was --- ".$old_ip."
The new IP address is --- ".$current_ip."
but that won't work. the only thing that works is
The old IP adresss was --- ".$old_ip."
The new IP address is --- ".$old_ip."
or
The old IP adresss was --- ".$old_ip."
The new IP address is ---
<?php
//Get IP
include 'get_ip.php';
//Connect to SQL
mysql_connect('localhost','root','root');
//Select database
mysql_select_db("ip_changes") or die(mysql_error());
//Get Date Info
$date = date("D M Y");
$time = date("H i s");
//Generate SQL query
$sql="INSERT INTO ip (date, time, current_ip)
VALUES ('$date', '$time', '$current_ip')";
//Execute SQL
mysql_query($sql);
//$sqlcurrent = mysql_query(SELECT current_ip FROM ip ORDER BY id DESC LIMIT 1);
echo $current_ip;
$new_ip = $current_ip;
//Send Mail
$old_ip = '192.168.0.1';
$to = "justinmarmorato#gmail.com";
$subject = "IP Address Change";
$message = "Hello! This is an automated message from the IPMS. An IP address chamge has been
detected.
//Right here, I can only send out $old_ip, and nothing else. The date and time at the bottom does work.
The old IP adresss was --- ".$old_ip."
The new IP address is --- ".$old_ip."
The IP address change was detected at ---". $date. ' , '. $time;
$message1 = 'Old IP:'.$old_ip.
'New IP:'.$current_ip;
$from = "no-reply#http://mar-remote-net.dns2.us";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo 'Old IP:'.$old_ip.
'New IP:'.$current_ip;
?>
any suggestions?

No doubt, that it doesn't work, because you are using a wrong variable name:
$message = "Hello! ...";
//why is it called message1?
$message1 = 'Old IP:'.$old_ip. 'New IP:'.$current_ip;
//here you are sending $message
mail($to,$subject,$message,$headers);

I figured it out...
$finalmessage = <<< EOT
Hello! This is an automated message from the IPMS. An IP address change has been detected.
<html>
<style>
table, th, td
{
border: 2px solid black;
border-color:grey;
}
</style>
<table class='table'>
<tr>
<td>Old IP</td><td>New IP</td><td>Time Detected</td>
</tr>
<tr>
<td>$old_ip</td><td>$new_ip</td><td>$date $time</td>
</tr>
</table>
</html>
EOT;

Related

sending an email based on data from MySQL table

I've got email function setup and working by setting the code to email a specific email address. However, with this is that it goes to the same email address everytime the submit button is pressed based on the data entered in a text box who the mail comes from.
However, I want to change it so that when a user enters their username in the username box it checks my database table for that username and checks their email address and emails them all the information set for that user.
The code i'm using is ;
$username = $_POST['username'];
$my_query="SELECT * from loanusers where username = '$username'";
$result= mysqli_query($connection, $my_query);
$to = $myrow["emailaddess"];
$subject = 'CSG - Forgotten Password';
$sender = 'CSGLoanSystem#mail.com';
$password = $myrow["password"];
$admin = 'CSGLoanSystem Admin Team';
$body = <<< EMAIL
Hi {$username}, You have recently requested a notification of your password.
The Password registered with account {$username} is $password.
Thanks - {$admin}
EMAIL;
$header = "From:" . $sender;
if ($result):
mail($to, $subject, $body, $header);
$feedback = 'Email Sent';
endif;
At the moment when the submit button is pressed, the page refreshes but nothing actually happens and no email is received at the expected email address?
Pointing to the right direction:
Read up on MySQL and PDO. Also Read up on prepared statements and parameter binding.
Elaborating on the directions given:
There are many ways to connect to a database, and there are many different databases available. One popular database software is called MySQL, and the coding method that is most recommended to connect to that database is PDO for reasons such as having better methods for preventing security breaches.
You can find a lot of online tutorials on how to connect to a database, so I won't go into that, though I will however give you an example of a query you could use to do your email searching, and also I'll include prepared statements and parameter binding since these two details are often misunderstood by a lot of programmers.
If you have the following table:
users
______________________________
| username | email |
|------------+-----------------|
| john44 | abc#gmail.com |
|------------+-----------------|
| adam11 | 123#gmail.com |
|------------+-----------------|
the following code would allow you to retrieve john44's email:
$username = $_POST['username'];//getting the username written in the form
$sql = "SELECT email FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$username]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//here I'm just outputting the obtained email for you to see
//it works, however you would then use the email saved in
//$result['email'] whichever way you want.
echo "email = {$result['email']}<br>";
Edited:
After you edited your code, I noticed you are not fetching the information you queried. Insert the following code after line $result= mysqli_query($connection, $my_query);:
$myrow = mysqli_fetch_assoc($result);

How to check if an IP is already stored in mysql?

I have this feedback form I made, but I need a bit of help. I want to stop people from posting feedbacks if they already did with the same ip, which is stored in a database. Here is the code:
<?php
if(isset($_POST['add'])){
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
$ip = $_SERVER['REMOTE_ADDR'];
$datetime = date('Y-m-d H:i');
$checkIp = mysql_query("SELECT ip from comments WHERE ip = '$ip'");
if (mysql_num_rows($checkIp) > 0) {
echo "Only 1 feedback per IP allowed!";
$IP = mysql_fetch_array($checkIp);
print_r($IP);
}
if($name){
if($email){
if($comment){
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
mysql_query("INSERT INTO comments (id, name, email, comment, ip, datetime) VALUES ('','$name','$email','$comment','$ip','$datetime')");
}
else
echo "The email address is invalid!<br><br>";
}
else
echo "You haven't entered any comment!<br><br>";
}
else
echo "You haven't entered an email address!<br><br>";
}
else
echo "You haven't entered your name!<br><br>";
}
I tried to have a go myself, but failed (you can see at the top I tried some functions), can someone please tell me how to do it?
You should be using PDO or mysqli_ with prepared statements rather than mysql_ since its deprecated and due to be removed. Also, if you really want IP address to be unique in this table, you should set a unique constraint on the field.
But probably you could get this code working as far as this point (for about 90-98% of cases) simply by adding an exit; in the if-statement where you are checking the number of rows:
if (mysql_num_rows($checkIp) > 0) {
echo "Only 1 feedback per IP allowed!";
$IP = mysql_fetch_array($checkIp);
print_r($IP);
exit; //stop execution here so nothing else happens
}
The code will be open to SQL injection, however, if you continue with mysql_, and it won't be as straightforward and will leave open a technical possibility of somehow ending up with more than one of the same IP in the database.
For example, if two requests came in at once and both read the database as not having the IP yet, then both inserted. With a contraint in the table, that wouldn't happen because the database server would be managing the constraint itself.

Get all rows into a variable then mailto for each PHP

So, I found this thread (Get all data from mysql row in a variable) but I am too much of a beginner to make it apply easily to my situation. Thank you for helping me out... sorry for the total newb questions.
I have a PHP form that lets the user select one of my tables in a database where email addresses are stored to send an email to each of them. Right now, I have this code:
$recipientid = $_POST['recipientid'];
$body = $_POST['body'];
$subject = $_POST['subject'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: SENDER NAME <senderemail#gmail.com>' . "\r\n";
date_default_timezone_set('America/Los_Angeles');
$time = date('m/d/Y h:i:s a', time());
$sendbody = $body . "<br><br>This is a bulk email announcement sent by
the institution.<br><br>It was sent at " . $time . ". If you have any
questions about this message or wish to unsubscribe, please contact
the institution.";
if($recipientid == 'allstudents'){
// SEE NOTE #2//
$recipientlist = //email addresses
}
$process=explode(",",$recipientlist);
reset($process);
foreach ($process as $to) {
$sent=mail($to,$subject,$sendbody,$headers);
}
if ($sent) { //(success echo goes here... it is quite long so i removed it.)
} else {
echo "Email could not be sent, PLEASE CONTACT US.";
}
What is the easiest way to capture all of the email addresses in the column of the specified table and then loop a mailto for each? I was originally trying to get them all into one string and then explode them as you can see, but that might not be the best solution. Am I on the right track here?
(NOTE #2 FROM IF)
HERE IS WHERE I NEED SOMETHING... I was sort of thinking about trying to use the following. I need it to grab all the emails from the column emailaddresses in the table students. I am using an if statement because there are four other things that $recipientid could equal, and each different one grabs email addresses from a different table.
array pg_fetch_all_columns ( resource $result [, int $column = 3 ] ) But then, I don't know how to get this array to work with my mail. I originally tried to use just a SELECT * from emailaddresses and then use each row somehow but I don't know how to implement that.
YES, I know I am using mysql not mysqli and I know that mailto is probably not the best solution, but it is what I have to work with right now (unless you can suggest an alternative route for the mail loop).
Thank you again! I really want to learn what I am doing, so an explanation would be appreciated:)
(and ps I am using the mail function with the explode because of this article http://tutorial.world.edu/web-development/php-script/how-to-send-out-mass-emails-php-script/)
I might be a little confused about the question. It sounds like you have a database with email address and you want to send an email for each email address. I think you can just do the query SELECT emailaddress from table and cycle through the results and use your mail function each time.
$query = *your select query*
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$sent=mail($row['emailadress'],$subject,$sendbody,$headers);
if ($sent) { //(success echo goes here... it is quite long so i removed it.)
} else {
echo "Email could not be sent, PLEASE CONTACT US.";
}
If you want your user to select the table the email addresses are coming from you can use a form and a variable in the query.
You can use the below piece of code to send the mail.
Consider you have an email field in your table 'students'
then
$sel = mysql_query("select email from students");
while($info = mysql_fetch_assoc($sel))
{
$to = $info['email'];
$sent=mail($to,$subject,$sendbody,$headers);
//---Remaining code goes on
}
try it.

Sending form information to emails stored in the database

I have been researching this but cant sem to get an answer.
I have a form that is sending the info to my database, I also want the info to go to email addresses which are stored in a column in my table in the database. Heres the code, I was just playing around to see if I could do a SELECT query but it wouldnt work, also Iknow that sending the email works when I manually ut an address into my "setTo"
require 'mail/class.simple_mail.php';
$mailer = new SimpleMail();
$comments = $_REQUEST['comments'];
$time = $_REQUEST['time'];
$date = $_REQUEST['date'];
$place = $_REQUEST['place'];
$email = "SELECT email FROM bridesmaids";
$message = "<strong>This is an email from the bride to you the bridesmaids, here is the information on the next dress fitting<br />".$date." ".$time." ".$place." ".$comments." </strong>";
$send = $mailer->setTo('$email', 'Your Email')
->setSubject('Dress Fitting')
->setFrom('donaghy-e5#email.ulster.ac.uk', 'Domain.com')
->addMailHeader('Reply-To', 'donaghy-e5#email.ulster.ac.uk', 'Domain.com')
->addMailHeader('Cc', 'donaghy-e5#email.ulster.ac.uk', 'Bill Gates')
->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
->setMessage($message)
->setWrap(100)
->send();
echo ($send) ? 'Your Email has been sent to your bridesmaids' : 'Could not send email';
If you haven't created an SQL connection, do this first then:
1: Select your emails from your bridesmaids table - then return the results into an array (PDO::FETCH_ASSOC or fetch_array(MYSQLI_ASSOC)) and bind this array to a variable e.g. $mailingList.
2: Wrap your mailer code in a foreach loop (http://uk3.php.net/manual/en/control-structures.foreach.php) an example would be:
foreach($mailingList as $value) {
// your mailer code here, replace $email with $value
$send = $mailer->setTo($value, 'Your Email')
// $value will update for each iteration with your emails
}
3: Ensure any code or variables which do not need to be repeated are outside of the loop.
You don't query the database for the actual e-mail adresses. You just have s string that contains an SQL Query but you never actually connect to a database and fetch data using a query.
$email = "SELECT email FROM bridesmaids";
This should become something like this:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($result = $mysqli->query("SELECT email FROM bridesmaids")) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}

Php if else logic Block runs no matter what?

So, Writing this script, and now I do get the correct email, with the old IP address from the database, and the new address from the script. My problem now, is that wether the old ip address and the current are the same or different, the email sends. This script will run every minute to check for dynamic ip address changes, so I don't really want an email every minute. My goal is to have it send the email ONLY if the last posted IP is DIFFERENT from the one discovered. Now, the email is sending wether the IPs are different or not. Everything else works. The email sends fine, and everything else works perfectly. The only problem is using logic to decide when to send the email. (When the new and old IPs are different.)
When the script gets there ip from the database, it looks like 123.123.123.123. The IP from the http://www.ipaddresscheck.comlu.com/ip.php also looks like 123.123.123.123. (***Example) But if the database says 123.123.123.123, and the current is 134.134.134.134, it should send the email.
In the comparison, I've tried !=, ==, and I've tried putting the mail block in the then and else sections. Could the problem be caused by different data types? Is the $new_ip a string while $old_ip is an integer? Im only 14, so... Yea.
<?php
//Get IP
$new_ip = file_get_contents('http://www.ipaddresscheck.comlu.com/ip.php');
//Connect to SQL
mysql_connect('localhost','root','root');
//Select database
mysql_select_db("ip_changes") or die(mysql_error());
//Get Date Info
$date = date("D M Y");
$time = date("H:i:s");
//Get last inserted IP
$sql = mysql_query('SELECT * FROM ip ORDER BY id DESC LIMIT 1');
$row = mysql_fetch_array( $sql );
$old_ip = $row['current_ip'];
echo $old_ip;
//Generate SQL query
$sql="INSERT INTO ip (date, time, current_ip) VALUES ('$date', '$time', '$new_ip')";
//Execute SQL
mysql_query($sql);
//Get latest IP
//$lastip = mysql_query(SELECT $selected FROM ip ORDER BY id DESC LIMIT 1);
if ($old_ip == $current_ip)
{
}
else {
//Set Mail Settings
$to = "justinmarmorato#gmail.com";
$subject = "IP Address Change";
$from = "no-reply#http://mar-remote-net.dns2.us";
$headers = array (
"From:" . $from,
"Content-Type: Text/HTML"
);
//Create email
$finalmessage = <<< EOT
Hello! This is an automated message from the IPMS. An IP address change has been detected.
<html>
<style>
table, th, td
{
border: 2px solid black;
border-color:grey;
}
</style>
<table class='table'>
<tr>
<td>Old IP</td><td>New IP</td><td>Time Detected</td>
</tr>
<tr>
<td>$old_ip</td><td>$new_ip</td><td>$date $time</td>
</tr>
</table>
</html>
EOT;
mail($to,$subject,$finalmessage, implode("\r\n", $headers));
mail('justinmarmorato#gmail.com', 'Hello!', implode("\r\n", $headers));
}
?>
Did you mean to say $new_ip instead of $current_ip in your if statement?
$current_ip doesn't appear to be set anywhere -- if that is the case $current_ip will always be unset and will never be equal to $old_ip.

Categories