how to delete mysql table row from mail inbox - php

I want to delete mysql table row from mail inbox , Is it possible !, If yes how can i delete the table row in my server database from any mail inbox account, please tell me the solution
Table Structure:
id usrname password status usercat
1 xxxxxxx xxxxxxx new 1
2 uuuuuuu uuuuuuu new 5
$del_qry= mysql_query("DELETE FROM table_name WHERE some_column=some_value")
In my site after Registration, the registered person get alert mail and also site admin get registered user detail's mail. So if the admin want to delete the second user(username - uuuuuu) from his mail account.
How can i do this, Please tell me i am new here...

The email you send to the admin will have to contain a link like this:
http://www.example.org/admin/remove_account.php?id=123
Where 123 is the user that was registered and remove_account.php is the script that will be loaded when the link is clicked.
Within the script you would have something like this:
mysql_query("DELETE FROM table_name WHERE id=" . mysql_real_escape_string($_GET['id']));
CAUTION
A few words of caution. The above link should be protected by one of the following:
User & password protection (either using Apache or PHP)
Signature protection (example below)
The signature protection prevents tampering / forging link parameters by adding a signature. Works like this:
$secret = "some reasonably long string of random data";
$id = "123"; // like above, the user id
$sig = hash_hmac('sha1', $id, $secret);
$link = 'http://www.example.org/admin/remove_account.php?' . http_build_query(array(
'id' => $id,
'sig' => $sig,
));
To verify the signature:
$secret = "some reasonably long string of random data";
if (isset($_GET['id'], $_GET['sig'])) {
$calc_sig = hash_hmac('sha1', $_GET['id'], $secret);
if ($calc_sig === $_GET['sig']) {
// your delete query here
}
}
Please note that, although the link protects against someone trying to access your administrative script, if it falls in the wrong hands you're still pretty much screwed. Don't underestimate security :)

I think you must add a link of a page of your site in email of delete with respect of user list. and when user click on link it will redirect to particular page where it will get that user id from url of link and then you can perform delete action. It is necessary to redirect to site page from mail because in mail you can not direct connect with database.
thanks

Related

how to protect an ID in the url with php?

For a simple mailinglist, i use flat-file (.txt) files for storing the date from subscribers.
The name of the .txt files is the same as the id i assign to a subscriber.
A .txt file with the data inside (name and email) looks so something like this:
id-8759874589.txt
In every email i send, i send an unsubscribe link so that the subscriber can unsubscribe from receiving mails. I encode the unsubscribe link with base64_encode. Only for the mask of the eye.
An unsubscribe-link looks something like this:
http://example.com/unsubscribe.php?id=aWQtMjAxOTEyMjMNDUyMTQ%3D&email=amNtZy5tYWVzc2VuQGdtYWlsLmNvbQ%3D%3D
For unsubscribing, i use this code:
<?php
$id = $_GET['id'];
$email = $_GET['email'];
// decode the id and email string
$id_decode = base64_decode($id);
$email_decode = base64_decode($email);
if( isset($id_decode) ) {
$filename = 'subscribers/'.$id_decode.'.txt';
// delete subscribers entry
if(file_exists($filename)) {
unlink($filename);
echo '<div class="alert alert-success"><b>'.$email_decode.'</b> is successfully removed from our mailinglist!</div>';
}
else {
echo '<div class="alert alert-danger">Email not found or you already have unsubscribed from our mailinglist!</div>';
}
}
?>
As you can see: the id, which is assigned to the .txt file, will be unlinked. The subscriber is deleted from the mailinglist.
My worries:
Lets say: you were a subscriber and you did unsubscribe, then you know how the url is created.
You can start guessing: How will the subscriber be unsubscribed? Lets say: you know that every subscriber has his data in a .txt file with the name of the id. You can let a robot guess the identities in the url string and execute this url. In worse case scenario, he found an id that really exists and the file will be deleted. A random subscriber is removed from the list without doing itself.
How can i protect this better?
Create a unique code and store this code in the file, also provide this code in unsubscribe url:
http://example.com/unsubscribe.php?id=aWQtMjAxOTEyMjMNDUyMTQ%3D&email=amNtZy5tYWVzc2VuQGdtYWlsLmNvbQ%3D%3D&token=WHATEVER
In this case you can also get a token from url as $_GET['token'] and check if it is the same as one in the file. If it is the same (and no one except you knows the algorithm with which token is created) - you can unsubscribe the user. In case of failure you can consider that someone is cheating)
You should worry when you only encode your parameters.
As you already expected gives Base64 no security, also the fact that you expect an Id and a email gives information to hack you.
The third risk is your response, there you als give information away, just inform your that the request is processed.
You should use encryption see to be safe.

A secure enough way of identifying and activating a user in MySQL PHP with a URL

