Are IMAP email identifiers unique in PHP? - php

My goal is to be able to use a form, checkbox and submit button (delete button) to remove specific emails.
I am starting off with this connection script:
<?php
//Inbox - Connect;
$inbox = imap_open($folder_inbox,$username,$password) or die('Error connecting to Gmail: ' . imap_last_error());
//Grab Inbox Emails;
$inbox_emails = imap_search($inbox,'ALL');
//If there are emails;
if($inbox_emails) {
//Output Arrays;
$inbox_from = array();
$inbox_subject = array();
$inbox_date = array();
$inbox_msg = array();
//Put the newest emails to the top;
rsort($inbox_emails);
//For each email, Give it an email number;
foreach($inbox_emails as $inbox_email_number) {
//Get information specific to this email;
$inbox_overview = imap_fetch_overview($inbox,$inbox_email_number,0);
$str_date = $inbox_overview[0]->date;
include('../func/inbox/grab/datefix.php');
mb_internal_encoding('UTF-8');
//Add email information to the arrays;
$inbox_read[] = $inbox_overview[0]->seen;
$inbox_from[] = str_replace('"',"", str_replace("_"," ", mb_decode_mimeheader($inbox_overview[0]->from)));
$inbox_subject[] = str_replace("_"," ", mb_decode_mimeheader($inbox_overview[0]->subject));
$inbox_date[] = $str_date;
//$inbox_msg[] = imap_fetchbody($inbox,$inbox_email_number,2);
}
}
//Close The Connection;
imap_close($inbox);
?>
I know how to move an email to a trash folder but I am concerned that there might be a race condition between getting a set of IDs for a folder and, a few minutes later, requesting the deletion of one of those items.
For example, I have my form showing 2 email subjects, I click the checkbox related to email 1 which has the id '1', then click the delete button which submits the form. The checkbox will have the name="1" parameter. Now when we submit the form lets say on the submit page it uses post gets the id 1 but lets say before we loaded the PHP file I got a new email wouldn't it incorrectly delete the new email rather then the email we checked?

Related

php should not send email multiple times to same person who reply multiple time with same email

I am New to php . Any help would be greatly appreciated.
My issue is that when user reply to any post with specific id, php sends an email alerting involved users that have previously comment on the post with same id, the problem is if the person has entered 3 reply for that post the user gets 3 emails, Since my database has reply entries from the same user with email for each post multiple times.
This is what is the problem
$to = $row['Email'];
How do I make sure it does not send an email to the user multiple times?
// update data in mysql database
$sql4= "select * from answer WHERE id='$id'";
$result4=mysql_query($sql4);
while($row = mysql_fetch_array($result4))
{
$to = $row[‘email’] ;
// Your subject
$subject="$name Reply on example.com”;
// From
$header="from: Associate <no-reply#example.com>";
// Your message
$message = "$name Reply on example.com\n$comment\nDate and Time=$datetime\nhttps://www.example.com/upload/$img\nfor More Visit https://www.example.com/visit/“;
// send email
$sentmail = mail($to,$subject,$message,$header);
}
Change your query to this: $sql4= "SELECT DISTINCT * FROM answer WHERE id='$id'";
you can add email in array and use array_unique function so your duplicate entry will remove auto.
<?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
?>

Tracking number of clicks on a link - php

