Category Archives: http

How does PHP handle multiple clients?

When a client requests a PHP file, does the server execute the code, serve the client and close the script? Or does the server run a single instance of the PHP script from boot to shutdown? If not, does Apache start a new thread/run a new "program" for each client?

If multiple clients are connected (HTTP Long Polling) at the same time, can the server hold back its response to all of them until it gets a specific HTTP get request from another client?

429 HTTP error during development on Xampp

I have read quite a bit about the 429 error and i understand why it occurs and what protection it provides, the problem is that i am working on an application and i am using xampp as my development server and this error has now occurred for the second time, it is really annoying as it halts my development process, the first time it occurred i had to wait for like 14 hours and this time around the retry-after header indicated that the rate limit will reset after 4 days. I have'nt been able to find an solution so far but there must be a workaround to this as it makes no sense to have this rate limiting feature on while working on a development server.

Any help would be appreciated. Thanx

A screenshot of the response.

Trouble with Angular 2 http.get method

Salutations. I'm trying to learn Angular 2 by rebuilding the front end of a project I did previously while using the same back end code. The original project used jQuery on the front end and PHP in the back. I'm at the point where I want to start hooking my the front end to the back but I can't seem to get it to work.

Currently I have my original back end code running on apache2 on localhost and test Angular app is running on localhost:4200. The back end file I'm trying to access is at ajax.php (path is 'localhost/pokemon/ajax.php') and I have a line in that file to log an error whenever that file is referenced.

When I do http.get from my Angular 2 service and log the result on my component, I get [object Object] And the ajax.php doesn't log the message so it seemingly hasn't been called.

Here's my code. I The functions in question are near the bottom of each file.

hero.service.ts

import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { MessageService } from './message.service';

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';

@Injectable()
export class HeroService {
  private heroesUrl = 'api/heroes';

  constructor(
    private messageService: MessageService,
    private http: HttpClient
  ) { }


  getHeroes (): Observable<Hero[]> {
    //return this.http.get<Hero[]>(this.heroesUrl)
    return null;
  }

  getHero(id: number): Observable<Hero> {
    // TODO: send the message _after_ fetching the hero
    this.messageService.add(`HeroService: fetched hero id=${id}`);
    return of(HEROES.find(hero => hero.id === id));
  }

  //calls http.get
  testFunc() {
    console.log("Test func is being called in the service");
    return of(this.http.get('localhost/pokemon/ajax.php?method=getTypes'));
  }
}

And the component I'm trying to test with

heroes.component.ts

import { Component, OnInit } from '@angular/core';

import { Hero } from '../hero';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  heroes: Hero[];

  constructor(private heroService: HeroService) { }

  ngOnInit() {
    console.log("Init is being called");
    //this.getHeroes();
    this.testFunc();
  }

  //calls the test function
  testFunc(): void {
    console.log("Test function is being called");
    this.heroService.testFunc()
      .subscribe(
        data => console.log("Got this: " + data),
        err => console.log("Error " + err),
        () => console.log("Done!")
      );
  }
}

I also tried to get the data from a live server with the same app but the result was the same.

Thanks!

Why http status code is different when using "apache httpclient" and "httpurlconnection"?

I am now implementing weibo oauth2 login. I used two method - apache httpclient and httpurlconnection. But HTTP response code is different in two case.

String accessToken = "***";
String weiboUid = "***";

try {
        URL url = new URL("https://api.weibo.com/2/users/show.json?access_token=" + accessToken + "&uid=" + weiboUid);
        conn2 = (HttpURLConnection) url.openConnection();
        conn2.setConnectTimeout(10000);
        conn2.setDoInput(true);
        conn2.setDoOutput(true);
        conn2.setRequestMethod("GET");

        outputStream = conn2.getOutputStream();
        outputStream.flush();

        int responseCode = conn2.getResponseCode();

        StringBuilder responseReq = new StringBuilder();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn2.getInputStream()));
            while ((line = br.readLine()) != null) {
                responseReq.append(line).append("\n");
            }
            br.close();
        } else {
            throw new Exception("data not exist!");
        }

        String result = responseReq.toString().trim();
        JsonParser parser = new JsonParser();
        JsonObject jsonObject = parser.parse(result).getAsJsonObject();
        String nickname = jsonObject.get("screen_name").getAsString();

        System.out.println(nickname);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (conn2 != null)
            conn2.disconnect();
    }

