Issue with 'if statement' in a php form with multiple recipients - html

My php form has a <select> option for multiple recipients with an email address associated to each of them:
<select name="sendto">
<option value="select">-- Select --</option>
<option value="general">General</option>
<option value="support">Support</option>
<option value="sales">Sales</option>
</select>
I'm able to send and receive successfully only the 'General' option, the rest fails. It's obvious the issue is with the 'if statement' but I can't figure out what the problem is exactly. Any help? Thanks.
This is the php code:
<?php
$to = $_REQUEST['sendto'] ;
$from = $_REQUEST['Email'] ;
$name = $_REQUEST['Name'] ;
$headers = "From: $from";
$subject = "Web Contact Data";
$fields = array();
$fields{"Name"} = "Name";
$fields{"Company"} = "Company";
$fields{"Email"} = "Email";
$fields{"Phone"} = "Phone";
$fields{"list"} = "Mailing List";
$fields{"Message"} = "Message";
$body = "We have received the following information:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
$headers2 = "From: noreply#my-site.com";
$subject2 = "Thank you for contacting us";
$autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.my-site.com";
if ($sendto == 'general') {
$to = 'alex#my-site.com';
}
else if ($sendto == 'support') {
$to = 'alabanino#my-site.com';
}
else if ($sendto == 'sales') {
$to = 'alabanino#my-site.com';
}
else { //other options
$to = 'alex#my-site.com';
}
if($from == '') { print "You have not entered an email, please go back and try again"; }
else {
if($name == '') { print "You have not entered a name, please go back and try again"; }
else {
$send = mail($to, $subject, $body, $headers, '-fnoreply#yourmailer.com');
$send2 = mail($from, $subject2, $autoreply, $headers2);
if($send){
header( "Location: http://www.my-site.com/thankyou.html" );}
else {
print "We encountered an error sending your mail, please notify webmaster#my-site.com";
}
}
}
?>

Where is $sento defined? This will be 'working' cos it will be defaulting to your final else condition as all others fail.
You need to add this and it should work
$sendto = $_REQUEST['sendto']
Or else use $to insetad

Related

No results found when i use postman

I have a PHP code connected to mysql database. I want to send user login data from the postman tool and receive it in the php code and then return it to the result
The problem is that when sending data do not get the result
PHP CODE
<?php
$response = array();
header("Content-type: application/json; charset=utf-8");
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
include 'db/db_connect.php';
include 'functions.php';
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array
//Check for Mandatory parameters
if(isset($input['username']) && isset($input['password']) ){
$username = $input['username'];
$password = $input['password'];
$query = "SELECT full_name , password_hash , salt , email , id_con , born , city , country و card_id ,cardstatus, cardvalue FROM member WHERE username = ?";
if($stmt = $con->prepare($query)){
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->bind_result($fullName , $passwordHashDB ,$salt, $email , $countryid , $born , $city , $country ,$cardid ,$cardstatus, $cardvalue);
if($stmt->fetch()){
//Validate the password
if(password_verify(concatPasswordWithSalt($password,$salt),$passwordHashDB)){
$response["status"] = 0;
$response["message"] = "Login successful";
$response["full_name"] = $fullName;
$response["card_id"] = $cardid;
$response["email"] = $email;
$response["id_con"] = $countryid;
$response["country"] = $country;
$response["city"] = $city;
$response["born"] = $born;
$response["cardstatus"] = $cardstatus;
$response["cardvalue"] = $cardvalue;
}
else{
$response["status"] = 1;
$response["message"] = "Invalid username and password combination";
}
}
else{
$response["status"] = 1;
$response["message"] = "Invalid username and password combination";
}
$stmt->close();
}
}
else{
$response["status"] = 2;
$response["message"] = "Missing mandatory parameters";
}
//Display the JSON response
echo json_encode($response);
?>
SCREENSHOT

WordPress and PHP | Check if row exists in database if yes don't insert data