Is checking against my table with the user's email and dedicated hash enough to verify and activate an account if a match is found against those two values?
A user is asked to register themselves with user data and their email id. They are then sent a URL to their email which they are asked to click on to confirm and activate their account.
This is my current setup:
<?php //The user-account-creation processing page
$email_id = taken from user input;
$randomnessWhateverItsCalled = "lots-of-randomness-here";
UPDATE advert SET advert_hash = SHA1(CONCAT($email_id, $randomnessWhateverItsCalled))
//For simplicity's sake I omitted the PDO stuff
INSERT INTO table_name (..., user_email, hash, account_activated, ...) VALUES (..., usersEmail, advert_hash, NO, ...)
/**
Send an email with some php code with the URL that would look like this
URL to click on attached to email body:
*/
$attachStringToEmailBody = "http://www.domainname.com/activate-user?email_id=" . $usersEmail . "&hash=" . $randomnessWhateverItsCalled;
enter code here
//Send email from this process page with a little email php code
//Redirect user to a page informing the user to activate the account by visiting their email and clicking on the url
?>
Then in the activate-user.php page I have the following:
<?ph
$user_email = $_GET['email_id'];
$hash = $_GET['hash'];
/**
search database and return a row if there is a match containing both the $user_email and the $hash
if(match){
Update database and set the `account_activated` column to `YES`
}
else{
//Tell if there was no match then activation failed
//Let the user know that we do not recognise the link they used to try and activate their account.
}
*/
?>
It seems secure enough, as long as you made the "randomness" part hard to guess. You can put there the email, username, password, etc. and mix them up with another key - all encrypted - that's what I usually do.
But I would advise you to use 0/1 for active/inactive - why using strings, when you can do the same with smallint (1) - and save some space, thus making the database a bit lighter ?

Auto Login from email link and PHP?

I'm trying to create a link that when clicked will login a user automatically and take them to a specific page.
I've thought about creating some sort of hashed string that contains the user's ID, username and a few other pieces of info. When clicked these pieces of information are looked up in the DB and if validated I login them in and redirect them to a specific page.
For sites like Twitter and Facebook when I receive an email notification and click the link in my email I'm automatically taken to my inbox on the corresponding site. I'm trying to duplicate that behavior...
Are there any security issues with doing something like this or is there a safer more preferred way?
if you want to offer this feature to your users, you have to take care of two things:
The validity of the created url must be set in time (ex: 24hours, 48hours).
The created url must only work for one specific user.
(optionnal) The created url only work for one page
I propose this kind of solution to create an url which match these criteria (it's only a proof of concept):
<?php
$privateKey = 'somethingVerySecret';
$userName = 'cedric';
$url = 'my/personal/url';
$timeLimit = new DateTime('Tomorow');
function createToken($privateKey, $url, $userName, $timeLimit){
return hash('sha256', $privateKey.$url.$userName.$timeLimit);
}
function createUrl($privateKey, $url, $userName, $timeLimit){
$hash = createToken($privateKey, $url, $userName, $timeLimit->getTimestamp());
$autoLoginUrl = http_build_query(array(
'name' => $userName,
'timeLimit' => $timeLimit,
'token' => $hash
));
return $url.'?'.$autoLoginUrl;
}
function checkUrl($privateKey){
if((int)$_GET['timeLimit'] > time() ){
return false;
}
//check the user credentials (he exists, he have right on this page)
$hash = createToken($privateKey, $_SERVER['PHP_SELF'], $_GET['name'], $_GET['timeLimit']);
return ($_GET['token'] == $hash);
}
The general standard for logging in is when a user creates an account your program should create a string of seemly random letters and numbers with a certain php function in php 5.5, and then store this in a file with some sort of pointer based on the username. Then when a user tries to login you use that same function and compare the two strings. The function being hash_pbkdf2 even though this php function supports sha... encryptions do not use those. I salt the hash code with the username. Here is an article on all website login and password things. The most secure thing you can do with your website to prevent people from brute force cracking your passwords is to limit the connection speed after a couple wrong password attempt to something so slow it would take longer than the life of the universe to crack after a couple password attempts. If you wanted to make a sort of remember me button store the username in cookies But never the password the browser will take care of the remembering password part if you label your form elements correctly.

"Issue viewing email? View email online?" unique link in Codeigniter email

I'm not sure where to begin with this task, so I'm looking for an answer on just the idea of how to go about doing this.
When a new user creates an account on my Codeigniter site I send him/her an email about signing up (very typical). Here is how I'm sending the email...
...
$subject = 'Welcome to __________, ' . $firstName . '!';
$emailData = array(
'name' => $name,
'blah' => $blah,
'blah' => $blah,
// etc.
);
$html_email = $this->load->view('emails/signup_html_view', $emailData, true);
$text_email = $this->load->view('emails/signup_text_view', $emailData, true);
$this->email->from('team#_________.com', '________ Team');
$this->email->to($to);
$this->email->subject($subject);
$this->email->message($html_email);
$this->email->set_alt_message($text_email);
$this->email->send();
...
As you can see, I'm passing data to those views to send the email. In the email view, at the top, I have a link that says "Problem viewing email? Click here to view it online.". That is common practice for emails on newsletters, signups emails, etc. so that the user can view the email online if it renders weird or something goes wrong.
Where I'm getting lost is how do I generate that unique "...view it online." link so that when the user clicks it, they see an online version of the email and the online version still has all the data still passed to it? Do I need to create a separate controller or what is the best way to handle that? How do I generate that unique link?
#zach,
yes, what you do is:
1) create a separate controller that can display this email, just like you were making a page
2) I'm assuming the user is already created in the db, but is not yet activated or taken steps to be able to login. So, backing up a bit, when you make your user record, also create a random hashtag & store that.
Now, in the email link, set it to www.mysite.com/welcome/hashtag
This way you are allowing them to get a unique record without using an id that they could just use to go look at everyone else
This welcome page, of course, doesn't require them to be logged in. Probably you give them a submit (maybe after they fill out some more info) that will then activate their account
Hope that was close enough to what you were asking to get you through

