Ajax POST / GET security - mysql

I am building a type of crm using ajax, php and mysql. I am building the solution with GET and POST requests using ajax xhr requests. My question is, what is the best way to make sure these requests are secure from any type of hack or attack. I want to make sure my clients data and this crm is secure.
Right now i am just using long hand ajax/javascript. I don't use much jquery: My request looks something like this:
function getContacts()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","xhr_php/getContacts.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var contact = document.getElementById('contact_id').value;
xmlhttp.send("contact="+contact);
}
my php file looks like this
$contact=$_POST['contact'];
$sql="SELECT *
FROM contacts
WHERE contacts.contact_id = $contact";
So this is the basic method i have used to not only retrieve data but also to insert records and run all other queries. My question is what is the best way to secure these requests and sql queries so that all the data is secure. I want to make sure this is a secure crm solution so that data can't be corrupted, stolen, injected, hacked, etc. Thank you for your help.

This is not secure; it is vulnerable to an SQL injection attack, which has nothing to do with Ajax, POST or GET. You should not be building SQL statements in that way. Your question isn't well suited to Stack Overflow - "How do I make my code secure" is a vast topic that can't be answered in a simple way. If you are building this in a professional capacity, please seek out a more senior developer to help you with this - if you are making basic SQL injection mistakes, then it is very unlikely you will be able to build an entire CRM package on your own while making it secure.

You should use PDO. Following is example code. you can modify it as required.
$host = 'localhost';
$dbname = 'contacts';
$username = 'anyuser';
$password = 'your password';
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//If contact is int value then pass it through intval function
$contact=intval($_POST['contact']);
$sql = 'SELECT * FROM contacts WHERE contacts.contact_id = :contact_id';
$statement = $conn->prepare($sql);
$statement->bindParam(':contact_id', $contact, PDO::PARAM_INT);
$statement->execute();
//Use $result is your page
$result = $statement->fetch(PDO::FETCH_ASSOC);
You can do insert / update with PDO as well
$stmt = $conn->prepare("INSERT INTO Table (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
$stmt->execute();
Hope this helps.

This should be immune to sql injection:
$contact=intval($_POST['contact']);
$sql="SELECT *
FROM contacts
WHERE contacts.contact_id = $contact";
mysql_query($sql);

Related

Can't get email from Google Classroom student profile

I'm trying to write a PHP routine to import Google Classroom enrollment data into our database. Here are my scopes:
$client->setScopes([Google_Service_Classroom::CLASSROOM_COURSES_READONLY, Google_Service_Classroom::CLASSROOM_ROSTERS_READONLY, Google_Service_Classroom::CLASSROOM_PROFILE_EMAILS]);
Then I'm trying to run through the class enrollment data. (I made a class in my personal Google account, and got some co-workers to sign up for the class.) I'm getting profiles, but the emailAddress is always blank:
$results = $service->courses->listCourses();
foreach ($results->getCourses() as $course) {
$roster = $service->courses_students->listCoursesStudents($course->id);
foreach ($roster['students'] as $student) {
$profile = $student['profile'];
$name = $profile['name']; // Works
$first_name = $name['givenName']; // Works
$email = $profile['emailAddress']; // Always null
}
}
What am I missing?
This has mysteriously started to work...which does not make me feel great, but you know the feeling, right? There's no way to make the problem come back, so you just have to hope it doesn't...I will post here again if it does.
Maybe this is related to the fact that we just refilled the form with new scopes. So for the moment, I'm getting a warning that "Google hasn't verified the app" before it connects. So maybe it's the new scopes, or maybe it's the warning.

Use PEAR on Fedora

I am attempting to use PEAR to send email on a Fedora server machine and am getting nowhere.
Below is the code I am trying to use. The email authentication settings in the code are not the actual but the info I am using is pulled from my email client config so should work.
I am also trying to get debug info to find out what is happening. Is setting 'debug' to 'true' enough or is something else required? And where can I find the debug log information?
A lot of asks but I hope someone can direct me in the right direction.
I tried PHPMailer as well but no go. I have this sense that some configuration on the machine is blocking...
One more thing, this exact code works on a Ubuntu machine so I know it works. I am trying to move all services from the Ubuntu machine to a Fedora machine.
<?php
require_once "Mail.php";
$from = "demo#demo.com";
$recipients = 'demo#demo.com';
$headers["From"] = $from;
$headers["To"] = 'demo#demo.com';
$headers["Reply-To"] = $from;
$headers["Subject"] = 'Testing';
$headers["MIME-Version"] = "1.0";
$headers["Content-Type"] = "text/html; charset=UTF-8";
$body = 'Testing';
$smtpinfo["host"] = "mail.demo.com";
$smtpinfo["port"] = "587";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = "demo#demo.com";
$smtpinfo["password"] = "password";
$smtpinfo["debug"] = true;
$mail_object = Mail::factory("smtp", $smtpinfo);
$mail_object->send($recipients, $headers, $body);
if (PEAR::isError($mail_object)) {
$ret['success'] = false;
$ret['msg'] = 'Message delivery failed...';
} else {
$ret['success'] = true;
$ret['msg'] = 'data is valid';
}
return $ret;
?>
Thank you
So, after a few more hours of testing I have resolved the issue. This website provided direction on how to get debug information in the command line.
After testing the PHP code from the command line and confirming that messages can be sent, I attempted to send an email from a web page; which failed to work.
So, now thinking that the issue is likely related to the web server, led me to this question on Stack Overflow . The solution of which resolved the issue immediately. Specifically, doing the following as described in the accepted solution:
$ sestatus -b | grep sendmail
httpd_can_sendmail off
$ restorecon /usr/bin/sendmail
$ setsebool -P httpd_can_sendmail 1
Hope this helps someone else facing the some problem.

SQL Injection Concern

I'm developing a new site that requires user logins. Currently just testing a few things and passwords are stored as plain text but I will be changing this.
I was just wondering, as I'm new to using MySQL / PHP, if this is vulnerable to SQL Injection or not, and if so what would you recommend to make it more secure?
(using [insert_php] as wordpress is the CMS)
[insert_php]
include("Config.php");
$_SESSION['username']= "Your value";
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$myusername=addslashes($_POST['username']);
$mypassword=addslashes($_POST['password']);
$sql="SELECT id FROM admin WHERE username='$myusername' and
password='$mypassword'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$active=$row['active'];
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION['username'];
$_SESSION['login_user']=$myusername;
header("location: welcome.php");
}
else
{
$error="Your Login Name or Password is invalid";
}
}
[/insert_php]

