Consuming web services with PHP - javascript

I am completely new to web services and I want to implement one. I did some research and I came across this site http://www.9lessons.info/2012/05/create-restful-services-api-in-php.html. The thing is given here but I have no idea on how to consume this web service as a client.
Let's say I have a client file which is supposed to display the users.
How do i do that?
Thanks.

Here is a sample JSON Web-service code snippet for u to learn....
but you should have a basic knowledge b4 to dive in...!
for example below code is in submit_user_details.php
you need to call the page for example
*localhost/appname/webservices/submit_user_details.php*
<?php
require_once('../Connections/db_connection.php');
?>
<?php
error_reporting(E_ERROR);
$json = file_get_contents('php://input');
$obj = json_decode($json);
$pin=$obj->{'pin'};
$name=$obj->{'name'};
$phone=$obj->{'phone'};
$second_number=$obj->{'second_number'};
$home_no=$obj->{'home_no'};
$email=$obj->{'email'};
//mysql_select_db($db, $db_connection)or die ('->>Error selecting database'.mysql_error());
$query = "UPDATE `haji_members` SET `name`= '".$name."',`phone`= '".$phone."',`secondary_phone`= '".$second_number."',`home_number`= '".$home_no."',`email`= '".$email."' WHERE pincode='".$pin."'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
$posts = array();
if($result != 1)
{
$post = array("message"=>"0");
$posts[] = array('post'=>$post);
}
else{
$post = array("message"=>"1");
$posts[] = array('post'=>$post);
}
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
#mysql_close($db_connection);
?>
The output would look like
{"posts":[{"post":{"tot_count":"0","username":null,"password":null}}]}

Related

i can't put the input data into the database

this is my code. i've done this before in other computer and it's okay, but now when try it in my laptop,it can't be done. idk what is the problem, it will show blank in phpmyadmin. i'm using xampp v3.2.2, is that will be the problem?
<html><head><title>Your Data</title></head>
<body>
<?php
$n = $_POST["n"];
$c = $_POST["contact"];
$e = $_POST["email"];
$cm = $_POST["campus"];
$m1 = $_POST["member1"];
$m2 = $_POST["member2"];
$m3 = $_POST["member3"];
$connect = mysqli_connect("localhost","root","") or die("Unable to connect MySQL".mysqli_error());
$db = mysqli_select_db($connect,"multimedia_db") or die("Unable to select database");
$query1 = "INSERT INTO teams(advisor_name,advisor_contact,advisor_email,advisor_campus,member1,member2,member3) VALUES ('$n','$c','$e','$cm','$m1','$m2','$m3')";
$data1 = mysqli_query($connect,$query1) or die("SQL statement failed"); //records are assigned to variable data
echo "You've succesfully register";
?>
</body>
</html>
I don't use MySQLi very often. So I'll explain how to use PDO. Just so you know PDO means PHP Data Objects. The reason I'm explaining, PDO is because, if done properly, it makes SQL injection almost impossible.
Connection
connecting to your database is generally done in a separate file. Here is an example:
con.php
<?php
$hostname = '';
$username = '';
$password = '';
$dbname = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
This is just connecting to the database, so we don't have to keep connecting to other pages, we just refer to this page with an include, like this:
<?php include 'con.php'; ?>
We can put this on any page and it'll include the connection to the database. For example, if you want to select from a database:
<?php
include 'con.php';
$load_data = $dbh->prepare("SELECT * FROM user_table");
if ($load_data->execute()) {
$load_data->setFetchMode(PDO::FETCH_ASSOC);
}
while ($row = $load_data->fetch()) {
$name = $row['name'];
echo $name;
}
?>
This would simply SELECT everything from the user_table from the column name and would display all the matching records.
If you're trying to do an INSERT instead:
<?php
include 'con.php';
$post_name = $_POST['post_name'];
$stmt = $dbh->prepare("INSERT INTO user_table (name) VALUES (:user_name)");
$stmt->bindParam(':user_name', $post_name, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "Success";
} else {
echo "Failed";
}
?>
So the $post_name would be the name you give your input on a form in this case name="post_name" that would be inserted into the user_table.
Hope this helps and FYI here is a very good tutorial on how to do INSERT, UPDATE and DELETE using PDO.
i've found the solution for my question. It's just that i forgot to put localhost in front of the 'url'. no wonder it showed blank.
like 'localhost/sem5/saveRegistration.php'.
i'm sorry for the inconvenience. still a beginner using this hehe

AJAX function for retrieving postgres data not working