Drupal's profile_save_profile Doesn't Work in hook_cron, When Run by the Server's cron

I have a problem with the following implementation of hook_cron in Drupal 6.1.3.
The script below runs exactly as expected: it sends a welcome letter to new members, and updates a hidden field in their profile to designate that the letter has been sent. There are no errors in the letter, all new members are accounted for, etc.
The problem is that the last line -- updating the profile -- doesn't seem to work when Drupal cron is invoked by the 'real' cron on the server.
When I run cron manually (such as via /admin/reports/status/run-cron) the profile fields get updated as expected.
Any suggestions as to what might be causing this?
(Note, since someone will suggest it: members join by means outside of Drupal, and are uploaded to Drupal nightly, so Drupal's built-in welcome letters won't work (I think).)
<?php
function foo_cron() {
// Find users who have not received the new member letter,
// and send them a welcome email
// Get users who have not recd a message, as per the profile value setting
$pending_count_sql = "SELECT COUNT(*) FROM {profile_values} v
WHERE (v.value = 0) AND (v.fid = 7)"; //fid 7 is the profile field for profile_intro_email_sent
if (db_result(db_query($pending_count_sql))) {
// Load the message template, since we
// know we have users to feed into it.
$email_template_file = "/home/foo/public_html/drupal/" .
drupal_get_path('module', 'foo') .
"/emails/foo-new-member-email-template.txt";
$email_template_data = file_get_contents($email_template_file);
fclose($email_template_fh);
//We'll just pull the uid, since we have to run user_load anyway
$query = "SELECT v.uid FROM {profile_values} v
WHERE (v.value = 0) AND (v.fid = 7)";
$result = db_query(($query));
// Loop through the uids, loading profiles so as to access string replacement variables
while ($item = db_fetch_object($result)) {
$new_member = user_load($item->uid);
$translation_key = array(
// ... code that generates the string replacement array ...
);
// Compose the email component of the message, and send to user
$email_text = t($email_template_data, $translation_key);
$language = user_preferred_language($new_member); // use member's language preference
$params['subject'] = 'New Member Benefits - Welcome to FOO!';
$params['content-type'] = 'text/plain; charset=UTF-8; format=flowed;';
$params['content'] = $email_text;
drupal_mail('foo', 'welcome_letter', $new_member->mail, $language, $params, 'webmaster#foo.org');
// Mark the user's profile to indicate that the message was sent
$change = array(
// Rebuild all of the profile fields in this category,
// since they'll be deleted otherwise
'profile_first_name' => $new_member->profile_first_name,
'profile_last_name' => $new_member->profile_last_name,
'profile_intro_email_sent' => 1);
profile_save_profile($change, $new_member, "Membership Data");
}
}
}
To safely switch users
http://api.drupal.org/api/function/session_save_session/6
<?php
global $user;
$original_user = $user;
session_save_session(FALSE); // D7: use drupal_save_session(FALSE);
$user = user_load(array('uid' => 1)); // D7: use user_load(1);
// Take your action here where you pretend to be the user with UID = 1 (typically the admin user on a site)
// If your code fails, it's not a problem because the session will not be saved
$user = $original_user;
session_save_session(TRUE); // // D7: use drupal_save_session(TRUE);
// From here on the $user is back to normal so it's OK for the session to be saved
?>
Taken from here:
drupal dot org/node/218104
yes i confirm drupal cron user profile is "anonymous" so you have to add the permission de manager user for the "anonymous" user which is not very good in term of security ..
Not quite a random guess ... but close ...
When "real" cron runs code, it runs it as a particular user.
Similarly, when you run the Drupal cron code manually, the code will also be running as a particular user.
My suspicion is that the two users are different, with different permissions, and that's causing the failure.
Does the cron job's user have access to write the database, or read only?
Are there any log files generated by the cron job?
Update: By 'user' above, I'm referring to the user accounts on the host server, not Drupal accounts. For example, on a sandbox system I use for testing Drupal changes, Apache runs under the noone account.
profile_save_profile dosn't check for permissions or as far as I can see do 'global $user' so I don't know if this is the real issue.
$new_member = user_load($item->uid);
This looks wrong user_load should take an array not a uid (unless you are using Drupal7), but if that didn't work the rest of the code would fail too.

Categories