In this case, responseCode is 405 and excuted "throw new Exception("data not exist!");".

But when I use apache httpclient library, response code is 200 and I can get the login information.

String accessToken = "***";
String weiboUid = "***";
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("https://api.weibo.com/2/users/show.json?access_token=" + accessToken + "&uid=" + weiboUid);

    try {
        HttpResponse response = client.execute(request);
        System.out.println("Response Code : " +
                response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

What is the difference between apache httpclient and httpurlconnection?

Why http status code is different when using "apache httpclient" and "httpurlconnection"?

I am now implementing weibo oauth2 login. I used two method - apache httpclient and httpurlconnection. But HTTP response code is different in two case.

String accessToken = "***";
String weiboUid = "***";

try {
        URL url = new URL("https://api.weibo.com/2/users/show.json?access_token=" + accessToken + "&uid=" + weiboUid);
        conn2 = (HttpURLConnection) url.openConnection();
        conn2.setConnectTimeout(10000);
        conn2.setDoInput(true);
        conn2.setDoOutput(true);
        conn2.setRequestMethod("GET");

        outputStream = conn2.getOutputStream();
        outputStream.flush();

        int responseCode = conn2.getResponseCode();

        StringBuilder responseReq = new StringBuilder();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn2.getInputStream()));
            while ((line = br.readLine()) != null) {
                responseReq.append(line).append("\n");
            }
            br.close();
        } else {
            throw new Exception("data not exist!");
        }

        String result = responseReq.toString().trim();
        JsonParser parser = new JsonParser();
        JsonObject jsonObject = parser.parse(result).getAsJsonObject();
        String nickname = jsonObject.get("screen_name").getAsString();

        System.out.println(nickname);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (conn2 != null)
            conn2.disconnect();
    }

In this case, responseCode is 405 and excuted "throw new Exception("data not exist!");".

But when I use apache httpclient library, response code is 200 and I can get the login information.

