SQL Injection Concern - mysql

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]

Related

Using PHP/SQL to select, then delete image files that aren't referenced in user table

I have a site with user profiles. I've delete a slew of profiles within phpmyadmin, but those profiles that I've deleted still have their picture files in a folder on the website.
I'm looking for a script that I could run that would select/delete all the pictures in the folder that are not associated with any existing profile in the database.
A typical image name is like this: 0ae71e1bc25cae7e243464adb.jpg
I'm sure there's a way to do this, but I'm not a major expert at using mysql operations for something of this nature.
So in an attempt to be more clear:
I have let's say 100 existing users with their info in the database, including their profile picture name.
Their profile picture is in a folder on the server called images
In that same folder are images of users that do not exist
I'd like to run a script that will check to see if that image is referenced in the "users" table by any user, and if not, delete it.
Your help us appreciated.
I think this script should do the trick.
// Query the images paths as array using mysqli
$db = new mysqli("localhost", "user", "pass", "foo_db");
$result = $db->query("SELECT image_path FROM users");
$images_db = $result->fetch_all(MYSQLI_ASSOC);
// Use glob to retrieve all the existing img in dir
$directory = "/home/user/public_html/images/";
$images_dir = glob($directory . "*.*");
// if image_dir is not in images_db delete it using unlink fn
foreach($images_dir as $image_dir) {
if (!in_array($image_dir, $images_db)) {
unlink($directory . $image_dir);
}
}
You have to tweak the script for your need.
Be carefull with unlink ! First test the script in local !
Lighter on memory solution:
$files = scandir(DIR_TO_IMAGES_FOLDER);
$db_conn = create_db_connection(); //assume this creates the connection to your db and return false if it cant;
if (!$db_conn) exit(); //no connection
foreach ($files as $file){
if (is_file($file)){
$query = "SELECT COUNT(*)
FROM TABLE_NAME
WHERE image_name=:image_name";
$result = $db_conn->prepare($query);
$result->bindParam(":image_name", $file);
$in_use = true; //assume it is in use just incase sql execute fails;
try{
$result->execute();
$in_use = $result->fetchColumn();
}catch (Exception $e){
}
if (!$in_use) unlink(DIR_TO_IMAGES_FOLDER . '/' . $file);
}
}
But I would just create a new TABLE image_delete_pending and a trigger BEFORE DELETE on your 'users' table. The trigger would insert the image_name to the image_delete_pending TABLE. Then the script will for sure know that every image in the image_delete_pending needs to be deleted.
The script would then be:
$db_conn = create_db_connection(); //assume this creates the connection to your db and return false if it cant;
if (!$db_conn) exit(); //end script; no connection
$query = "SELECT image_name
FROM image_delete_pending;";
try{
$result = $db_conn->prepare($query);
$result->execute();
while ($row = $result->fetch()){
if(unlink(DIR_TO_IMAGES_FOLDER . '/' . $row['image_name'])){
$db_conn->query("DELETE FROM image_delete_pending WHERE image_name='". $row['image_name'] ."';";
}
}
}catch (Exception $e){
}

save Facebook information in my remote data base with titanium

I want to ask I have developed a mobile application which you can login using Facebook username and password so I want to know how can I save the username and password from Facebook into my remote database.
This is my code any help please:
var fb = require('facebook'); fb.appid = "281158112043247";
// Set the URL
fb.permissions = ['email'];
fb.authorize();
fb.addEventListener('login', function(e) {
if (e.success) {
fb.requestWithGraphPath('me', {}, 'GET', function(e) {
if (e.success) {
var data= JSON.parse(e.result);
xhr = Titanium.Network.createHTTPClient();
xhr.open("Post", "http://192.168.131.145:5220/Create.svc/createClient");
var params = {
Clientusername: data.name,
//password:password1.value,
// Clientpassword: Ti.Utils.md5HexDigest(password1.value),
Clientnom: data.name,
Clientid:data.id,
Clientemail: data.email
};
xhr.send(JSON.stringify(params));
//xhr.send(e.result);
Ti.API.info("Name:"+data.name);
Ti.API.info("email:"+data.email);
Ti.API.info("facebook Id:"+data.id);
} else if (e.error) {
alert(e.error);
} else {
alert('Unknown response.');
}
});// request graph
}else{
if(e.error){
alert(e.error);
}else{
alert("Unkown error while trying to login to facebook.");
}
}
});
You don't have access to their Facebook password. The oauth specifically protects against you having to know their access credentials. It allows Facebook to separately identify you, and what you are doing with the API. The user can also then disable your access to their data, if they see fit. But if you had their password, you could do anything that they can do, even temporarily steal their account. Plus their account would only be as secure as your storage of their password (is it encrypted? are you servers secure? on premise? compromised? running any malware?). So generally, no, it's a bad idea, don't do that, even if you figure out a way to do so.
In the case of your code above, you have already authorized the user inside your app, so you won't need to authorize them again. They'll already be logged in. You should check if (fb.loggedIn) and then do your logged-in-only code, else fb.authorize();.

Ajax POST / GET security

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);

