S
S
sm_book2016-02-11 01:03:11
PHP
sm_book, 2016-02-11 01:03:11

Dynamic content in php + cnc. How to implement?

I'm studying php and got stuck a day ago)
What I'm thinking: a site with dynamic content + cnc so that these links come back to normal,
I first want to do it just to make it work. Now either CNC or content loading is working. Together, this all throws an error in ajax.php

Warning: include(Z:\home\hiapi.ru\www\contacts) [function.include]: failed to open stream: Permission denied in Z:\home\hiapi.ru\www\ajax.php on line 5

Warning: include() [function.include]: Failed opening 'contacts' for inclusion (include_path='.;C:\php\pear') in Z:\home\hiapi.ru\www\ajax.php on line 5

There must be something wrong with this if(!empty($_POST['uri'])){
Please help )

This is index.html
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />			
    <script type="text/javascript" src="/js/jquery-1.9.0.min.js"></script>
    <script type="text/javascript" src="/js/script.js"></script>		
  </head>
  <body>
    
<!--Блок ссылок для переключения страниц-->	
<div id='control'>
<a href="about">О нас</a>
<a href="contacts">Контакты</a>
</div>		
    
<div id='data'>
<!--Блок для вывода динамического контента-->	
</div>	

</body>
</html>


this is .htaccess
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} (.*)
RewriteCond %{REQUEST_URI} /$ [NC]
RewriteRule ^(.*)(/)$ $1 [L,R=301]
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1


index.php
<?php

class Router {
    private $_route = array(); //Переменная хранит маршруты, и файлы, которые будут открываться при определеном маршруте

    /**
     * Метод для установки маршрута, и файла который будет открываться при заданом маршруте
     * @param <string> $dir - маршрут
     * @param <string> $file - адрес файла
     */
    public function setRoute($dir, $file) {
        $this->_route[trim($dir, '/')] = $file;
    }


    public function route() {
        if (!isset($_SERVER['PATH_INFO'])) { //Если открыта главная страница
            include_once 'index.html'; //Открываем файл главной страницы
        } elseif (isset($this->_route[trim($_SERVER['PATH_INFO'], '/')])) { //Если маршрут задан
            include_once $this->_route[trim($_SERVER['PATH_INFO'], '/')]; //Открываем файл, для которого установлен маршрут
        }
        else return false; //Если маршрут не задан
        
        return true;
    }
}
$ajax = true; 
if(!empty($_POST['uri'])){
  include $_POST['uri'];
}

$route = new Router;
$route->setRoute('about', "1.html"); //Устанавливаем маршрут , и файл который будет открываться при этом маршруте
$route->setRoute('tel', "2.html");
if (!$route->route()) { //Если маршрут не задан..
    echo 'Маршрут не задан';
}


ajax.php
<?php 
// Подгружает страницу указаную в $_POST['uri']

if(!empty($_POST['uri'])){
  include $_POST['uri'];
}


script.js
$(document).ready(function(){

  // получаем текущий uri, если uri не существует то присваиваем uri первой страницы 
  var thisUri = getThisUri()?getThisUri():'page1.php';
  
  //сразу задаем параметры для текущего состояния
  history.replaceState({uri:thisUri}, null, thisUri);
  
  // клик на ссылки переключения страниц
  $('#control a').click(function(){	 
  
    // получем путь к запрашиваемой странице
    var uri = $(this).attr('href');
    
    //создаем новую запись в истории только когда кликаем по ссылке
    history.pushState({uri:uri}, null, uri);
    
    // открываем страницу
    openPage(uri);	  
    return false;
  });
  
  // обработчик нажатий на кнопки браузера назад/вперед 
  $(window).bind('popstate', function(event) { 
      openPage(history.state.uri);	
  });

  /**
   * Загрузка запрашиваемых страниц с сервера
   */
  function openPage(uri){
  // динамическая загрузка контента
    $.ajax({
        type: "POST",
        url: "/ajax.php",
        data: {
      uri: uri
    },
        cache: false,        
        success: function(data){  
      // вывод в блок <div id="data">
          $('#data').html(data);
        }
      });
  }
  
  /**
   * Возвращает текущий URI страницы
   */
  function getThisUri(){
     var loc = event.location 
    || ( event.originalEvent && event.originalEvent.location )
    || document.location;		
      return loc.pathname.substr(1);
  }	  

  
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2016-02-11
@Stalker_RED

You should not connect like this any files that are specified in the request. An attacker can be imaginative in requests.
See how others do routing

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question