How to connect a hybrid application made in intel xdk with a mysql database? Any good resources? - intel-xdk

I've been searching for examples to connect my intel xdk application with mysql database but I can't find anything. I've read this information http://qnimate.com/create-a-intel-xdk-app-with-php-and-mysql-backend/ but they don't explain anything about the files and where information come from.
If anyone have good resources it would be a great help for me. Thanks!

Ok this how I did it
// php script. Make sure this file is in your www folder if you are using wamp
<?php
$data = array(); // array to store data
$con = mysql_connect('localhost','root','wtf'); // connection to database
if(!$con){
die('Error Occured ' . mysql_error());
} // checking if connection was successfully
$sel_db = mysql_select_db('church',$con); // select database
if(!$sel_db){
die("Failed to select database". mysql_error());
}
// query
$query = "Select * from clist";
$result_set = mysql_query($query,$con);
if(!$result_set){
die("Failed to Execute Query ". mysql_error());
}
while($re = mysql_fetch_array($result_set)){
$data[] =$re; // store data in array
}
echo json_encode($data); // this will send the array to the ajax call
mysql_close();
?>
// in XDK
function onAppReady()
{
if( navigator.splashscreen && navigator.splashscreen.hide )
{
// Cordova API detected
navigator.splashscreen.show() ;
}
getServer();
}
// using ajax to communicate with the server
function getServer(){
$.get("http://localhost/others/server.php",function(data,status){
if(status == 'success')
{
var result = new Array();
result = JSON.parse(data); // getting the array from the php
var i;
// what your want to do with the data.
}
});
}
// this works for me

Related

Fatal error: require_once(): Failed opening required ... Novice programmer, appreciate any guidance

