Rectangle 27 3

Your return code is not important at all, because it's AJAX request so you are able to return anything you want. You return error code then process it using JS then return message to user. Example user click on button delete, he/she may do not have permission to do this, so you return json: status: error, type: permission. Then display to user the message belong to this error type.

You should combine 1 and 2 together. Write a function or class to check their command. Example:

$check = $session_check(USER_COMMAND);
if ($check) //has right
else //no right.

function session_check($command){
     $userCmdList = array(COMMAND_1,2,3,4);
     $modCmdList = array(COMMAND_2,3,4,5,6,7);
     switch ($_SESSION['group_id']){
          case "admin":
               return true;
               break;
          case "mod":
               if !in_array($command,$modCmdList) return false;
               else return true;
               break;
          case "user":
               if !in_array($command,$userCmdList) return false;
               else return true;
               break;
          default:
               break;
    }
}

What do You mean by using unique hash for each session? I use PHP session_start after login (no "Remember me" option). PHP creates SESSION_ID itself when called session_start(). link. I assumed that browsers remove the SESSION cookies after browser is closed. Correct me if I'm wrong. (There is also "Log out" button that uses session_destroy and unsets the session cookie.)

you can combine client agent + client IP + client session id. $_SESSION['hash'] = md5($agent.$IP.session_id()); This is unique for each browser and user. If you wait for session destroy so what if hacker takes user's session before they logged-out? By using session_hash if hacker uses this session_id but invalid session hash so this session will be destroyed. (the logged-in user's session will be stored in database)

This is good technique. Client agent and IP may change over time, but I assume they will be same at least as long as the browser is open :) I will consider using this.

php - Correct HTML status codes for unauthorized access and forbidden ...

php html ajax unauthorized
Rectangle 27 4

You can take a look here for catching file_get_content error

$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) { 
   echo "SUCCESS";
} else { 
   echo "FAILED";
}

oauth - PHP catch failed to open stream: HTTP request failed! HTTP/1.1...

php oauth error-handling oauth-2.0
Rectangle 27 4

You can take a look here for catching file_get_content error

$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) { 
   echo "SUCCESS";
} else { 
   echo "FAILED";
}

oauth - PHP catch failed to open stream: HTTP request failed! HTTP/1.1...

php oauth error-handling oauth-2.0
Rectangle 27 10

If the site requires basic authentication, you can give your credentials this way:

fopen("http://user:pass@www.example.com/path/to/resource", "r");

If it uses digest authentication, you'll have to handle it manually by reading the headers of the failed response and sending a new one with the correct headers. See HTTP context options for how to read and set headers and see how digest works in HTTP authentication with PHP.

php - [function.fopen]: failed to open stream: HTTP request failed! HT...

php fopen
Rectangle 27 5

<?php
if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] != 'admin' || $_SERVER['PHP_AUTH_PW'] != 'foobar') {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Unauthorized';
    exit;
}

+1 thanks @Long Ears, I think that is what I need indeed! When i put this code on the top of my php file it does ask for password nicely with the popup screen. BUT, when i type admin and foobar as login credentials the same login screen comes back with emptied fields and asks me again to type login/password. After three orso tries it says UNAUTHORISED.... any guesses ?? Thanks: much appreciated

@Sam if you have PHP running through CGI rather than as an Apache module then this won't work alone, here's a fix, besthostratings.com/articles/http-auth-php-cgi.html

apache - Passwordprotecting a Single PHP file with Apache2 or PHP inde...

php apache .htaccess apache2 .htpasswd
Rectangle 27 3

I do this sort of thing all the time in my Laravel Apps with no issues. This code allows the user to delete a resource through AJAX while presenting a bootstrap confirmation dialog first. The code is laid out in the order the events would occur.

<a class="delete-plan" href="{{ route('admin.plans.destroy', $plan['id']) }}" data-redirect="{{ route('admin.plans.index') }}" data-plan-name="{{ $plan['name'] }}" data-lang="billing.plans">
    <i class="fa fa-trash fa-lg"></i>
</a>
$('.delete-plan').on('click', function(e) {
    e.preventDefault();

    var data = {
        'route':        $(this).attr('href'),
        'redirect':     $(this).data('redirect'),
        'modal_title':  'Delete Plan',
        'content_view': 'Are you sure you want to delete plan: <strong>' + $(this).data('plan-name') + '</strong>?',
        'lang':         $(this).data('lang')
    };

    loadDestroyModal(data);
});