I have a simple AJAX function bound to a button that should execute a PostgreSQL query. However, when I click the button that I bound the ajax query to, all I get is the confirmation that the database connection was successful. Nothing seems to happen withe the ajax result (should be printing to console in the handleAjax() function. What am I doing wrong?
This is the javascript code (with jquery):
$(document).ready(function() {
function sendAjax() {
$.ajax({
url: "db/database.php",
success: function (result) {
handleAjax(result);
}
});
}
function handleAjax(result) {
console.log(result);
}
$("#submit-button").on("click", sendAjax);
});
And this it the contents of database.php:
<?php
function dbconn(){
ini_set('display_errors', 1); // Displays errors
//database login info
$host = 'localhost';
$port = 5432;
$dbname = 'sms';
$user = 'postgres';
$password = 'postgres';
// establish connection
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
}
}
$conn = dbconn();
$sql = "SELECT * FROM numbers;";
$result = pg_query( $sql ) or die('Query Failed: ' .pg_last_error());
$count = 0;
$text = 'error';
while( $row = pg_fetch_array( $result, null, PGSQL_ASSOC ) ) {
$text = $row['message'];
//echo $text;
}
pg_free_result( $result );
?>
The problem is in the database.php file, all you get is "Connected." because you don't print your result at the end. Ajax only receive the output of the php file.
So at the end of your php file you should add :
echo $text;
And you also should remove the echo "Connected.";
AJAX is not a magic wand that in magic way reads PHP code. Let's say AJAX is a user. So what does user do.
Open web page
Wait until PHP execute code and display data
Tells you what he sees
If you don't display anything, ajax can't tell you what he saw.
In thi's place is worth to say that the best way to communicate between PHP and AJAX is using JSON format.
Your code generally is good. All you have to do is to display your data. All your data is in your $text var. So let's convert your array ($text) to JSON.
header('Content-Type: application/json');
echo json_encode($text);
First you set content-type to json, so ajax knows that he reads json. Then you encode (convert) your PHP array to js-friendly format (JSON). Also delete unnecessary echoes like 'Conntected' because as I said, AJAX reads everything what he sees.
You should return $conn from dbconn()
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
return $conn;
}

Header not working in php

I have a program that brings an image from the database and displays it inside an image div in my website. The below code was working successfully on my local wamp server but when I moved it to an online server it did not work anymore.
<?php
session_start();
include 'dbConnector.php';
$uID = $_SESSION['loggedUserID'];
$sql = "SELECT photo FROM hostmeuser WHERE userID = '$uID'";
$result = $conn->query($sql);
if(!$row = mysqli_fetch_assoc($result))
{
$imgData = "Assets/man.jpg";
}
else
{
$imgData = $row['photo'];
}
header("content-type: image/jpg");
echo $imgData;
?>
I have noticed that all (header) functions are not working on the new server and I have no control over this server so I replaced every:
header("Location: example.php")
with:
?>
<script type="text/javascript">
window.location.replace("example.php");
</script>
<?php
it is working fine now on most cases but not this one!
header("content-type: image/jpg");
Can you suggest any solution for this? or at least do you know how to represent this command in javascript?

Is it possible to access the Prestashop's Web service by client (customer) login instead the key?