I'm fairly new to WordPress and SQL. I have a contact form that I want to have the data be submitted to my WordPress database but only if the data that has been entered has not been entered before.
This is what i have so far, which sends data to my database when form is submitted.
if(isset($_POST['contact_us'])) {
$invalidContact = "<h5 class='invalidBooking'> Nope try again</h5>";
$successContact = "<h5 class='invalidBooking'> Message Sent!</h5>";
$table_name='contact_table';
global $wpdb;
$contact_name = esc_attr($_POST['contact_name']);
$contact_email = sanitize_email($_POST['contact_email']);
$subject = esc_attr($_POST['subject']);
$message = esc_attr($_POST['message']);
$error= array();
if (empty($contact_name)) {
$error['name_invalid']= "Name required";
}
if (empty($contact_email)){
$error['email_invaild']= "Email required";
}
// Im guessing some code here to check if row exists in database
if (count($error) >= 1) {
echo $invalid;
}
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
echo $successContact;
}
}
You may try this code
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$query = "SELECT * FROM $table_name WHERE 'Contact_Name'= '$contact_name' AND 'Contact_Email' = '$contact_email' AND 'Contact_Subject' = '$subject' AND 'Contact_Message' = '$message'";
$query_results = $wpdb->get_results($query);
if(count($query_results) == 0) {
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
}
}
Hope this works for you.
fetch data using this code
$query = "SELECT * FROM {$wpdb->prefix}table WHERE column = 1";
echo $query;
$results = $wpdb->get_results($query);
and then you know what to do...

Google API for analytics invalid grant but works sometimes

I've been on this problem now for 2 days and have tried looking under google code and stackoverflow but still can come up with an answer.
My problem is when I try my google analytics api I get "Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'"
But the weird part is that some times it will work. rarely but if I refresh and keep trying it, it will output.
The only thing I could find is that it could be the refresh token limit has been exceeded
Attached is my code if someone could help me out or point me to the right direction.
Thanks!
<?php
session_start();
require_once 'Google_Client.php';
require_once 'Google_AnalyticsService.php';
require_once 'config.php';
$keyFile = 'key.p12';
$client = new Google_Client();
$client->setApplicationName("test");
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$client->setAssertionCredentials(new Google_AssertionCredentials(
GOOGLE_SERVICE_ACCOUNT,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyFile))
);
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setAccessType('offline');
$client->setUseObjects(true);
$service = new Google_AnalyticsService($client);
try {
$results = $service->data_ga->get(
'ga:44444444',
date('Y-m-d', strtotime('-30 days '.date('Y-m-d', strtotime('-1 day '.date('Y-m- d'))))),
date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))),
'ga:visits,ga:newVisits',
/*array(
'dimensions' => 'ga:source,ga:keyword',
'sort' => '-ga:visits,ga:keyword',
'filters' => 'ga:medium==organic',
'max-results' => '25'
)*/
array('dimensions' => 'ga:date')
);
} catch (Google_ServiceException $e) {
// echo $e->getMessage();
}
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
}
$dateParsePattern = '/"Date.parse\(\\\"((\d{4})-(\d{2})-(\d{2})) UTC\\\"\)"/';
$dateParseReplacement = 'Date.parse("$1 UTC")';
$allVisitsItems = array();
$newVisitorsItems = array();
if ($results && count($results->getRows()) > 0) {
foreach ($results->getRows() as $row) {
$date = 'Date.parse("'.date("Y-m-d", strtotime($row[0])).' UTC")';
$allVisitsItems[] = array($date, intval(htmlspecialchars($row[1], ENT_NOQUOTES)));
$newVisitorsItems[] = array($date, intval(htmlspecialchars($row[2], ENT_NOQUOTES)));
}
}
header('Content-Type: application/json');
?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($allVisitsItems)) ?>
Edit - It's not the NTP, when I echoed date('l jS \of F Y h:i:s A'); it matched up.
The following works to generate output - make sure you are running PHP 5.3 or higher.
<?php
require_once './src/Google_Client.php';
require_once './src/contrib/Google_AnalyticsService.php';
$path_to_keyfile = '.p12';
$service_account_email = '7#developer.gserviceaccount.com';
$client_id = '7.apps.googleusercontent.com';
$analytics_profile_id = 'ga:IN URL OF ANALYTICS';
$client = new Google_Client();
$client->setApplicationName("API TEST");
$client->setAssertionCredentials(
new Google_AssertionCredentials(
$service_account_email,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($path_to_keyfile)
)
);
$client->setClientId($client_id);
$client->setAccessType('offline_access');
$service = new Google_AnalyticsService($client);
$from = date('Y-m-d', strtotime('-30 days '.date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))))); // 30 days
$to = date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))); // yesterday
$dateParsePattern = '/"Date.parse\(\\\"((\d{4})-(\d{2})-(\d{2})) UTC\\\"\)"/';
$dateParseReplacement = 'Date.parse("$1 UTC")';
$allVisitsItems = array();
$newVisitorsItems = array();
try {
$data = $service->data_ga->get(
//
$analytics_profile_id,
$from,
$to,
'ga:visits,ga:newVisits',
array('dimensions' => 'ga:date')
);
if($data && $data['totalResults'] > 0) {
foreach($data['rows'] as $row) {
$date = 'Date.parse("'.date("Y-m-d", strtotime($row[0])).' UTC")';
$allVisitsItems[] = array($date, intval(htmlspecialchars($row[1], ENT_NOQUOTES)));
$newVisitorsItems[] = array($date, intval(htmlspecialchars($row[2], ENT_NOQUOTES)));
}
}
header('Content-Type: application/json');
?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($allVisitsItems)) ?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($newVisitorsItems)) ?>
<?php
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}