I'm a novice in server-side programming so any advice is appreciated.
I have some PHP files uploaded on a virtual server (000webhost.com) and I'm having trouble with locating a file I'm requiring in another PHP file. The register.php is attempting to "require_once" the update_user_info.php
Here's the code for register.php (Which I've taken from a tutorial and adjusted it with my variables):
<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'../update_user_info.php');
$db = new update_user_info();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST ['password']) && isset($_POST['branch']) && isset($_POST['gender'])) {
// receiving the post params
$username = $_POST['username'];
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$branch = $_POST['branch'];
$gender = $_POST['gender'];
// check if user is already existed with the same email
if ($db->CheckExistingUser($email)) {
// user already existed
$response["error"] = TRUE;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->StoreUserInfo($username, $name, $email, $password, $branch, $gender);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["user"]["username"] = $user["username"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["branch"] = $user["branch"];
$response["user"]["gender"] = $user["gender"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter (username, name, email or password) is missing!";
echo json_encode($response);
}
?>
And here's a screenshot of the error that's occurring when attempting to visit the link containing the register.php:
Screenshot of the error
What I've tried so far:
1- tried to use require_once __DIR__."/../filename.php"; and lots more of the same, basically tinkering the statement with different language constructs and constants.
2-Read tutorials on the correct way to use require once but their cases is almost always very different. Either they are using WAMP/XAMPP -meaning they have a local path not a virtual one- So no luck there.
3- tried to change .htaccess file, as someone said in a post that it solved his problem.
4- I'm certain that both files are uploaded to the same directory. Yet it says "No such file".
Does anyone have an idea of where the error could be stemming from? Thanks in advance!

Hashing password in register and account settings

I am get login errors when i test my script by logining under my own account. Do you think hashing passwords twice a bad practice?
I have hashed the users password twice in my website. Once, when they register and once, when they update their password in account update. Also i am using bcrypt method and cost of bcrypting is 10 on both hashings and i am on localhost server.
///// this is the code in register.php page
<?php
if(isset($_POST['registeruser'])) {
session_start();
$FName = $_POST['regfname'];
$LName = $_POST['reglname'];
$Email = mysqli_real_escape_string($conn, $_POST['regemail']);
$origignalpassword = preg_replace('#[^a-z0-9_]#i', '',
$_POST['regpassword']);
$Passwordw = $_POST['confirmedpassword'];
$infosql = "SELECT * FROM users WHERE useremail = '".$Email."'";
$result = mysqli_query($conn,$infosql);
if(mysqli_num_rows($result)>=1)
{
echo "Email already taken.";
}
else if(mysqli_num_rows($result) !=1 && $Passwordw ==
$origignalpassword) {
$Passwordhash = password_hash($Passwordw,
PASSWORD_BCRYPT, array('cost' => 10));
$sql = $conn->query("INSERT INTO users(firstname,
lastname, useremail, Passwordcell) Values('{$FName}',
'{$LName}','{$Email}','{$Psswordhash}')");
header('Location: login.php');
} else {
echo 'Please check your password:' . '<br>';
}
}
?>
//// Below code is the code in my update.php page
<?php session_start();
if(isset($_SESSION['user_id'])) {
} else {
header('Location: login.php');
}
$user = $_SESSION['userid'];
$myquery = "SELECT * FROM users WHERE `userid`='$user'";
$result = mysqli_query($conn, $myquery);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
$_SESSION['upd_fnames'] = $row['firstname'];
$_SESSION['upd_lnames'] = $row['Lastname'];
$_SESSION['upd_emails'] = $row['useremail'];
$_SESSION['upd_passwords'] = $row['Passwordcell'];
$_SESSION['upd_phone'] = $row['phonenum'];
$_SESSION['upd_bio'] = $row['biography'];
?>
<?php
if (isset($_POST['updateme'])) {
$updfname = $_POST['upd_fnames'];
$updlname = $_POST['upd_lnames'];
$updemail = $_POST['upd_emails'];
$updphone = $_POST['upd_phone'];
$upd_pswd = $_POST['upd_passwords'];
$biography = $_POST['update_biography'];
$Pswod = password_hash($upd_pswd, PASSWORD_BCRYPT,
array('cost' => 10));
$sql_input = $mysqli->query("UPDATE users SET firstname = '{$updfname}', Lastname = '{$updlname}', Phonenum = '{$updphone}', useremail = '{$updemail}', Passwordcell = '{$Pswod}', biography = '{$biography}' WHERE userid=$user");
header('Location: Account.php');
}
else
{
}
?>
Your problem could be just a typo, in your registration script, instead of $Passwordhash you wrote:
"INSERT INTO users(..., Passwordcell) Values(...,'{$Psswordhash}')"
Nevertheless there are other problems with your code, and since you asked for advise, i would like to share my thoughts.
Probably the biggest problem is, that your code is vulnerable to SQL-injection. Switch to prepared statements as soon as you can, writing code will become even easier than building the query as you did, and both MYSQLI and PDO are supporting it. This answer could give you a start.
Passwords should not be sanitized. Remove the line $origignalpassword = preg_replace('#[^a-z0-9_]#i', '', $_POST['regpassword']), and just pass the input directly to the hash function password_hash($_POST['regpassword'], PASSWORD_DEFAULT). The password_hash() function works with any type of input.
It is a good habit to place an exit after each redirection, otherwise the script will continue executing. header('Location: login.php', true, 303); exit;
Do you really have reason to put the user info into the session? Instead of $_SESSION['upd_fnames'] = $row['firstname']; i would fetch the information on demand from the database. With fetching it from the database you can be sure that the information is actually set (is not null) and is up to date, you can avoid a state and you get a bit more REST full.
Then last but not least i would recommend to follow some style rules, like starting variable names always with a small letter. You can avoid some silly typos and it makes your code more readable.

How to migrate mysqli to pdo

Hi I was wondering how I would migrate a mysqli php file to use PDO. Would anyone be able to take a look at my code and see if I'm on the right track?
This is my original (mysqli) code:
<?php
// connecting to database
$conn = new mysqli('xxxxxx', 'xxxxxx', 'password', 'xxxxxx');
$match_email = 'email';
$match_passhash = 'passhash';
if (isset($_POST['email'])) {
$clean_email = mysqli_real_escape_string($conn, $_POST['email']);
$match_email = $clean_email;
}
if (isset($_POST['passhash'])) {
$clean_passhash = mysqli_real_escape_string($conn, $_POST['passhash']);
$match_passhash = sha1($clean_passhash);
}
$userquery = "SELECT email, passhash, userlevel, confirmed, blocked FROM useraccounts
WHERE email = '$match_email' AND passhash = '$match_passhash'
AND userlevel='user' AND confirmed='true' AND blocked='false';";
$userresult = $conn->query($userquery);
if ($userresult->num_rows == 1) {
$_SESSION['authorisation'] = 'knownuser';
header("Location: userhome.php");
exit;
} else {
$_SESSION['authorisation'] = 'unknownuser';
header("Location: userlogin.php");
exit;
}
?>
And this is my attempt to migrate it to PDO:
<?php
// connecting to database
$dbh = new PDO("mysql:host=xxxxxx; dbname=xxxxxx", "xxxxxx", "password");
$match_email = 'email';
$match_passhash = 'passhash';
if (isset($_POST['email'])) {
$clean_email = mysqli_real_escape_string($conn, $_POST['email']);
$match_email = $clean_email;
}
if (isset($_POST['passhash'])) {
$clean_passhash = mysqli_real_escape_string($conn, $_POST['passhash']);
$match_passhash = sha1($clean_passhash);
}
$userquery = "SELECT email, passhash, userlevel, confirmed, blocked FROM useraccounts
WHERE email = ':match_email' AND passhash = ':match_passhash' AND
userlevel='user' AND confirmed='true' AND blocked='false';";
$stmt = $dbh->prepare($query);
$stmt->bindParam(":match_email", $match_email);
$stmt->bindParam(":match_passhash", $match_passhash);
$stmt->execute();
$userresult = $conn->query($userquery);
if ($userresult->num_rows == 1) {
$_SESSION['authorisation'] = 'knownuser';
header("Location: userhome.php");
exit;
} else {
$_SESSION['authorisation'] = 'unknownuser';
header("Location: userlogin.php");
exit;
}
?>
I'm also not sure how to count the number of rows returned in PDO.
If anyone would be able to help me out that wold be very great.
A million thanks in advance!
When using prepared statements and $stmt->bindValue() or $stmt->bindParam() you do not need to escape values with mysqli_real_escape_string(), PDO will do that for you.
Just remember to set a correct data type for the value. That is the third argument in the bind functions and it is a string by default so your code here is fine. I would only use bindValue() instead of bindParam() as you do not need references.
$stmt->execute() will run your prepared statement as a query. The other $conn->query() does not work with prepared statements. It is for raw queries, like you used to have with MySQLi.
When $stmt->execute() runs your response is saved in the $stmt object. For row count use $stmt->rowCount().

ftping only todays files only

I am new to php. have a task to ftp only todays files from the server containing files for over a week. how do i select or filter the files based on date and ftp to my local folder.
Help is much appreciated !!
Soloman
If you already have the filenames to check, use filemtime
Returns the time the file was last modified, or FALSE on failure. The time is returned as a Unix timestamp, which is suitable for the date() function.
To compare that today, you can use date('Y-m-d') to get today compare to date('Y-m-d', filemtime($filename))
To get the filenames, you could use readdir to read each one in turn.
<?php
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Files:\n";
while (false !== ($filename = readdir($handle))) {
echo "$filename\n";
}
closedir($handle);
}
?>
The manual also has an FTP example which should show you how to ftp the file once found.
So, combining all this, you could get something like:
<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// check connection
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name";
}
if ($handle = opendir('/path/to/files')) {
while (false !== ($filename = readdir($handle))) {
if (date('Y-m-d') == date('Y-m-d', filemtime($filename))) {
// upload the file
$upload = ftp_put($conn_id, $destination_file, $filename, FTP_BINARY);
// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}
}
}
closedir($handle);
// close the FTP stream
ftp_close($conn_id);
?>
Of course, you will need to fill in the dummy values as appropriate.
Disclaimer: I typed this in notepad++ and it is not tested for any mistakes!
link :
http://www.php.net/manual/en/function.ftp-rawlist.php
you connect to the server ,
get the list of the files with ftp_rawlist()
and get only file you want via ftp_fget()
example
<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// get the file list for /
$rawfiles = ftp_rawlist($conn_id, '/');
foreach ($rawfiles as $rawfile) {
# parse the raw data to array
if(!empty($rawfile)) {
$info = preg_split("/[\s]+/", $rawfile, 9);
$arraypointer[] = array(
'text' => $info[8],
'isDir' => $info[0]{0} == 'd',
'size' => byteconvert($info[4]),
'chmod' => chmodnum($info[0]),
'date' => strtotime($info[6] . ' ' . $info[5] . ' ' . $info[7]),
'raw' => $info
// the 'children' attribut is automatically added if the folder contains at least one file
);
// pseudo code check the date
if($arraypointer['date'] is today)
ftp_fget(file);
}
// close the connection
ftp_close($conn_id);
// output the buffer
var_dump($buff);
?>

Sending a SOAP message with PHP

what I'm trying to do is send a load of values captured from a form to a CRM system with SOAP and PHP. I've been reading up on SOAP for a while and I don't understand how to go about doing so, does anybody else know?
In order to do this it might be easiest to download a simple soap toolkit like 'NuSOAP' from sourceforge.
And then you would code something like the following (example submission of ISBN number):
<?php
// include the SOAP classes
require_once('nusoap.php');
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter';
//define method namespace
$namespace="urn:xmethods-BNPriceCheck";
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// if a fault occurred, output error info
if (isset($fault)) {
print "Error: ". $fault;
}
else if ($price == -1) {
print "The book is not in the database.";
} else {
// otherwise output the result
print "The price of book number ". $param[isbn] ." is $". $price;
}
// kill object
unset($client);
?>
This code snippet was taken directly from, which is also a good resource to view
http://developer.apple.com/internet/webservices/soapphp.html
Hope this helps.
You probably found a solution since then - but maybe the following helps someone else browsing for this:
soap-server.php:
<?php
class MySoapServer {
public function getMessage ()
{
return "Hello world!";
}
public function add ($n1,$n2)
{
return $n1+n2;
}
}
$option = array ('uri' => 'http://example.org/stacky/soap-server');
$server = new SoapServer(null,$option);
$server->setClass('MySoapServer');
$server->handle();
?>
and soap-client.php
<?php
$options = array ('uri' => 'http://example.org/stacky/soap-server',
'location' => 'http://localhost/soap-server.php');
$client = new SoapClient(null,$options);
echo $client ->getMessage();
echo "<br>";
echo $client ->add(41,1);
?>