Forum: NGINX problem with php script

2974d09ac2541e892966b762aad84943?d=identicon&s=25 shahin-slt (Guest)
on 2014-05-18 12:23
(Received via mailing list)
hi
i' using a script on apache and now i want to use it on nginx, but it
does
not work. hears my codes and config.(i use windows)

please help me. sorry for my long topic

nginx.conf:


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local]
"$request"
'
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       81;
        server_name  localhost;
         autoindex on;
        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;




         }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on
127.0.0.1:9000
        #
        location ~ \.php$ {


            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            include        fastcgi_params;
            fastcgi_param  SCRIPT_FILENAME
E:/nginx/html/$fastcgi_script_name;

        }



        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based
configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}




    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}



download.php code:

<?php

  require_once('config.php');

  require_once('http.class.php');
  $av_http = new av_httpdownload;

  function av_remote_auth_check( $data ){
    global $av_config;
    $request = '';
    $request .= 'action=av_user_auth';
    $request .= '&user_name='.$data[0];
    $request .= '&user_password='.$data[1];
    $request .= '&confirm_key='.$av_config['key'];
    $response = '';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $av_config['site_url'] );
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    $response = curl_exec($ch);
    curl_close($ch);
    if( $response == 'true' )
      return true;
    else
      return false;
  }

  if( empty( $_SERVER['PATH_INFO'] ) )
    return;



  $fileData = explode( '/' , ltrim( $_SERVER['PATH_INFO'] , '/' ) );

  $filePath = $av_config['files_path'] . $fileData[0];

  $isFree = ( isset( $fileData[1] ) && $fileData[1] == 'free' ) ? true :