Mysql Values not Working

I have a rank to determine the user level, (e.g. rank 1 = registered, rank3 = admin), and everything works fine in my script below.
<?php
session_start();
require('../../config.php');
$qry=("SELECT `rank`, `uname` FROM users");
$result=mysql_query($qry);
$row = mysql_fetch_assoc($result);
$rank = $row['rank'];
$user = $_SESSION['user'];
$logged = $_SESSION['loggedin'];
if ($logged == true) {
if ($rank >= 3) {
echo "Succesful, $user.<br />
<form method='POST' action='delete.php'>
<select><option>Please select</option>";
while ($row = mysql_fetch_assoc($result)) {
$users = $row['uname'];
$lol = ucwords($users);
}
echo "<option>$lol</option>";
echo "</select>
</form>";
} else {
echo "Your not an admin.";
}
} else {
echo "Please login.";
}
?>
But, once I add a new user to the database, (2 rows in database), it says "Your not an admin".
Please help. Thank you.
Shouldn't add the where condition to specify which user? Like use the userid?
$qry=("SELECT `rank`, `uname` FROM users WHERE uid = $uid");

how to handle call to method getElementsByTagname is null

i have this js piece of code:
<script language="JavaScript" type="text/javascript">
var sendReq = getXmlHttpRequestObject();
var receiveReq = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
function handleReceiveChat()
{
if (receiveReq.readyState == 4)
{
var chat_div = document.getElementById('div_chat');
var xmldoc = receiveReq.responseXML;
var message_nodes = xmldoc.getElementsByTagName("message");
//more code
}
}
function getChatText()
{
if (receiveReq.readyState == 4 || receiveReq.readyState == 0)
{
receiveReq.open("GET", 'getChat_xml.php?chat=1&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}
</script>
and in getChat_xml i have this:
$xml = '<?xml version="1.0" ?><root>';
if(!isset($_GET['chat']))
{
$xml .='Your are not currently in a chat session. Enter a chat session here';
$xml .= '<message id="0">';
$xml .= '<user>Admin</user>';
$xml .= '<text>Your are not currently in a chat session. <a href="">Enter a chat session here</a></text>';
$xml .= '<time>' . date('h:i') . '</time>';
$xml .= '</message>';
}
else
{
$last = (isset($_GET['last']) && $_GET['last'] != '') ? $_GET['last'] : 0;
$sql = "SELECT message_id, user_name, message, date_format(post_time, '%h:%i') as post_time" .
" FROM message WHERE chat_id = " . db_input($_GET['chat']) . " AND message_id > " . $last;
$message_query = db_query($sql);
//Loop through each message and create an XML message node for each.
while($message_array = db_fetch_array($message_query))
{
$xml .= '<message id="' . $message_array['message_id'] . '">';
$xml .= '<user>' . htmlspecialchars($message_array['user_name']) . '</user>';
$xml .= '<text>' . htmlspecialchars($message_array['message']) . '</text>';
$xml .= '<time>' . $message_array['post_time'] . '</time>';
$xml .= '</message>';
}
}
$xml .= '</root>';
can anybody help here please?? dont understand how this works
thanks
After seeing the code you have posted, these problems come to mind...
You have not actually added an echo $xml; to output the generated XML.
Even after adding an 'echo' statement, you may get null responseXML (and hence an undefined getElementsByTagName) because of some errors in your PHP code (maybe the SQL query).
Even if your PHP code is right, you will get null responseXML because u have not sent proper content header (header('Content-Type: text/xml');).
Maybe a stupid question but are you actually echoing $xml in your getChat_xml.php file? I can see xmldoc.getElementsByTagName("message") returning null because it can't find any <message> elements because the DOM was never outputted by PHP. What happens when you view the file directly? : http://www.yoursite.com/getChat_xml.php?chat=1&last=xxx
Just a shot in the dark here, but try this:
function handleReceiveChat()
{
if (receiveReq.readyState == 4)
{
var chat_div = document.getElementById('div_chat');
var xmldoc = receiveReq.responseXML;
var message_nodes = xmldoc.getElementsByTagName("message");
if (message_nodes)
{
//more code
}
}
}