I am trying to get a server script to use wp_mail() and send an email to a user. I am doing this as part of a password reset routine, and calling the script with Ajax from the user's side.
I am getting the following error from my server script:
Fatal error: Call to undefined function wp_mail() in /var/www/abc-php/pwd.php on line 57
I cannot seem to find an answer to my question, so maybe I am asking incorrectly. Is what I am doing possible?
My server script (pwd.php) contains:
<?php
$setFromId = "info#abc.com.au";
$setFromName = "Info # abc";
$replyToId = "info#abc.com.au";
$replyToName = "Info # abc";
$sendToEmail = base64_decode($_GET["ste"]); //the URL in AJAX call contains base64 encoded data
$resetPwd = base64_decode($_GET["rp"]);
$resetSalt = base64_decode($_GET["rs"]);
$param = $_GET["var"];
$username = "xxxxxxxxx";
$password = "xxxxxxxx";
$host = "localhost";
$database = "xxxxxxxxx";
$con = mysqli_connect($host, $username, $password, $database);
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
switch ($param) {
case "PWDRES": // Query 1: Current Logged In Partner Details
$mysqli = new mysqli($host, $username, $password, $database);
if (mysqli_connect_errno()) {
echo '<p>Unable to connect to the server at this time to update and send password. Please contact SMA for help or try again.</p>';
} else {
$myquery = "UPDATE abc_users
SET `password` = SHA2('" . $resetPwd . $resetSalt . "', 512),
`salt_value` = SHA2('" . $resetSalt . "', 512)
WHERE email_user_id = '" . $sendToEmail . "'";
mysqli_query($mysqli, $myquery);
if($mysqli->affected_rows >= 1) {
$headers = 'Reply-To: <' . $replyToName . '> ' . $replyToId;
$subject = "Password Reset - Confidential";
$body = "Subject: " . $subject . "<br/><br/>Your new password is: <br/><strong>" . $resetPwd . "</strong><br/><br/>Please ensure you reset this password next time you log in.";
$mail = wp_mail($sendToEmail, $subject, $body, $headers);
echo "Password was successfully reset and sent to " . $sendToEmail;
} else if($mysqli->affected_rows == 0) {
echo "No user id row was updated in the process of resetting password. Please try again.";
} else if($mysqli->affected_rows < 0) {
echo "There was an SQL error updating the user id password table. Please contact SMA for help.";
};
};
break;
case "OTHER1"
etc, etc, etc...
default;
};
};
unset($con);
unset($myquery);
unset($mysqli);
?>
Any help is appreciated.
You need to include wp-load.php in your file....
Just put this in top of your file.
require_once( dirname(__FILE__) . '/wp-load.php' );
The problem is you are not including Wordpress, so you are not using it at all (and it isn't including its libraries).
Plus, this is unrelated to the question, but you have a weakness in your code :
Any users can define the recipient of the email.
Related
I´m working on a script in PHP that reads all mails in INBOX, detects special mails via Header-Info and moves processed mails into a folder. I want to exclude this folder from further reading, at the moment my script also finds mails that are already in the processed folder. I´m using the imap_open function like this:
$host = "{" . HOST . ":" . PORT . "/imap/ssl/novalidate-cert}INBOX";
$email = EMAIL;
$password = PASSWORD;
$imap = imap_open($host, $email, $password) or die("Cannot Connect " . imap_last_error());
$emailIds = imap_search($imap, 'FROM ' . SCAN_EMAIL_FOR_OFFERS, SE_UID);
if (!empty($emailIds)) {
foreach ($emailIds as $emailId) {
$email = new readMail();
$header = $email->get_headerinfo($imap, $emailId);
if (strpos($header->subject, "Angebot Nr.") != false) {
...Doing stuff...
$email->move_mail($imap, $emailId, MOVE_PROCESSED_TO_FOLDER);
}
}
} else {
echo "No new offers.";
}
imap_close($imap);
Regards
Edit: This is the move-func of readMail-Class...
function move_mail($imap, $uid, $inboxFolder) {
$msgNo = imap_msgno($imap, $uid);
$movingMail = imap_mail_move($imap, $msgNo, 'INBOX/'. $inboxFolder);
if($movingMail == false) {die(imap_last_error());}
}
I have this script here:
<?php
//Tell the requester to output response as JSON
//header('Content-Type: application/json;charset=utf-8');
//POST information.
$name = $_POST['username'];
$pass = $_POST['password'];
$mysql_server = 'localhost';
$mysql_user = 'root';
$mysql_pass = '';
$mysql_dbname = 'test';
//Set up variables needed for middle-end
$return_code = 0;
$error_message = '';
//Connect to the Database
$conn = new mysqli($mysql_server, $mysql_user, $mysql_pass, $mysql_dbname);
if ($conn->connect_error)
{
//Return an error (in JSON format) that MySQL server wont connect
$return_code = -1;
$error_message = 'Failed to connect to MySQL: ' . $conn->connect_error;
}
else
{
//Query for a User/Pass match
$sqlquery = "SELECT ucid FROM test WHERE ucid = '" . $name . "' AND password = '" . hash('sha256', $pass) . "'";
$result = mysqli_query($conn, $sqlquery);
if (mysqli_num_rows($result) > 0)
{
//On Successful User/Pass
$return_code = 1;
}
elseif(mysqli_num_rows($result) == 0)
{
//On Failed User/Pass
$return_code = 0;
$error_message = 'Incorrect Username or Password';
}
else
{
//Something went wrong
$return_code = -1;
$error_message = 'You messed something up real good.';
}
}
if($return_code == 1)
{
$jsonResults = array('return_code' => $return_code);
}
elseif ($return_code == (0 || -1))
{
$jsonResults = array('return_code' => $return_code, 'error_message' => $error_message);
}
$echoJSON = json_encode($jsonResults, 1);
echo $echoJSON;
echo '<br><br>';
echo 'return code = ' . $return_code . ' and message: ' . $error_message;
echo '<br>Query Passed: ' . $sqlquery;
echo 'Username passed was: ' . $name . 'and Password passed was: ' . $pass;
?>
Basically put, you pass it a username & password, the script then connects to a MySQL server and does a SQL query of the username + the password after its been sha256 hashed. The point of the query is to see if the username + password is valid combination. If one of them is wrong, the query should show 0 results, thus resulting in an 'Incorrect username or password' message
However, when I run the script and echo the results, apparently nothing is getting passed:
<b>Notice</b>: Undefined variable: jsonResults in <b>C:\xampp\htdocs\alpha-test\db.php</b> on line <b>62</b><br />
null<br><br>return code = 0 and message: Incorrect Username or Password<br>Query Passed: SELECT ucid FROM test WHERE ucid = '' AND password = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'Username passed was: and Password passed was:
I do not know what I am doing wrong.
The problem seems to be something to do with postman ( I've never used that ). The best way to test this is to create a form on a new page and actually post the data and make sure that is working.
1) When I can't figure out why something doesn't work, I simplify the problem and reduce the possibility of other errors causing problems. So change your php script by adding these lines.
$name = $_POST['username'];
echo $name;
exit;
You need to make sure $name is getting set.
2) Create a form that posts to this page.
<form action="yourscript.php" method="post">
username: <input type=text name="username"><br>
password: <input type=text name="password"><br>
<input type=submit value="submit">
</form>
Submit the form and make sure you are capturing $_POST['username'] and $_POST['password'] before you worry about mysql or other issues.
3) Just so you know, I tried this locally and I had no problems posting that form and then having $name be set correctly. So the problem must be something to do with how you setup postman.
GL
<b>Notice</b>: Undefined variable: jsonResults in <b>C:\xampp\htdocs\alpha-test\db.php</b> on line <b>62</b><br />
First thing I notices the above error, To remove this, you should declare $jsonResults globally, currently its scope is local to block where you are setting values in this.
Next issue is blank username and password, for this please share your form, from where you are sending these. Possibly you are missing name property or some spelling error.
You are using $_POST to retrieve GET parameters. This is why you fail to get the username / password.
As you said, your are testing with this request, which means you are passing the parameters in the URL:
alpha-test/db.php?username=test&password=test
You must replace $_GET with $_POST or $_REQUEST. I've written a simple working code below. I use here $_REQUEST to be able to retrieve GET/POST variables using the same code.
<?php
//POST information.
$name = $_REQUEST['username'];
$pass = $_REQUEST['password'];
$sqlquery = "SELECT ucid FROM test WHERE ucid = '" . $name . "'' AND password = '" . hash('sha256', $pass) . "'";
echo $sqlquery;
?>
<?php
ini_set('error_reporting', E_ALL);
//create empty Variable
$username= $password= $email="";
//check the field is not empty
if (empty(($_POST["Username"]))) {
echo "Username should not be empty";
} else {
if (!empty(($_POST["Username"]=="/^[a-zA-Z0-9_-.]{3,15}$/"))) {
echo "Username should contain character,number,dash,underscore,dot only";
}
}
if (empty(($_POST["Password"]))) {
echo "password should not be empty";
} else {
if (!empty(($_POST["Password"]=="/^[a-zA-z0-9#]{3,15}$/"))) {
echo "Password should contain character,number,# only";
}
}
if (empty($_POST["Email"])) {
echo "Email field should not be empty";
} else {
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email = "Invalid email format";
}
}
//connect to Mysql Database
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->select_db("spinjobs");
//check if the username already exits in database table
if(isset($_POST["$username"]) && $_POST["$username"] != ""){
$sql_username = mysqli_query("SELECT id FROM newuser WHERE username='$username' LIMIT 1");
$username = mysqli_num_rows($sql_username);
if ($username < 1) {
echo '<strong>' . $username . '</strong> is OK';
exit();
} else {
echo '<strong>' . $username . '</strong> is taken';
exit();
}
}
$query = "INSERT INTO `newuser` ( `username`, `email`, `password`) VALUES ( '$username', '$email', '$password')";
$result = mysqli_query($conn, $query);
if (mysqli_affected_rows($conn) == 1) { //If the Insert Query was successfull.
// Send an email
$from = 'donotreply#spinfonet.com';
$to = $email;
$subject ='You are successfully Registered with us';
$message = 'Your $username, $password\r\n Please preserve this mail for your reference';
mail($from, $to, $subject, $message);
}
mysqli_close($conn);
?>
I am using GoDaddy as web host and upload this code file to my webhost space. I have Linux operating system with web host, while I type code on Notepad++ in Windows 10.
When I test my page in browser after filling record in HTML page and submit browser shows blank page, I have checked my PHP code with some of free online code testing website. This website do not find any mistake in code, can you guide what should be the mistake?
GoDaddy gives three version of PHP 5.4, 5.5, and 5.6. I have selected 5.6, 5.4 and 5.5 also have given blank page.
It's very likely that display_errors it's turned off. You can change that in the php.ini file:
display_errors = On
Here's where to find the file:
https://www.godaddy.com/help/what-filename-does-my-php-initialization-file-need-to-use-8913
Most of the time, it's in the root directory.
Solution given on godaddy community:
Steps:
Go to CPanel dashboard
Go to 'Select PHP Version', you should see a bunch of checkboxes
Set PHP version (min 5.4)
Uncheck the 'mysqli' extension and check both 'mysqlind' and 'nd_mysqli'
Apparently 'nd_mysqli' is 'mysqli' but configured to work with 'mysqlind' and to make it work you have to uncheck 'mysqli' due to settings conflicts.
This information was hidden deep within a stackoverflow answer that I can no longer find. Hope this helps some other people.
Make sure these values are correct according to your settings. And use mysqli_connect_error() function:
$servername = "server addresss";
$username = "";
$password = "";
$dbname = "";
I'm trying to count all emails from and email but my script only count mails from inbox,
anyone know how to count all emails from the mail account including sent,spam,deleted, etc
$mailcnf = "mail.office365.com:993/imap/ssl/novalidate-cert";
$conn_str = "{".$mailcnf."}INBOX";
$username = 'test3#sjnewman.co.uk';
$password = 'Woju6532';
$imap = imap_open($conn_str,$username,$password) or die('Cannot connect to Server: ' . imap_last_error());
echo $message_count = imap_num_msg($imap);
first use imap_list to list all available folders.
then $conn_str = "{".$mailcnf."}$mailbox"instead of mailbox
imap_num_msg should return the number of emails in the current mailbox
You can loop through each folder and use imap_status() to count the number of emails in each folder. Here's an example:
<?php
$username = 'mail#example.com';
$password = 'password123';
// Define the connection string:
$server = '{server.example.net:993/ssl}';
// Connect to the server:
$connection = imap_open($server, $username, $password);
// List the mailboxes:
$mailboxes = imap_list($connection, $server, '*');
// Loop through the mailboxes:
foreach($mailboxes as $mailbox) {
$status = imap_status($connection, "$mailbox", SA_ALL);
if ($status) {
echo "Mailbox: $mailbox\t\tMessages: " . $status->messages . "\n";
} else {
echo "imap_status failed: " . imap_last_error() . "\n";
}
}
// Close the connection:
imap_close($connection);
?>
Hello, I'm kind of new to php, so don't bash on me, but I just can't figure out what the problem is with this code. So basically I have several forms of output, but as soon as I do anything with mysql ( even just connect and disconnect! ), it won't allow me to do any kind of output. It also won't allow me to redirect.
I tried taking all the code out between the mysql connect and disconnect code and it didn't help to resolve anything, However, as soon as I comment out the mysql connection code, all my outputs and redirects work! I'm trying to build a simple login script that gets the email and password from a form elsewhere. I would love to get this resolved so I could figure out if the rest of it works. And I know that 'header' will not work after echo; the echo and the file writes will not be there as soon as I can make sure this is working. Any help would be appreciated! Thanks!
<?php
/*
Login.php searches for the email address given by loginPage.php in the data base.
If the email is found and the password given by loginPage.php matches that stored
in the data base, a session will begin and the client will be redirected to the
main page.
*** INCOMPLETE ***
*/
echo "HELLO!";
$email = $_POST["email"];
$password = $_POST["password"];
$errorLog = fopen("login.txt", "w");
fwrite($errorLog, "***Sesion started***");
$mysql_id = mysql_connect("localhost", "root", "12131");
if (!$mysql_id)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('informationStation', $mysql_id);
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "';", $mysql_id);
if($results != null && $password == mysql_fetch_array($result))
{
$redirect = 'Location: http://127.0.1.1/main.php';
}
else
{
$redirect = 'Location: http://127.0.1.1/loginPage.php';
{
mysql_close($mysql_id);
fwrite($errorLog, "result: " . $results);
fwrite($errorLog, "redirect: " . $redirect);
fclose($errorLog);
header($redirect);
?>
Try this to get you started..
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "'", $mysql_id) or die(mysql_error());
But you also need to read about sql injection.
And you should not store passwords in your database without salting and hashing them.
And you also need to use array syntax to access the data from your result...
$mysql = mysql_connect("localhost", "root", "12131") or die('Could not connect: ' . mysql_error());
mysql_select_db('informationStation', $mysql);
function loged($email, $password) {
$result = mysql_query("SELECT id FROM Personals WHERE email = '" . $email . "' AND password='" . $password . "'");
if(mysql_num_rows($result) != 1)
return false;
return true;
}
if(loged(mysql_real_escape_string($email), md5($password))) {
header('Location: http://127.0.1.1/mainPage.php');
exit;
}
header('Location: http://127.0.1.1/loginPage.php');
In this example you need to store users password using md5 encryption method (search for other more securely encryption methods).
Also we've escaped the email address against sql injection.
I've created a function which can be called every time you want to see if the user is loged in or not.
Note that this is not a complete login script. You will also need to make a login function where you'll have to start a new session for each user.