PHP Basic Rest API with Custom Header - php

I'm fairly new to PHP Rest API. I would like to upgrade my knowledge so I need to create an authorisation for my web service. I'd like to ask first if they are authorised to view my web service, if not then they won't see it.
This is what I've done so far:
<?php
include('db.php');
$sql = "SELECT * FROM bb_users";
$stmt = $conn->prepare($sql);
$stmt->execute();
$set = array();
while($r = $stmt->fetchAll(PDO::FETCH_ASSOC)){
$set = $r;
}
// $username='ABC';
// $password='XYZ';
//header("Authorization: Basic " . base64_encode($username . ":" . $password));
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
echo json_encode($set);
?>
Any ideas? I would gladly appreciate your help. And if you could provide some tips or links to get started with.

This is a basic implementation of what you are trying to do. Keep in mind that this uses Basic access Authentication and it does not provide any protection against username an password since those are pretty much transmitted over the net.
To build a better more robust API I recommend https://www.apigility.org/ in my opinion it's one of the best, if not the best out there,
As far as the Authentication goes, I recommend OAuth.
FYI: I am assuming your code was correct and did not have any errors, so I just moved it inside the if block. There is a call to check_if_credentials_are_valid_function which is the function you will define and call to make sure the username and password are valid. If credentials are valid it will return the json encoded data and exit, otherwise it will continue to the end of the script and return a 401 status code.
<?php
$headers = apache_request_headers();
if(isset($headers['Authorization'])) {
$authorization = $headers['Authorization'];
if (preg_match('/Basic\s+(.*)$/i', $authorization, $auth)) {
// Split the string, base64 decode it
list($user, $pass) = explode(':', base64_decode($auth[1]));
if (check_if_credentials_are_valid_function($user, $pass)) {
include('db.php');
$sql = "SELECT * FROM bb_users";
$stmt = $conn->prepare($sql);
$stmt->execute();
$set = array();
while($r = $stmt->fetchAll(PDO::FETCH_ASSOC)){
$set = $r;
}
// $username='ABC';
// $password='XYZ';
//header("Authorization: Basic " . base64_encode($username . ":" . $password));
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
echo json_encode($set);
exit();
}
}
}
header('HTTP/1.0 401 Unauthorized');
exit();
?>

Related

web service in php is not displaying results