String accessToken = "***";
String weiboUid = "***";
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("https://api.weibo.com/2/users/show.json?access_token=" + accessToken + "&uid=" + weiboUid);

    try {
        HttpResponse response = client.execute(request);
        System.out.println("Response Code : " +
                response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

What is the difference between apache httpclient and httpurlconnection?

Redirect unknown subdomains from http to https

I got a project where clients can generate their own template based websites. These websites will (in most cases) be subdomains of the main page. However, some of them will have own domains. These websites generate from one PHP project. It checks for the subdomain or the domain and renders the right data.

In order to fit the new EU data protection laws we need to make all this websites use https. The certificates are there already.

I have inserted this code into the .htaccess:

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

The result is that nothing really happens. If i type in http://subdomain.domain.com then it shows me an 404 error. The site cannot be found on the server. If i type it in with https it works. But there is just no redirect. The code doesn´t work in my eyes.

I looked at other examples where people did, what i would call "static redirects". They typed in the domain name and were able to make an 301 redirect to https.

Within this project it´s just not possible due to too many subdomains and domains the several client websites have.

Can anyone give me a hint on this?

How to enforce password policy change in apache http server?

We are using HTTP server to route the request to Winchill PLM. There is a requirement to force the user to change the password once the login first time into the PLM. In order to achieve this, PTC ( Winchill PLM Vendor) posted a note stating that this can be done through Apache setting.

Could somebody help us on what is the setting to be done in Apache httpd conf file so that Apache validates the auth data with Winchill directory server and also force the user to change if it is first time login.

Tomcat server taking long time to send the response back

I've written a server in Apache Tomcat that I'm using for performance analysis & benchmarking. Profiling the server is part of the equation to ensure there is no unnecessary time consumption on the server.

Mechanism:

A client sends a payload of 20KB to the server. The HttpServlet notifies me about the request using doPost(). I'm using the request.getInputStream() to read all the data.

According to the HttpServlet documentation:

Called by the server (via the service method) to allow a servlet to handle a POST request. The HTTP POST method allows the client to send data of unlimited length to the Web server a single time

My current understanding is, this inputStream reads data from a local inputStream where the network stack has buffered all the data coming from the client in a request. Sometimes reading data from this inputStream takes merely a few miliseconds but other times it can take over 10 seconds. Now I'm skeptical that the inputStream is probably reading the data from the network stream rather then a local buffered stream which means the HTTP servlet is acting like TCP sockets in which the data is streamed to the destination.

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Long startTime = Calendar.getInstance().getTimeInMillis();
        String clientRequestPayload = IOUtils.toString(request.getInputStream(), "UTF-8");
       Long endTime = Calendar.getInstance().getTimeInMillis();

      //send the response back
}

So my question is:

Does the inputStream provided by HTTPServlet read data from a network input stream or a local disk input stream?

Tomcat server taking long time to send the response back

I've written a server in Apache Tomcat that I'm using for performance analysis & benchmarking. Profiling the server is part of the equation to ensure there is no unnecessary time consumption on the server.

Mechanism:

A client sends a payload of 20KB to the server. The HttpServlet notifies me about the request using doPost(). I'm using the request.getInputStream() to read all the data.

According to the HttpServlet documentation:

Called by the server (via the service method) to allow a servlet to handle a POST request. The HTTP POST method allows the client to send data of unlimited length to the Web server a single time

My current understanding is, this inputStream reads data from a local inputStream where the network stack has buffered all the data coming from the client in a request. Sometimes reading data from this inputStream takes merely a few miliseconds but other times it can take over 10 seconds. Now I'm skeptical that the inputStream is probably reading the data from the network stream rather then a local buffered stream which means the HTTP servlet is acting like TCP sockets in which the data is streamed to the destination.

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Long startTime = Calendar.getInstance().getTimeInMillis();
        String clientRequestPayload = IOUtils.toString(request.getInputStream(), "UTF-8");
       Long endTime = Calendar.getInstance().getTimeInMillis();

      //send the response back
}

So my question is:

Does the inputStream provided by HTTPServlet read data from a network input stream or a local disk input stream?

Tomcat server taking long time to send the response back

I've written a server in Apache Tomcat that I'm using for performance analysis & benchmarking. Profiling the server is part of the equation to ensure there is no unnecessary time consumption on the server.

Mechanism:

A client sends a payload of 20KB to the server. The HttpServlet notifies me about the request using doPost(). I'm using the request.getInputStream() to read all the data.

According to the HttpServlet documentation:

Called by the server (via the service method) to allow a servlet to handle a POST request. The HTTP POST method allows the client to send data of unlimited length to the Web server a single time

My current understanding is, this inputStream reads data from a local inputStream where the network stack has buffered all the data coming from the client in a request. Sometimes reading data from this inputStream takes merely a few miliseconds but other times it can take over 10 seconds. Now I'm skeptical that the inputStream is probably reading the data from the network stream rather then a local buffered stream which means the HTTP servlet is acting like TCP sockets in which the data is streamed to the destination.

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Long startTime = Calendar.getInstance().getTimeInMillis();
        String clientRequestPayload = IOUtils.toString(request.getInputStream(), "UTF-8");
       Long endTime = Calendar.getInstance().getTimeInMillis();

      //send the response back
}

So my question is:

Does the inputStream provided by HTTPServlet read data from a network input stream or a local disk input stream?