function loadDestroyModal(data) {
    $.get('/ajax/destroy-modal', { data: data }, function(modal) {
        $('body').append(modal);
        $('#destroy-modal').modal('show');
    });
}
// routed by /ajax/destroy-modal
public function destroyModal() {
    $data = Input::get('data');

    $params = [
        'route'    => $data['route'],
        'redirect' => $data['redirect'],
        'title'    => $data['modal_title'],
        'content'  => $data['content_view'],
        'lang'     => $data['lang']
    ];

    return View::make('_helpers.modal-destroy', $params);
}
<div id="destroy-modal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true"><i class="fa fa-times"></i></span>
                    <span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title">{{ $title }}</h4>
            </div>
            <div class="modal-body">
                {{ $content }}
            </div>
            <div class="modal-footer">
                <button id="modal-confirm" type="button" class="btn btn-primary" data-route="{{ $route }}"
                data-redirect="{{ $redirect }}" data-lang="{{ $lang }}">Confirm</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
$('body').on('click', '#destroy-modal #modal-confirm', function(e) {
    var redirect = $(this).data('redirect');
    var lang     = $(this).data('lang');

    $(this).html('<i class="fa fa-spinner fa-spin"></i> Please Wait');

    $.ajax({
        'url':     $(this).data('route'),
        'type':    'DELETE',
        'success': function(response) {
            if (response) {
                redirectWithFlashMessage(redirect, 'destroy', 'success', lang);
            } else {
                redirectWithFlashMessage(redirect, 'destroy', 'errors', lang);
            }
        }
    });
});
public function destroy($id)
{
    try
    {
        Stripe::plans()->destroy(['id' => $id]);

        return Response::json(TRUE);
    }
    catch (Exception $e)
    {
        return Response::json(FALSE);
    }
}
function redirectWithFlashMessage(redirect, type, status, lang) {
    var params = {
        type:   type,
        status: status,
        lang:   lang
    };

    $.get('/ajax/flash', params, function(response) {
        window.location.href = redirect;
    });
}

AJAX CONTROLLER (Redirect with Flash)

public function flashData() {
    $message_type = 'success' == Input::get('status') ? 'success' : 'failure';

    $message = Lang::get(Input::get('lang'))[Input::get('type') . '_' . $message_type];

    Session::flash($message_type, $message);

    return ['status' => $message_type, 'message' => $message];
}

It's a lot of code but once setup it's extremely easy to replicate.

php - 401 Unauthorized DELETE request to RESTful API in laravel via Aj...

php jquery ajax rest laravel
Rectangle 27 2

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information. HTTP access authentication is explained in "HTTP Authentication: Basic and Digest Access Authentication" [43].

php - [function.fopen]: failed to open stream: HTTP request failed! HT...

php fopen
Rectangle 27 25

The 401 (Unauthorized) response message is used by an origin server to challenge the authorization of a user agent. This response MUST include a WWW-Authenticate header field containing at least one challenge applicable to the requested resource.

java.io.IOException: No authentication challenges found
401 Unauthorized
407 Proxy Authentication Required

If you own the server-side API, then you can fix it by adding the required WWW-Authenticate header when you return 401 or 407. In my case, I fixed it in PHP as follows:

header('WWW-Authenticate: OAuth realm="users"');
header('HTTP/1.1 401 Unauthorized');

HttpURLConnection worked fine in Android 2.x but NOT in 4.1: No authen...

android authentication httpurlconnection
Rectangle 27 25

The 401 (Unauthorized) response message is used by an origin server to challenge the authorization of a user agent. This response MUST include a WWW-Authenticate header field containing at least one challenge applicable to the requested resource.

java.io.IOException: No authentication challenges found
401 Unauthorized
407 Proxy Authentication Required

If you own the server-side API, then you can fix it by adding the required WWW-Authenticate header when you return 401 or 407. In my case, I fixed it in PHP as follows:

header('WWW-Authenticate: OAuth realm="users"');
header('HTTP/1.1 401 Unauthorized');

HttpURLConnection worked fine in Android 2.x but NOT in 4.1: No authen...

android authentication httpurlconnection
Rectangle 27 1

You are trying to access a site that requires authentication, as maggie pointed out. fopen() does not support HTTP Basic Authentication, so you must use the Client URL Library to achieve such functionalities.

This is not true. The http wrapper supports basic authentication. What it doesn't support is digest authentication.

php - [function.fopen]: failed to open stream: HTTP request failed! HT...

php fopen
Rectangle 27 1

It gives a 401 because its using an invalid key (XXXXXXXX) since you're getting a similar response it could also be that you're sending an invalid api key or no key at all?

php - failed to open stream: HTTP request failed! HTTP/1.1 401 Unautho...

php stream steam
Rectangle 27 4