I have made a tracking website in php which tracks number of clicks on a specific link - for affiliate links tracking. what I am doing is:
When a user clicks a link provided by my website, he goes to my website which after recording its ip address redirects the user to another address mapped to the link user clicked. A counter increments the number of click after validating ip.
The problem I am facing is that when i compare the number of clicks in my website and that of facebook results, my result is many times more. I don't know what is the cause of that.
My results:
Facebook results:
My question is that why is there a difference? if facebook has some additional checks does someone know what they are? or are they private? or facebook just reduces the number of clicks?
Help would be really appreciated. I am stuck here.
Here is my code to check the visitors ip and increment the click counter:
<?php
require_once "dbdata.php";
if(isset($_GET['linkid']) && !empty($_GET['linkid'])){
$id = $_GET['linkid']; //getting link id to fetch data from database
$ip = $_SERVER['REMOTE_ADDR']; // getting visitors ip address
//database connection
#$db = new mysqli(hostname,username,password,dbname) or die(json_encode(array("status"=>"Can not connect (Database Connection Error)")));
//getting data from table
$query = "select * from links_shared where id = $id ;";
$result_link = $db -> query($query) or die(json_encode(array("status"=>"Error Fetching previous income data")));
$row_link = $result_link-> fetch_assoc();
$link = $row_link['orignal']; //the link to be redirect the user to
header("Location:".$link); //redirected
if($row_link['status'] == "live"){ //status of link should be live
$array_ip = explode(",", $row_link['ip']); //comma sepearted string of ips to array
if(!in_array($ip, $array_ip)){ //check if ip is not already present
$query = "select * from links_deleted where url = '$link' ;"; //getting block list
$result_del = $db -> query($query) or die(json_encode(array("status"=>"Can not select deleted")));
if($result_del -> num_rows <1){ //check if link not in block list
$concat = ",".$ip;
echo $query = "update links_shared set clicks = (clicks + 1), ip = concat(ip,'$concat') where id= $id; ";
$result_update = $db -> query($query) or die(json_encode(array("status"=>"can not update clicks")));
}
}
}
}
?>
Either facebook is invalidating clicks that your script accepts (eg: untrusted IPs, repeated IPs, automatic bot detection...) or more simply facebook only sees clicks from its platform but your script receives all clicks from everywhere.
Of course there could also be a problem with your script itself, but since you don't show it, I can't address that.

Write to a php file via wordpress

I've built a web page that is able to send text messages to employees at the company where I work. With new employees being added and removed on a constant basis, I want to integrate this app with wordpress where the employees can be managed without editing the code.
Each post would contain the user's name and phone number. The name would be pulled in on the webpage as an option for the user to contact. When the form is submitted, it would go to a php form that runs an if/else to find the employee and match that employee with their phone number like so:
//Who the text message is to, Establish their phone #
if($employee == 'brad'):
$text_to[] = '+15555555555';
elseif ($employee == 'mary'):
$text_to[] = '+15555555555';
elseif ($employee == 'tom'):
$text_to[] = '+15555555555';
elseif ($employee == 'bill'):
$text_to[] = '+15555555555';
elseif ($employee == 'joe'):
endif;
I want to be able to not only pull these names from wordpress via a loop to display onto my page, but also to be able to add or remove the new entries, along with their phone number, to this php contact form.
I know how to loop through the wordpress posts to display the names on the page. I want to know if it's possible to also use this data to modify this contact form, and if so, how to set this up. Each time someone edits the wordpress entry for Joe, the PHP form gets this update so that when Joe is sent a message, it finds his phone number and sends him the message.
Any help is greatly appreciated. I should also note that I'm using Twilio to send the texts messages.
The use of a DMBS works well, but is not the only solution.
include 'users.inc'; // flat file creating array $userList
which could be an array( ofArrays ) for complex structures
[assume $userList = array($user => $phone, ...); ]
then foreach( $userList as $user => $phone ) { // process($user, $phone); }
Kudos for trying to solve a simple problem yourself. It's obvious that you are new to the idea of databases, and quite frankly, you're doing this the wrong way.
Let's talk about how your initial approach can be improved:
Each post would contain the user's name and phone number.
Perhaps instead of posts, we have one database table to store employee information.
You'll find tons of information on databases and how to use them with your wordpress account with a simple google search.
I want to be able to not only pull these names from wordpress via a loop to display onto my page, but also to be able to add or remove the new entries, along with their phone number, to this php contact form.
Again, if you had a database to store employee information, this is basic.
For example, an employees database table may have the following columns:
id
name
phone
created_at
updated_at
Since PHP has built in functions for communicating with a MYSQL database (which is most likely what WordPress is already using), you can do things like:
Get all employee data
SELECT * FROM employees
Get a certain employee's data
SELECT * FROM employees WHERE name = '$name'
$name is a variable that can be set via POST request from a WordPress form
Update a certain employee's data
UPDATE employees SET phone = '+15555555555' WHERE name = '$name'
Remove a certain employee's data
DELETE FROM employees WHERE id = 5
You are also able to do things like:
SELECT * FROM employees WHERE created_at > '3/1/2015'
Which will return all employees that were added after 3/1/15.
So everything that you all suggested was helpful. I may have not been as clear as I could have that I really needed the creation/editing/deletion of entries to be done via wordpress posts. I was able to set it up like this by doing the following:
//pull variables from html form input. Employee variables are post ID's that I will then be able to use to retrieve the post_content which contains their phone numbers
$employee1 = $_POST['employeeName1'];
$employee2 = $_POST['employeeName2'];
$employee3 = $_POST['employeeName3'];
$customMsg = $_POST["textMessage"];
//Create array from above variables and exclude any that lack post data
$employees = array($employee1, $employee2, $employee3);
$setEmployeeIDs = array();
foreach ($employees as $employee) {
if (!empty($employee)) {
$setEmployeeIDs[] = $employee;
}
}
$servername = "xxxx";
$username = "xxxx";
$password = "xxxx";
$dbname = "xxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Get array of Phone Numbers connected to each ID and add to array
$sql = "SELECT * FROM wp_posts WHERE ID IN (".implode(',',$setEmployeeIDs).")";
$result = $conn->query($sql);
$phoneNumbers = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$phoneNumbers[] = $row["post_content"] ;
}
} else {
echo "0 results";
}
$conn->close();
So to sum it up, I used wordpress to publish/edit/delete that data as posts, then sent the ID's selected from the webpage to the php form, and then was able to retrieve the phone numbers from the SQL database using Raphael's direction.

