Php code/library is not for multiple request in http it only allows single connection and prioritize new request

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
User avatar
xiao23
New php-forum User
New php-forum User
Posts: 11
Joined: Tue Mar 12, 2019 7:21 am

Tue Mar 12, 2019 7:29 am

Greetings!
Good evening

It was my first time here :)

I 've been struggling for 2 months just in connecting my device to the php server because I send simultaneous request (3) to the web server (php code/library) to update the specific field in firebase

I hope you can help me guys!
thank you

here's the code

php code

Code: Select all

<?php

require 'firebaseLib.php';
$Trash = $_GET["trash"];

$Distance = $_GET["distance"];
$Temperature = $_GET["temp_f"];
$Humidity= $_GET["humidity"];


// --- This is your Firebase URL
$baseURI = 'https://thesis1-69.firebaseio.com';
// --- Use your token from Firebase here
$token = 'MI3ZrLNP8YrtJbZqcr2vazG8x7wPh5cheiCyR1rM';
// --- Here is your parameter from the http GET


 $firebasePath = '/thesis1-69/';

$devicestatus= array('Distance' => $Distance,'Temperature' => $Temperature,'Humidity' => $Humidity);


$full= array($Trash => $devicestatus);

/// --- Making calls
$fb = new Firebase($baseURI, $token);
$fb -> update($firebasePath, $full);

?>
firebaseLib (library)

Code: Select all

<?php


class Firebase
{
    private $_baseURI;
    private $_timeout;
    private $_token;
    private $_ch;
    private $_fp;
    /**
     * Constructor
     *
     * @param String $baseURI Base URI
     *
     * @return void
     */
    function __construct($baseURI = '', $token = '')
    {
        if ($baseURI == '') {
            trigger_error('You must provide a baseURI variable.', E_USER_ERROR);
        }
        if (!extension_loaded('curl')) {
            trigger_error('Extension CURL is not loaded.', E_USER_ERROR);
        }
        $this->setBaseURI($baseURI);
        $this->setTimeOut(10);
        $this->setToken($token);
    }
    /**
     * Sets Token
     *
     * @param String $token Token
     *
     * @return void
     */
    public function setToken($token)
    {
        $this->_token = $token;
    }
    /**
     * Sets Base URI, ex: http://yourcompany.firebase.com/youruser
     *
     * @param String $baseURI Base URI
     *
     * @return void
     */
    public function setBaseURI($baseURI)
    {
        $baseURI .= (substr($baseURI, -1) == '/' ? '' : '/');
        $this->_baseURI = $baseURI;
    }
    /**
     * Returns with the normalized JSON absolute path
     *
     * @param String $path to data
     */
    private function _getJsonPath($path)
    {
        $url = $this->_baseURI;
        $path = ltrim($path, '/');
        $auth = ($this->_token == '') ? '' : '?auth=' . $this->_token;
        return $url . $path . '.json' . $auth;
    }
    /**
     * Sets REST call timeout in seconds
     *
     * @param Integer $seconds Seconds to timeout
     *
     * @return void
     */
    public function setTimeOut($seconds)
    {
        $this->_timeout = $seconds;
    }
    /**
     * Writing data into Firebase with a PUT request
     * HTTP 200: Ok
     *
     * @param String $path Path
     * @param Mixed  $data Data
     *
     * @return Array Response
     */
    public function set($path, $data)
    {
      return $this->_writeData($path, $data, 'PUT');
    }
    /**
     * Writing multiple datas into multiple Firebase paths with a PUT request via socks
     * $paths[$key] must be pair to $datas[$key]
     * !! SUPER FAST !! Do not use more than 200 elements ( depends of elements size, it's not well tested )
     *
     * @param Array $paths List of Paths
     * @param Array $data  List of Values
     *
     * @return Nothing, be careful
     */
    public function set_multi($paths,$datas)
    {
        if(count($paths) != count($datas))
            return 0;
        foreach ($paths as $key => $path) {
            $this->_socksPut($path,$datas[$key]);
        }
        $this->_closeSocks();
    }
    /**
     * Pushing data into Firebase with a POST request
     * HTTP 200: Ok
     *
     * @param String $path Path
     * @param Mixed  $data Data
     *
     * @return Array Response
     */
    public function push($path, $data)
    {
      return $this->_writeData($path, $data, 'POST');
    }
    /**
     * Updating data into Firebase with a PATH request
     * HTTP 200: Ok
     *
     * @param String $path Path
     * @param Mixed  $data Data
     *
     * @return Array Response
     */
    public function update($path, $data)
    {
      return $this->_writeData($path, $data, 'PATCH');
    }
    /**
     * Reading data from Firebase
     * HTTP 200: Ok
     *
     * @param String $path Path
     *
     * @return Array Response
     */
    public function get($path)
    {
        try {
            $ch = $this->_getCurlHandler($path, 'GET');
            $return = curl_exec($ch);
        } catch (Exception $e) {
            $return = null;
        }
        return $return;
    }
    /**
     * Deletes data from Firebase
     * HTTP 204: Ok
     *
     * @param type $path Path
     *
     * @return Array Response
     */
    public function delete($path)
    {
        try {
            $ch = $this->_getCurlHandler($path, 'DELETE');
            $return = curl_exec($ch);
        } catch (Exception $e) {
            $return = null;
        }
        return $return;
    }
    /**
     * Returns with Initialized CURL Handler
     *
     * @param String $mode Mode
     *
     * @return CURL Curl Handler
     */
    private function _getCurlHandler($path, $mode)
    {
        $url = $this->_getJsonPath($path);
        if (!$this->_ch) {
            $this->_ch = curl_init();
        }
        curl_setopt($this->_ch, CURLOPT_URL, $url);
        curl_setopt($this->_ch, CURLOPT_TIMEOUT, $this->_timeout);
        curl_setopt($this->_ch, CURLOPT_CONNECTTIMEOUT, $this->_timeout);
        curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->_ch, CURLOPT_CUSTOMREQUEST, $mode);
       