<?php
    /*
    ** Define a couple of functions for
    ** starting and ending an HTML document
    */
    function startPage()
    {
        print("<html>\n");
        print("<head>\n");
        print("<title>Listing 24-1</title>\n");
        print("</head>\n");
        print("<body>\n");
    }

    function endPage()
    {
        print("</body>\n");
        print("</html>\n");
    }
    /*
    ** test for username/password
    */
    if( ( isset($_SERVER['PHP_AUTH_USER'] ) && ( $_SERVER['PHP_AUTH_USER'] == "leon" ) ) AND
      ( isset($_SERVER['PHP_AUTH_PW'] ) && ( $_SERVER['PHP_AUTH_PW'] == "secret" )) )
    {
        startPage();

        print("You have logged in successfully!<br>\n");

        endPage();
    }
    else
    {
        //Send headers to cause a browser to request
        //username and password from user
        header("WWW-Authenticate: " .
            "Basic realm=\"Leon's Protected Area\"");
        header("HTTP/1.0 401 Unauthorized");

        //Show failure text, which browsers usually
        //show only after several failed attempts
        print("This page is protected by HTTP " .
            "Authentication.<br>\nUse <b>leon</b> " .
            "for the username, and <b>secret</b> " .
            "for the password.<br>\n");
    }
?>

How can I use Basic HTTP Authentication in PHP? - Stack Overflow

php authentication http-authentication http-basic-authentication server-variables
Rectangle 27 1

Your authentication systems works, but what if you fail to check the control security on each page you have? You should learn about the front controller pattern and see if it suits your needs better.

Related to front controller pattern, I advice you to also read those 2 chapters from the fantastic symfony documentation (they are somewhat related to symfony but talk about HTTP / PHP in general and how and why a framework may benefit your code in the end):

And If you are worried about security as you seem to be (and of course you should), take a look at the OWASAP top 10 web vulnerabilities (a must read for every web developer).

Specific to you question is the session hijacking problem, you can find more here.

PHP: session controll the pages from unauthorized access, with level -...

php session
Rectangle 27 0

Did you whitelist the IP of your server? This is not necessary by default for the browser key, but it is for the server key.

You can check it here:

Thank you all guys. I was facing the problem due to browser key and API key. Now its working great with Server API key.

Google updated the console a bit, you will be redirected following the link in my answer. You can see the button "Edit allowed IPs" there. I have put in to "Any IP allowed", depending on the secrecy of my key for security.

php - Google GCM server returns Unauthorized Error 401 - Stack Overflo...

php android json google-cloud-messaging
Rectangle 27 0

As many people wrote, you have to whitelist your server IPV4 and IPV6. If you want only IPV4, add this to your curl php init:

curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );

php - Google GCM server returns Unauthorized Error 401 - Stack Overflo...

php android json google-cloud-messaging
Rectangle 27 0

I had the same issue. What resolved it for me was registering my public ip, waiting for a few minutes and then refreshing the google api console page.

Android GCM Unauthorized 401 error with PHP - Stack Overflow

android android-gcm
Rectangle 27 0

I had the same problem and ended up adding "0::0/0" to my whitelist ip addresses. This fixed the problem for me. Though a better solution would be to get a real IPV6 to use for the server.

Android GCM Unauthorized 401 error with PHP - Stack Overflow

android android-gcm
Rectangle 27 0

<?php
if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] != 'admin' || $_SERVER['PHP_AUTH_PW'] != 'foobar') {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Unauthorized';
    exit;
}

+1 thanks @Long Ears, I think that is what I need indeed! When i put this code on the top of my php file it does ask for password nicely with the popup screen. BUT, when i type admin and foobar as login credentials the same login screen comes back with emptied fields and asks me again to type login/password. After three orso tries it says UNAUTHORISED.... any guesses ?? Thanks: much appreciated

@Sam if you have PHP running through CGI rather than as an Apache module then this won't work alone, here's a fix, besthostratings.com/articles/http-auth-php-cgi.html

apache - Passwordprotecting a Single PHP file with Apache2 or PHP inde...

php apache .htaccess apache2 .htpasswd
Rectangle 27 0

Check your youtube account. Do you have a channel created? If you don't you wont be able to add videos (via API or even in youtube).

After creating the channel in youtube it worked. no need for new code or new keys.

Can you tell me, how to create the channel in youtube and how to use in the php code

Uploading video to Youtube using Youtube Data API V3 and Google API Cl...

php youtube youtube-api google-api-php-client youtube-data-api
Rectangle 27 0

you're sending a $.POST request with jquery, yet you're trying to change the type to a GET. Use .ajax if you want to add custom options to the ajax request.

php - 401 UNAUTHORIZED error with jquery get method with Tastypie api ...

php jquery ajax django tastypie