Only members can submit this form php

New to php. I have a form that is only for members to submit. What php code do I need for the form to check that the email address on the form is found my members database and then its okay to submit the form?
If email address is not in the members database then I want to echo "Only members can submit this form." What php code do I need to connect to database in the form and do the check so I don't get forms submitted from non members?
Thanks
At the top of your php file you could do something like this:
if(isset($_POST['email'])) {
mysql_connect("hostname","username","password");
$result = mysql_query("SELECT * FROM users WHERE email = '".mysql_real_escape_string($_POST['email'])."'");
if($row = mysql_fetch_array($result)) {
// found email
} else {
// email wasn't found
}
}
Of course you would need to replace the hostname, username and password to correct values, also you should change the users and email in the select query to the name of your table and field.
Here is a dummy form:
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<input type="text" name="email" />
<input type="submit" value="Send" />
</form>
You want to study Mysql query and other mysql functions. The code would basically look like:
$c = mysql_connect( ...);
mysql_select_db( 'database', $c);
$q = mysql_query( "SELECT COUNT(*) FROM users WHERE email = '" .
mysql_real_escape_string( $_POST['email'],$c) . "'");
$row = mysql_fetch_row( $q);
if( $row[0]){
echo "Thanks for submitting...";
} else {
echo "Only members...";
}
This is only brief example which is far from perfection but I think it's good place for you to start.
If someone is a registered member that implies you're very likely using a $_SESSION['id_member'] variable.
This will set the cookie's name that can be seen by the client to 'member'...
if (!headers_sent() && !isset($_SESSION))
{
session_name('member');
}
...then when a user authenticates assign a session variable and their permission...
$_SESSION['member_id'] = $mysql_row['id'];
$_SESSION['member_status'] = $mysql_row['id'];
Here is a status hierarchy that you might use or change but it should be a good point of reference...
10 - Super Admin (only you)
9 - Admin// mid-level admin
8 - Assistant//restrictive admin
7 - Moderator//Don't give this status to any jerks
6 - Premium Member//they gave you money!
5 - Registered Member//normal account status
4 - Frozen Account//not banned but did something wrong, will "thaw"
3 - Unverified Email Address//registered but did not verify email
2 - Unregistered Visitor//human
1 - Good Bots
0 - Banned
Generally first determine how to catch the form...
if ($_SERVER['REQUEST_METHOD']=='GET')
{
}
else if ($_SERVER['REQUEST_METHOD']=='POST')
{
if (isset($_POST['submit_button_name_value'])) {blog_post_ajax_comment();}
}
I add the name="value" attribute/value to submit buttons, why? Have two submit options (preview and publish in example) you may want to have the server trigger one function or the other, VERY simple and valid (X)HTML.
You should check if the variable isset (keep permissions in mind).
Then check if their user permissions are adequate, you can use a simple integer to represent this.
Then wrap the isset and permission if statements around two things, one the form and secondly make sure you use these conditions when PROCESSING the form.
I always test against things to reject and throwing in database query error handling to give you a little extra boost...
//function module_method_ajax_purpose()
function blog_post_ajax_comment()
{
if (!isset($_SESSION['member'])) {http_report('403',__FUNCTION__,'Error: you must be signed in to do that.');}
else if ($_SESSION['member_status']<=4) {http_report('403',__FUNCTION__,'Error: permission denied; your account has been flagged for abuse.');}
else if (flood_control($datetime,'60')!=1) {http_report('403',__FUNCTION__,'Error: you can only post a comment once every X seconds.');}
else if (!isset($_POST['post_form_name_1']) || !isset($_POST['post_form_name_2'])) {http_report('403',__FUNCTION__,'Error: permission denied.');}
else
{
// NOW process
$query1 = "SELECT * FROM table";
$result1 = mysql_query($query1);
if ($result1)
{
//successful, increment query number for further queries
}
else {mysql_error_report($query1,mysql_error(),__FUNCTION__);}
}
Error reporting is VERY powerful, use it for HTTP, JavaScript, PHP and MySQL. You could also benefit from my answer about real-time log reading here: jQueryUI tabs and Firefox: getBBox broken?

how can I pull out the contents from an email and write them in a mysql table?

How can I make it so when a user email's to my email address their email text/information is written into a mysql table? So basically extract the contents of a new email and write them into mysql table.
I tried this but I get nothing:
<?php
$imap = imap_open("{gmail.com}", "username", "password");
if( $imap ) {
//Check no.of.msgs
$num = imap_num_msg($imap)
//if there is a message in your inbox
if( $num >0 ) {
//read that mail recently arrived
echo imap_qprint(imap_body($imap, $num));
}
//close the stream
imap_close($imap);
}
?>
We are using an exchange server..I am a coop student so I am not really advanced at this.
I tried this as a test to see if it works, logging in gmail to read email. It didnt work.
<?php
// connect to the mailbox
$m_mail = imap_open("{mail.https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2}INBOX", "username", "password");
//get all messages
$m_search=imap_search ($m_mail, 'ALL ');
// Order results starting from newest message
rsort($m_search);
//loop through and do what's necessary
foreach ($m_search as $onem) {
//get imap header info for obj thang
$headers = imap_headerinfo($m_mail, $onem);
$head = imap_fetchheader($m_mail, $headers->Msgno);
$body = imap_body($m_mail, $headers->Msgno, FT_INTERNAL );
echo $body;
}
//purge messages (if necessary)
imap_expunge($m_mail);
//close mailbox
imap_close($m_mail);
?>
use IMAP functions for that. Set up another email account if necessary. Here's the example code:
// connect to the mailbox
$m_mail = imap_open("{mail.YOURHOST.com:993/imap/ssl/novalidate-cert}INBOX", "address#YOURHOST.com", "YOURPASSWORD");
//get all messages
$m_search=imap_search ($m_mail, 'ALL ');
// Order results starting from newest message
rsort($m_search);
//loop through and do what's necessary
foreach ($m_search as $onem) {
//get imap header info for obj thang
$headers = imap_headerinfo($m_mail, $onem);
$head = imap_fetchheader($m_mail, $headers->Msgno);
$body = imap_body($m_mail, $headers->Msgno, FT_INTERNAL );
//
DO WHAT YOU NEED TO DO HERE - insert to the database, etc
}
//purge messages (if necessary)
imap_expunge($m_mail);
//close mailbox
imap_close($m_mail);
read your mailbox via pop3 or imap and add the new emails to your database
Take a look a this class: http://php.net/manual/en/book.imap.php
you could read the pop3/imap in some intervals.
other method would be to redirect your email to a php script. I don't know which email system you are using on your server but here is an example with postfix.
the pop3/imap method is easier and you don't need to edit your server configs but the second method is faster because your script will start as it receives an email.

Categories