false;

  if( file_exists( $filePath ) ) {
    if( ! $isFree  ){
      $LoginSuccessful = false;
      if ( isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW'])
){
        $Username = $_SERVER['PHP_AUTH_USER'];
        $Password = $_SERVER['PHP_AUTH_PW'];
        if ( av_remote_auth_check( array($Username,$Password) ) ){
          $LoginSuccessful = true;
        }
      }
      if ( ! $LoginSuccessful ){
        header('WWW-Authenticate: Basic realm="Enter User name and
Password for
VIP Download."');
        header('HTTP/1.0 401 Unauthorized');
        print "Login failed!\n";
      }
      else {
        $av_http->set_byfile( $filePath );
        $av_http->download( $fileData[0] );
      }
    } else{
      $av_http->set_byfile( $filePath );
      $av_http->use_resume = false;
      $av_http->speed = is_numeric($av_config['free_dl_speed']) ?
intval($av_config['free_dl_speed']) : 100;
      $av_http->download( $fileData[0] );
    }
  }

  die();






config.php code:

<?php

  $av_config = array();

  $av_config['key'] = 'something';

  $av_config['free_dl_speed'] = 30; //

  $av_config['site_url'] = 'example.com'; your site that users have been
registerd.

  $av_config['files_folder'] = 'hgfGVFCDuytrfn'; folder that you keep
your
files

  $av_config['files_path'] = dirname(__FILE__) . '/' .
$av_config['files_folder'] . '/'; //



http.class.php codes:

<?php
class av_httpdownload{

  var $data = null;
  var $data_len = 0;
  var $data_mod = 0;
  var $data_type = 0;
  var $data_section = 0; //section download
  /**
   * @var ObjectHandler
   **/
  var $handler = array('auth' => null);
  var $use_resume = true;
  var $use_autoexit = false;
  var $use_auth = false;
  var $filename = null;
  var $mime = null;
  var $bufsize = 2048;
  var $seek_start = 0;
  var $seek_end = -1;

  /**
   * Total bandwidth has been used for this download
   * @var int
   */
  var $bandwidth = 0;
  /**
   * Speed limit
   * @var float
   */
  var $speed = 0;

  /*-------------------
  | Download Function |
  -------------------*/
  /**
   * Check authentication and get seek position
   * @return bool
   **/
  function initialize() {
    global $HTTP_SERVER_VARS;

    if ($this->use_auth) //use authentication
    {
      if (!$this->_auth()) //no authentication
      {
        header('WWW-Authenticate: Basic realm="Please enter your
username and
password"');
        header('HTTP/1.0 401 Unauthorized');
        header('status: 401 Unauthorized');
        if ($this->use_autoexit) exit();
        return false;
      }
    }
    if ($this->mime == null) $this->mime = "application/octet-stream";
//default mime

    if (isset($_SERVER['HTTP_RANGE']) ||
isset($HTTP_SERVER_VARS['HTTP_RANGE']))
    {

      if (isset($HTTP_SERVER_VARS['HTTP_RANGE'])) $seek_range =
substr($HTTP_SERVER_VARS['HTTP_RANGE'] , strlen('bytes='));
      else $seek_range = substr($_SERVER['HTTP_RANGE'] ,
strlen('bytes='));

      $range = explode('-',$seek_range);

      if ($range[0] > 0)
      {
        $this->seek_start = intval($range[0]);
      }

      if ($range[1] > 0) $this->seek_end = intval($range[1]);
      else $this->seek_end = -1;

      if (!$this->use_resume)
      {
        $this->seek_start = 0;

        //header("HTTP/1.0 404 Bad Request");
        //header("Status: 400 Bad Request");

        //exit;

        //return false;
      }
      else
      {
        $this->data_section = 1;
      }

    }
    else
    {
      $this->seek_start = 0;
      $this->seek_end = -1;
    }

    return true;
  }
  /**
   * Send download information header
   **/
  function header($size,$seek_start=null,$seek_end=null) {
    header('Content-type: ' . $this->mime);
    header('Content-Disposition: attachment; filename="' .
$this->filename.
'"');
    header('Last-Modified: ' . date('D, d M Y H:i:s \G\M\T' ,
$this->data_mod));

    if ($this->data_section && $this->use_resume){
      header("HTTP/1.0 206 Partial Content");
      header("Status: 206 Partial Content");
      header('Accept-Ranges: bytes');
      header("Content-Range: bytes $seek_start-$seek_end/$size");
      header("Content-Length: " . ($seek_end - $seek_start + 1));
    } else {
      header("Content-Length: $size");
    }
  }

  function download_ex($size){
    if (!$this->initialize()) return false;
    ignore_user_abort(true);
    //Use seek end here
    if ($this->seek_start > ($size - 1)) $this->seek_start = 0;
    if ($this->seek_end <= 0) $this->seek_end = $size - 1;
    $this->header($size,$seek,$this->seek_end);
    $this->data_mod = time();
    return true;
  }

  /**
   * Start download
   * @return bool
   **/
  function download( $file_name = null ) {
    if (!$this->initialize()) return false;

    $seek = $this->seek_start;
    $speed = $this->speed;
    $bufsize = $this->bufsize;
    $packet = 1;

    //do some clean up
    @ob_end_clean();
    $old_status = ignore_user_abort(true);
    @set_time_limit(0);
    $this->bandwidth = 0;

    $size = $this->data_len;

    if ($this->data_type == 0){

      $size = filesize($this->data);
      if ($seek > ($size - 1)) $seek = 0;

      if ( $file_name == null )
        $this->filename = basename( $this->data );
      else
        $this->filename = $file_name;

      $res = fopen($this->data,'rb');
      if ($seek) fseek($res , $seek);
      if ($this->seek_end < $seek) $this->seek_end = $size - 1;

      $this->header($size,$seek,$this->seek_end); //always use the last
seek
      $size = $this->seek_end - $seek + 1;

      while (!(connection_aborted() || connection_status() == 1) &&
$size > 0)
      {
        if ($size < $bufsize)
        {
          echo fread($res , $size);
          $this->bandwidth += $size;
        }
        else
        {
          echo fread($res , $bufsize);
          $this->bandwidth += $bufsize;
        }

        $size -= $bufsize;
        flush();

        if ($speed > 0 && ($this->bandwidth > $speed*$packet*1024))
        {
          sleep(1);
          $packet++;
        }
      }
      fclose($res);

    }

    elseif ($this->data_type == 1) //download from a string
    {
      if ($seek > ($size - 1)) $seek = 0;
      if ($this->seek_end < $seek) $this->seek_end = $this->data_len -
1;
      $this->data = substr($this->data , $seek , $this->seek_end - $seek
+ 1);
      //if ($this->filename == null) $this->filename = time();
      $size = strlen($this->data);
      $this->header($this->data_len,$seek,$this->seek_end);
      while (!connection_aborted() && $size > 0) {
        if ($size < $bufsize)
        {
          $this->bandwidth += $size;
        }
        else
        {
          $this->bandwidth += $bufsize;
        }

        echo substr($this->data , 0 , $bufsize);
        $this->data = substr($this->data , $bufsize);

        $size -= $bufsize;
        flush();

        if ($speed > 0 && ($this->bandwidth > $speed*$packet*1024))
        {
          sleep(1);
          $packet++;
        }
      }
    } else if ($this->data_type == 2) {
      //just send a redirect header
      header('location: ' . $this->data);
    }

    if ($this->use_autoexit) exit();

    //restore old status
    ignore_user_abort($old_status);
    @set_time_limit(ini_get("max_execution_time"));

    return true;
  }

  function set_byfile($dir) {
    if (is_readable($dir) && is_file($dir)) {
      $this->data_len = 0;
      $this->data = $dir;
      $this->data_type = 0;
      $this->data_mod = filemtime($dir);
      return true;
    } else return false;
  }

  function set_bydata($data) {
    if ($data == '') return false;
    $this->data = $data;
    $this->data_len = strlen($data);
    $this->data_type = 1;
    $this->data_mod = time();
    return true;
  }

  function set_byurl($data) {
    $this->data = $data;
    $this->data_len = 0;
    $this->data_type = 2;
    return true;
  }

  function set_lastmodtime($time) {
    $time = intval($time);
    if ($time <= 0) $time = time();
    $this->data_mod = $time;
  }

  /**
   * Check authentication
   * @return bool
   **/
  function _auth() {
    if (!isset($_SERVER['PHP_AUTH_USER'])) return false;
    if (isset($this->handler['auth']) &&
function_exists($this->handler['auth']))
    {
      return $this->handler['auth']('auth' ,
$_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']);
    }
    else return true; //you must use a handler
  }

}

?>

Posted at Nginx Forum:
http://forum.nginx.org/read.php?2,250179,250179#msg-250179
F28f13d5607639b47a8ce7cf9b71a3cf?d=identicon&s=25 Nuno Magalhães (Guest)
on 2014-05-18 16:54
(Received via mailing list)
Hi,

Maybe you should read this first:
http://catb.org/~esr/faqs/smart-questions.html

This is an nginx forum, not a PHP forum. If you're running copy/pasted
code and don't know why if fails, maybe it shouldn't be in a live
server? You could at the very least remove all the comments and,
perhaps, say why it "does not work". Have you checked the logs (the
ones you commented out)? How about an nginx version? Using pastebin?

Your location / seems odd and you should consider using try_files
(documented in the nginx wiki) instead.
You set all indexes there as .htm(l) and then define the PHP pass as
index.php - i'm not sure if it matters but it's odd and you don't seem
to have any index.html in your mail dump. Nor do i know how your
SCRIPT_FILENAME reacts to an E:/.

Running quickly through your PHP you seem to use HTTP Basic Auth -
without configuring it in nginx. Also documented.

Cheers,
Nuno
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.