1
\$\begingroup\$

I've been writing classic ASP.NET web services for a while now, and this is my first time writing a PHP based web service. I'm rather new to PHP as well.

In ASP.NET, you directly call the web method that you wish to be executed, but I'm not sure if PHP has a similar functionality.

Instead I'm calling a PHP page, and to it I'm passing the method name to be executed. Following is my code -

PHP Web Service

<?php
    require_once 'classes/CommonFunctionality.php';

    // Getting the json data from the request
    $json_data = json_decode(file_get_contents("php://input"));
    $response = '';

    // Checking if the data is null..
    if(is_null($json_data)) 
    {
        $response = json_encode(array("status" => -1, "message" => "Insufficient parmaters!"));
    }
    else
    {       
        // Checking if it's null or if it exists...
        if(!property_exists($json_data, "MethodName") || is_null($json_data->MethodName) || function_exists($json_data->MethodName . "()"))
        {
            $response = json_encode(array("status" => 0, "message" => "Invalid function name."));
        }
        else 
        {   
            // Get method name...           
            $methodName = $json_data->MethodName;
            // Call the method...
            $response = $methodName();
        }       
    }
    header('Content-type: application/json');
    echo $response;

    /****************************
     * Methods defined for use. *
     ****************************/
    function GetAllCrmUsers()
    {
        // Adding crm users class.
        $userArray = CrmUsers::GetAllUsers();
        return json_encode(array("status" => 200, "value" => json_encode($userArray)));
    }
?>

AJAX call

// URL, Data to send, Call back function.
AjaxCall($("#hdnWbUrl").val() , {MethodName : 'GetAllCrmUsers'}, BindData);

Generic jQuery ajax method

function AjaxCall(url, data, callBack){         
    $.ajax({
        url : url,
        type : 'POST',
        data : JSON.stringify(data),
        contentType : 'application/json utf-8',
        dataType : 'json',
        success : function(data, textStatus, jqxhr){                    
            callBack(data);
        },
        error : function (jqxhr, textStatus, errorMessage){ 
            console.log(argument);              
        }               
    })
}

Now my question is if there is a better way to do this, something that I might be unaware of.

\$\endgroup\$
3
\$\begingroup\$

First I would like to say, congratulations on stepping out of the Microsoft bubble!

To begin, most PHP functions are very similar (if not exactly the same) to their linux counterparts. Some of them even just directly call their linux counterparts and return the result. You don't have to know linux shell script to know PHP (or vice versa) but it definitely helps and knowing that there is a deeply connected relationship between the two is a enlightening.

PHP has a few global variables that you should familiarize yourself with:

  1. $_POST: holds any POST data sent with the request
  2. $_GET: holds any GET data sent with the request
  3. $_SESSION: holds the session data

My first recommendation for you is to use the $_POST variable instead of using file_get_contents("php://input").

I have to be honest, in all my years of PHP development, I've never used file_get_contents("php://input") for anything. I didn't even know what that did when I read this post. I had to look it up so that I could answer intelligently. All the POST data will be nicely, and automatically, placed into the $_POST array for you every single time.

My second recommendation for you is to checkout the PHP function empty(). This can be used on arrays with any key, even if the key doesn't exist, to check either if the key actually exists or if the key has an empty value. It's great for an initial check on POST data.

So for example, you could replace:

if(!property_exists($json_data, "MethodName") || is_null($json_data->MethodName) || function_exists($json_data->MethodName . "()"))

with

if(empty($_POST['MethodName']))

Pretty neat right?

The only caveat with this function is that it will return true not only if the array index doesn't exist, but also if the value at the array index evaluates to false ("", 0, array(), null, etc...). If you need to handle values that evaluate to false differently than you can use isset() either in addition to or instead of empty() which will tell you if the key is set, regardless of whether the value is an empty value or not.

So basically, $_POST, empty(), isset() are your bread and butter for form data processing in PHP. Use them wisely. :)

You should also check out unset()([http://]php.net/manual/en/function.unset.php), which lets you unset keys in your data arrays, for example, to remove keys that are set but have empty values that you'd rather just not be in the array at all.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.