Facebook-php-sdk

So I am using the facebook-php-sdk and I have created a page tab
On the page tab I am trying to use the SDK and it only works when I have logged into facebook as the page not as a user so what would the cause of this be?
require 'facebook-php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => '//APP ID//',
'secret' => '//APP SECRET//',
));
// Get User ID
$user = $facebook->getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
}
catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if(isset($user)) {
var_dump($user);
}
else if(isset($user_profile)) {
var_dump($user_profile);
}
else {
echo $loginUrl;
}
var_dump($facebook->getUser());
I get this is the error_log: Bad Signed JSON signature
Is the user you are testing with connected to the page (i.e., Liked it)? If not you will not receive any information about who the user is. This is to be expected. Facebook does its best to anonymize the user interaction with pages' apps when the user hasn't explicitly Liked the page.

POST Login with ActionScript 2.0

I have created a pretty basic Flash website for a client and am having an issue programming a Client Login feature that he would like. Currently, if I navigate to the site and click Client Login, it takes me to a login page. The way I need this to work is -- within the Flash, using ActionScript 2.0 -- have the user enter their UserID and Password and click to login, which submits POST vars to the form action of the Client Login website.
Is this possible/legal to do from a different domain? How would I go about doing this, assuming it's possible?
Try this:
myVars = new LoadVars();
myVars.username = username.text;
myVars.password = pwd.text;
myVars.onLoad = function(success) {
trace("yay!");
else {
trace("try again");
}
}
myVars.sendAndLoad("login.php", myVars, "POST");
So, I get "yay!" with the code provided below (yours had an error in it). However, I need to be redirected to the resulting "logged-in" page. How do I do that?
myVars = new LoadVars();
myVars.txtUserID = "some_user";
myVars.txtPassword = "some_password";
myVars.__VIEWSTATE = "dDw3MTcxMTg3ODM7dDw7bDxpPDM+O2k8NT47PjtsPHQ8cDxsPFRleHQ7PjtsPGRlbW87Pj47Oz47dDw7bDxpPDE+O2k8Mz47aTw1Pjs+O2w8dDxwPGw8VGV4dDs+O2w8YmFja2dyb3VuZC1jb2xvcjojZjZmNmY2XDtjb2xvcjojMzMzMzMzXDs7Pj47Oz47dDxwPDtwPGw8c3R5bGU7PjtsPHdpZHRoOjEwMHB4XDs7Pj4+Ozs+O3Q8cDw7cDxsPHN0eWxlOz47bDx3aWR0aDoxMDBweFw7Oz4+Pjs7Pjs+Pjs+Pjs+56k0UDxn5ED61lGLjP0fIkStm6o=";
myVars.onLoad = function(success) {
if (success)
{
trace("yay!");
} else {
trace("try again");
}
}
myVars.sendAndLoad("http://www.buildertrend.net/loginFrame.aspx?builderID=35&bgcolor=%23f6f6f6&fcolor=%23333333&uwidth=100&pwidth=100", myVars, "POST");