        return $this->_ch;
    }
    private function _writeData($path, $data, $method = 'PUT')
    {
        $jsonData = json_encode($data);
        $header = array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($jsonData)
        );
        try {
            $ch = $this->_getCurlHandler($path, $method);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            $return = curl_exec($ch);
        } catch (Exception $e) {
            $return = null;
        }
        return $return;
    }
    private function _socksPut($path,$data)
    {
        $jsonData = json_encode($data);
        $path = $this->_getJsonPath($path);
        $parts=parse_url($path);
        $sslUrl = "ssl://".$parts['host'];
        if($this->_fp)
            $fp = $this->_fp;
        else{
            $fp = fsockopen($sslUrl,443,$errNo, $errStr, 30);
            $this->_fp = $fp;
        }
        $out = "PUT ".$parts['path']."?auth=".$this->_token." HTTP/1.1\r\n";
        $out.= "Host: ".$parts['host']."\r\n";
        $out.= "Keep-Alive: 300\r\n"; 
        $out.= "Connection: keep-alive\r\n"; 
        $out.= "Content-Type: application/json\r\n";
        $out.= "Content-Length: ".strlen($jsonData)."\r\n";
        $out.= "Connection: Close\r\n\r\n";
        if (isset($jsonData)) $out.= $jsonData;
        fwrite($fp, $out);
    }
    private function _closeSocks()
    {
        fclose($this->_fp);
        $this->_fp=null;
    }
}
User avatar
hyper
php-forum GURU
php-forum GURU
Posts: 854
Joined: Mon Feb 22, 2016 5:52 pm

Tue Mar 12, 2019 8:30 am

What errors are you getting?
User avatar
xiao23
New php-forum User
New php-forum User
Posts: 11
Joined: Tue Mar 12, 2019 7:21 am

Tue Mar 12, 2019 5:05 pm

Good morning!

there's no error but it doesn't update all the device that requested in the web server
it only allow 1 device to update
I have 3 devices
I hope you can help me with something like curl_multi_init() or curl_multi_exec() in the Library I am using
or any solution? I am not familiar with it
User avatar
xiao23
New php-forum User
New php-forum User
Posts: 11
Joined: Tue Mar 12, 2019 7:21 am

Wed Mar 13, 2019 4:14 am

any help?
User avatar
hyper
php-forum GURU
php-forum GURU
Posts: 854
Joined: Mon Feb 22, 2016 5:52 pm

Wed Mar 13, 2019 8:33 am

Without any error messages, it is difficult to find what's wrong.

Have you checked the error log?
User avatar
xiao23
New php-forum User
New php-forum User
Posts: 11
Joined: Tue Mar 12, 2019 7:21 am

Wed Mar 13, 2019 8:42 am

that's the problem too

the code firebaLib and php code(upload.php) I put in the 000webhost


check my library (firebaseLib)
User avatar
xiao23
New php-forum User
New php-forum User
Posts: 11
Joined: Tue Mar 12, 2019 7:21 am

Fri Mar 15, 2019 8:25 pm

I need help guys

or any suggestion

the devices are connected but only 1 device at a time is updating

it doesn't update all simultaneously


I used http as my web server to send the data of arduino deviceS to firebase
User avatar
xiao23
New php-forum User
New php-forum User
Posts: 11
Joined: Tue Mar 12, 2019 7:21 am

Wed Jun 26, 2019 5:31 am

I got this working fine last April or March?
the only problem was that each device should have a Unique IP address so each will have an simultaneous request to a firebase
Post Reply