I'm studying Prestashop's development. And I trying to create a "third part" side application with react.js (React Native for more precision) and catch Json data in the prestashop's webservice. But I want to let the "customer" make login with his own account and only his account. With CRUD also.
in advance; Very thank you for your patience and attention.
Best Regards.
Michel Diz
Prestashop backoffice login give no access to webservices. Webservices must be enabled and a key generated. So, I recommend you that change your "login" way. Customers accounts are not related with webservices and webservices are only used to access stored data un Prestashop (more like Backoffice than Frontoffice).
What exactly do you need to do?
I hope it helps you.
I don't know if you're still searching for a solution but there is a way actually.
DO MAKE SURE IT IS A SECURE LOGIN.
Since you're giving access to all prestashop data do make sure the login is very secure. I've been able to recreate it with PHP I think that with some additions you're able to recreate it the way you want it. See it as a guideline.
To create a login system by using the prestashop webservice you'll need three things
Access through webservice to the customers table
The COOKIE_KEY, defined in app/config -> parameters.php:: 'cookie_key' => '12321test';
Some expierence with PHP
The first thing is to get the customers table from the webservice.
// code placeholder
require_once('./../PSWebServiceLibrary.php');
/**
* get information from PrestaShop
*/
$webService = new PrestaShopWebservice($url, $key, $debug);
$COOKIE_KEY = 'CookieKey';
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
$optUser = array(
'resource' => 'customers',
'filter[email]' => '[' . $email . ']',
'display' => '[id,email,lastname,firstname,passwd]'
);
$resultUser = ($webService->get($optUser));
$json = json_encode($resultUser);
The second and most important thing is to Check the user input
// code placeholder
foreach ($resultUser->customers->customer as $info) {
// Prestashop uses the cookie_key in combination with a salt key. To check the password use the php function: password_verify();
$salt = substr($info->passwd, strrpos($info->passwd, ':') + 1, 2);
$ZCpassword = md5($COOKIE_KEY . $password) . ':' . $salt;
// Check if password comparison is true or false
if (password_verify($password, $info->passwd) == true) {
session_start();
$response = array();
$response['status'] = 'succes';
$response['message'] = "You did it!";
setcookie("userId", $info->id);
header('Content-type: application/json');
echo json_encode($response);
} else {
$response = array();
$response['status'] = 'error';
$response['message'] = 'Wrong password';
header('Content-type: application/json');
echo json_encode($response);
}
}
This is how to reproduce the issue to a working example.
Hope this helps!
For those who are still searching for this answer,
<?
if (isset($_GET["email"]) && isset($_GET["password"]) )
{
$email = $_GET["email"];
$password = $_GET["password"];
$COOKIE_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$jsonurl = "https://XXXXXXXXXXXXXXXXXXXX#example.com/api/customers?filter[email]=".$email."&display=[passwd]&output_format=JSON";
$json = file_get_contents($jsonurl);
$json_a = json_decode($json, true);
$loopone = $json_a['customers'];
$looptwo = $loopone[0];
$loopthree = $looptwo['passwd'];
$ZCpassword = md5($COOKIE_KEY . $password);
if (strcmp($loopthree, $ZCpassword) == 0) {
echo "sucess";
} else {
echo "fail";
}
}
else
{
echo "Send something with url dude";
}
?>

Javascript and PHP scan for nudity

I am trying to not allow the uploading of files that have nudity to my server. I found javascript online that will scan a photo for nudity. It comes with demo pics and an html file and js files. I am using PHP to upload the file and I am having trouble not allowing if the scan find that the pic has nudity.
Here is my code sample:
$q= "insert into $table values('', '$email', '$aim', '$icq', '$yahoo', '$homepage', '0', '0', '0', '0', '0', '0', '', now(),'$myip','$email2','$password','$title','$download','$approved','$allowdelete','$author','$facebook','$piclink','$domain','$option3','$secret')";
$result = mysql_query($q) or die("Failed: $sql - ".mysql_error());
$q = "select max(id) from $table";
$result = mysql_query($q);
$resrow = mysql_fetch_row($result);
$id = $resrow[0];
$file = $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], "pics/".$id.".".$picext);
$picfile=$id.".".$picext;
echo '<script type="text/javascript" <src="nude.js">';
echo 'nude.load("pics/".<? echo $picfile; ?>);nude.scan(function(result){if(!result){ <? $nude = false; ?>;}else{ $nude = true;}})';
echo '</script>';
if ($nude === false) {
$q = "update $table set picfile = '".$id.".".$picext."' where id='$id'";
$result = mysql_query($q);
Header("Location: index.php?id=$id");
} else{
echo '<script type="text/javascript">';
echo 'alert("Nudity found. Please try again.")';
echo '</script>';
$q = "delete from $table where id='$id'";
$result = mysql_query($q);
unlink("pics/".$picfile);
Header("Location: new2.php");
}
The code uploads the file and then it's supposed to check the file for nudity and delete it and tell the user to try again if nudity is found. If nudity is not found the user is brought to the main page of the site.(This is the add new photo page). All of the PHP is working fine, but since the javascript doesn't seem to be running the file i uploaded and then since $nude isn't set it goes into the else of the if statement and again the js doesnt run(no alert box), and then the file is deleted. How can I make the javascript run to scan my uploaded pic for nudity? What am I doing wrong here?
Any help is greatly appreciated!
P.S.
For those that would like to see the js file that is doing the scanning: http://pastebin.com/MpG7HntQ
The problem is that this line:
echo 'nude.load("pics/".<? echo $picfile; ?>);nude.scan(function(result){if(!result){ <? $nude = false; ?>;}else{ $nude = true;}})';
Doesn't do what you think it does.
When you output JavaScript via echo(), that code runs on the browser or client side and doesn't run until after the PHP script has finished.
You'll either need to port the code to PHP or use an AJAX call to report the validity of the images.

Categories

Resources