web page keep content after refresh server side

I would like to create a simple text web page that keeps the content. I want to keep the content saved on the server by what ever means (php or sql is fine).
sessionStorage and localStorage isn't what i'm looking for. Those keep the data on the users computer and doesn't allow other computers to see the same thing.
Thanks
So im kind of confused by your question I assume you mean pull string from mysql and display it on the webpage so here is an example.
<?php
//Connect
$user = 'example';
$password = 'example';
$host = 'example';
$link = mysql_connect($host, $user, $password);
mysql_select_db('example_db');
$handle = mysql_query('SELECT * FROM Example_db');
$row = mysql_fetch_row($handle);
$text = $row[0]; // Retrieve text in database
//Variable name above can be what ever you want it to be.
?>
//Example html
<h1><?php echo $text;></h1>
pard me if i'm wrong if so just tell me and I can see if I can further help you.

PHP-EWS No Data Received Message

I just downloaded PHP-EWS, installed following the README instructions, and spun up a script to test out its functionalities. When I try running the script in my browser, I get the following message:
I get the same message when I supply a login I know is invalid. It seems I am connecting to my Exchange server, but it's not recognizing the credentials I provide.
Here is the script I am using
<?php
function __autoload($className)
{
$className = str_replace('_','/', $className);
$sFileName = $className . '.php';
if (file_exists($sFileName) && !class_exists($className))
{
require_once $sFileName;
}
// If the above if fails, you're program will terminate, there is no way to catch this.
}
include("ExchangeWebServices.php");
$host = "https://myexchange/EWS/Services.wsdl";
$username = "myusername#mydomain.com";
$password = "mypassword";
$ews = new ExchangeWebServices($host, $username, $password);
$request = new EWSType_FindItemType();
$request->ItemShape = new EWSType_ItemResponseShapeType();
$request->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::DEFAULT_PROPERTIES;
$request->Traversal = EWSType_ItemQueryTraversalType::SHALLOW;
$request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
$request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
$request->ParentFolderIds->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::INBOX;
// sort order
$request->SortOrder = new EWSType_NonEmptyArrayOfFieldOrdersType();
$request->SortOrder->FieldOrder = array();
$order = new EWSType_FieldOrderType();
// sorts mails so that oldest appear first
// more field uri definitions can be found from types.xsd (look for UnindexedFieldURIType)
$order->FieldURI->FieldURI = 'item:DateTimeReceived';
$order->Order = 'Ascending';
$request->SortOrder->FieldOrder[] = $order;
$response = $ews->FindItem($request);
echo '<pre>'.print_r($response, true).'</pre>';
?>
Try testing your access by:
Hitting the server url directly: https://YOUREXCHANGESERVER/EWS/Services.wsdl
You should be prompted for credentials. After you enter your credentials you will be presented with the WSDL definition. If it does not present you a WSDL definition that looks like the example below then check with your administrator on credentials or if there are any firewall blocks put in place.
Example (Partial response):
<wsdl:definitions targetNamespace="http://schemas.microsoft.com/exchange/services /2006/messages"><wsdl:types><xs:schema><xs:import namespace="http://schemas.microsoft.com/exchange/services/2006/messages" schemaLocation="messages.xsd"/></xs:schema></wsdl:types>
A great tool I use in analyzing web services is: SOAP-UI by SmartBear