my php web service is not giving me json result from my database when i run it in web browser or i try to connect to it from my android app. When i test it through postman it gives me back results i json.
Here is my php code:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
include 'connection.php';
showStudent();
}
function showStudent()
{
global $connect;
$query = " Select * FROM demo; ";
$result = mysqli_query($connect, $query);
$number_of_rows = mysqli_num_rows($result);
$temp_array = array();
if($number_of_rows > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$temp_array[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode(array("demo"=>$temp_array));
mysqli_close($connect);
}
?>
here is my result from database through postman:
whil in web browser im not getting any of this:
can anybody see any problem with this, im actually not a php developer i tried to wrote this on my own for a project.
Thanks
You are checking for the method of submission first which is POST. while when you hit direct url it work as GET. So for getting data in web change POST to GET.
<?php
if($_SERVER["REQUEST_METHOD"]=="GET"){
include 'connection.php';
showStudent();
}

cross-origin request blocked with extra header

I am creating a apps with sql stuffs and i am using a online database, everything works fine if i input this header("Access-Control-Allow-Origin: *");
But the next few lines i need this header as well header('Content-Type', 'text/plain');
Once i insert that and run my html and to run this particular php file, i will get this error
error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.gamestopica.net/andrew/login.php. This can be fixed by moving the resource to the same domain or enabling CORS.
anyone know what i should do to fit those 2 header under the same php file without the cross-origin error?
my php file
<?php
header("Access-Control-Allow-Origin: *");
include_once('db.php');
session_start();
header('Content-Type', 'text/plain');
$username = $_POST['username'];
$password = $_POST['password'];
$verify = 0;
$result = $db->query("SELECT * FROM `userdetails` WHERE `username` = '".$username."'")
or die("fail");
if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_array($result);
$passwordDB = $row["Password"];
if($password == $passwordDB)
{
$_SESSION['user'] = $username;
$result2 = json_encode(
array("type"=>"true", "username"=>$_SESSION['user'])
);
echo $result2;
}
else
{
$result2 = json_encode(
array("type"=>"false")
);
echo $result2;
}
}
else
{
$result2 = json_encode(
array("type"=>"nothing")
);
echo $result2;
}
?>
Your call to header() is not valid syntax for that function. Try changing:
header('Content-Type', 'text/plain');
to
header('Content-Type: text/plain');
and see if that fixes your issue.

Mysql call stops all forms of output php

Hello, I'm kind of new to php, so don't bash on me, but I just can't figure out what the problem is with this code. So basically I have several forms of output, but as soon as I do anything with mysql ( even just connect and disconnect! ), it won't allow me to do any kind of output. It also won't allow me to redirect.
I tried taking all the code out between the mysql connect and disconnect code and it didn't help to resolve anything, However, as soon as I comment out the mysql connection code, all my outputs and redirects work! I'm trying to build a simple login script that gets the email and password from a form elsewhere. I would love to get this resolved so I could figure out if the rest of it works. And I know that 'header' will not work after echo; the echo and the file writes will not be there as soon as I can make sure this is working. Any help would be appreciated! Thanks!
<?php
/*
Login.php searches for the email address given by loginPage.php in the data base.
If the email is found and the password given by loginPage.php matches that stored
in the data base, a session will begin and the client will be redirected to the
main page.
*** INCOMPLETE ***
*/
echo "HELLO!";
$email = $_POST["email"];
$password = $_POST["password"];
$errorLog = fopen("login.txt", "w");
fwrite($errorLog, "***Sesion started***");
$mysql_id = mysql_connect("localhost", "root", "12131");
if (!$mysql_id)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('informationStation', $mysql_id);
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "';", $mysql_id);
if($results != null && $password == mysql_fetch_array($result))
{
$redirect = 'Location: http://127.0.1.1/main.php';
}
else
{
$redirect = 'Location: http://127.0.1.1/loginPage.php';
{
mysql_close($mysql_id);
fwrite($errorLog, "result: " . $results);
fwrite($errorLog, "redirect: " . $redirect);
fclose($errorLog);
header($redirect);
?>
Try this to get you started..
$results = mysql_query("SELECT password FROM Personals WHERE email = '" . $email . "'", $mysql_id) or die(mysql_error());
But you also need to read about sql injection.
And you should not store passwords in your database without salting and hashing them.
And you also need to use array syntax to access the data from your result...
$mysql = mysql_connect("localhost", "root", "12131") or die('Could not connect: ' . mysql_error());
mysql_select_db('informationStation', $mysql);
function loged($email, $password) {
$result = mysql_query("SELECT id FROM Personals WHERE email = '" . $email . "' AND password='" . $password . "'");
if(mysql_num_rows($result) != 1)
return false;
return true;
}
if(loged(mysql_real_escape_string($email), md5($password))) {
header('Location: http://127.0.1.1/mainPage.php');
exit;
}
header('Location: http://127.0.1.1/loginPage.php');
In this example you need to store users password using md5 encryption method (search for other more securely encryption methods).
Also we've escaped the email address against sql injection.
I've created a function which can be called every time you want to see if the user is loged in or not.
Note that this is not a complete login script. You will also need to make a login function where you'll have to start a new session for each user.

PHP script not redirecting via header

I am looking for some kind of bug in my code which is causing this PHP page to not redirect. I'm looking to see if someone might know the cause of this problem (it may have something to do with the cookies).
inc_vars.php:
<?php
//some of the variables have been omitted.
$pid = 'gbb';
$dbtable ='';
$dbname = '';
$dbuser = '';
$dbpass = '';
$connect = mysql_connect('localhost', $dbuser, $dbpass);
if(!$connect){
header('Location: omitted');
die();
}
mysql_select_db ($dbname, $connect);
$webroot = 'omitted';
$share_page = $webroot . '/share-the-training';
$gift = $webroot . '/free-video?setuser=1199';
$bonus_content = $webroot . '/awesome-bonus';
$share_php = $webroot . '/share.php';
?>
refresh_id.php:
<?php
include_once('inc_vars.php');
$results = mysql_query("SELECT id FROM " . $dbtable . " WHERE email='" . $_GET['email'] . "'");
if(!$results || mysql_num_rows($results)==0){
header('Location: ' . $share_page . '?errorcode=1');
die();
}
$res_arr = mysql_fetch_assoc ($results);
setcookie($pid . "_viral", (string)$res_arr['id'], time() + 3600 * 365);
move_on();
function move_on(){
header ('Location: ' . $share_php);
die();
}
?>
When the person visits refresh_id.php?email=their_email they should redirect to the $share_php page. This is not working.
However, if this scenario happens: refresh_id.php?email=an-email-that-is-not-in-database then the script redirects to $share_page absolutely fine.
I have tried this with and without the gbb_viral cookie in place. I'm not sure why this isn't working. All pages are live and on the internet right now in case you want to look for yourself.
omitted
An email that exists in the database is as follows: acctrafficcop#gmail.com (for those that want to test this)
UPDATE
Stupid mistake with scopes. I simply added global $share_php in the move_on() function and everything is working fine now. Thank you everyone for the heads up on SQL injection, I am switching over to prepared statements right now.
In your move_on function, the variable $share_php does not exist because of variable scope. Therefore your redirect looks like this: Location:. There is no URL in the Location header.
You can pass the variable into the function, or use the global keyword to make it available. Try this:
move_on('/redirect_url');
function move_on($url){
header ('Location: ' . $url);
die();
}
In fact, in refresh_id.php I don't see a variable called $share_php anywhere, so you are redirecting to an empty URL.
You also need to set a status header for the browser to honor the location header. Try adding
header('HTTP/1.1 303 See Other');
Using curl will help you debug. Also, your are setting yourself up for SQL Injection with your SQL query.
Edit: After reading the second answer, it is correct that you aren't passing in a location to your redirection function. This should be fixed as well.
$results = mysql_query("SELECT id FROM " . $dbtable . " WHERE email='" . $_GET['email'] . "'");
Never trust input from users like this. Instead, use a SQL bind. Here's how you would do it with the mysqli library: http://php.net/manual/en/mysqli-stmt.bind-param.php

Can't login on a website with Webservice and PHP

I have access to the webservice of an website which allow you to get a user information if you know his username and security code. I tried to do this with a simple test, but I always recieve the message "unknown username or wrong security-code", although the information is correct.
Any idea what is wrong with this code?
<?php
$client = new SoapClient('http://handballmania.tk/fx/WebService.wsdl');
$Username = 'icsulescu';
$SecurityCode = 'nusa7maru';
try {
$answer = $client->GetTeam($Username, $SecurityCode);
}
catch (Exception $e) {
echo $e->getMessage();
}
?>
I think the parameters sent should be contained in an array.
...
$user_info["Username"] = "icsulescu";
$user_info["SecurityCode"] = "nusa7maru";
...
$answer = $client->GetTeam($user_info);
...

Categories