Почему php не работает в html
Перейти к содержимому

Почему php не работает в html

  • автор:

 

Почему php не работает в html

ЗЫ. Например это тож не пашет как надо:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

Цитата:

В чем может быть дело?

в том, что апач знает, что файлы с расширением .php нужно обрабатывать с помощью php интерпретатора.. а про .html он такого не знает

1) попробуйте написать в конфиг апача (httpd.conf)
AddType application/x-httpd-php .html
AddType application/x-httpd-php .htm

$link = mysql_connect($DBSERVER, $DBUSER, $DBPASS)
or die("Не могу подключиться" );
mysql_select_db($DB, $link) or die ('Не могу выбрать БД');
if(md5(crypt($_SESSION['user'],$_SESSION['password'])) != $_SESSION['SID']) <
if(!$_POST['do'])<

$q2 = @mysql_query("SELECT * FROM users WHERE nick='".$_SESSION['user']."' AND password='".$_SESSION['password']."' AND status=1");
if(@mysql_num_rows($q2)==1) <
$r2 = @mysql_fetch_array($q2);

Цитата:

хочу вставить его на главную в index(.html).. Каким образом это правильно сделать?

никак.. либо настраиваете сервер, чтобы html файлы обрабатывал как php, либо вставляете html код в php файл.

Цитата:

Но в самом php коде я не понимаю, поэтому и спрашиваю, как правильно вставить.

просто вставить где хочется и все.
html код в php файле, находящийся вне тегов <?php и ?> — не обабатывается и выдается напрямик в браузер

$link = mysql_connect($DBSERVER, $DBUSER, $DBPASS)
or die("Не могу подключиться" );
mysql_select_db($DB, $link) or die ('Не могу выбрать БД');

if(mysql_num_rows($q1)===1) <
$r=mysql_fetch_array($q1);
$_SESSION['user'] = $r['nick'];
$_SESSION['password'] = $r['password'];

$q2 = @mysql_query("SELECT * FROM users WHERE nick='".$_SESSION['user']."' AND password='".$_SESSION['password']."' AND status=1");
if(@mysql_num_rows($q2)==1) <
$r2 = @mysql_fetch_array($q2);

Выполнение php кода в html (ничего не помогает)

Подскажите плиз как заставить сайт на html обрабатывать php код, ни в какую не хочет.

Домен добавлен на сервер с поддержкой PHP как CGI

В .htaccess прописано следующее:

#AddDefaultCharset UTF-8
DirectorySlash Off

AddHandler php-cgi .html .htm .phtml .php

# important!
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond % ^site.ru
RewriteRule (.*) http://www.site.ru/$1 [R=301,L]

RewriteRule ^robots.txt$ — [L]
RewriteRule ^sitemap.xml$ — [L]

RewriteCond % !/_routing.php$
RewriteRule ^(.*)$ _routing\.php\?$1 [QSA,L]
</IfModule>

Ответ тех. поддержки хостинга, тоже не дал надежд(

Запись AddHandler php-cgi .html .htm .phtml .php верна.
Вставки php в html начинают работать только если отключить этот кусок кода в .htaccess :

RewriteEngine On
RewriteCond % ^site.ru
RewriteRule (.*) http://www.site.ru/$1 [R=301,L]

RewriteRule ^robots.txt$ — [L]
RewriteRule ^sitemap.xml$ — [L]

RewriteCond % !/_routing.php$
RewriteRule ^(.*)$ _routing.php?$1 [QSA,L]

Но если его отключить — сайт перестаёт корретно отображаться.
Копромиса, к сожелению найти не удалось.

  • Как повесить на отдельную страницу сайта 404 ошибку
  • Умрёт ли PHP в 2023 году? Нужно ли его учить?
  • Динамические страницы — как заставить поисковые системы их проиндексировать?

Вопрос: У меня сайт на чистом HTML, как мне вставить скрипт?

Ответ: В корневом файле .htaccess (если его нет, то нужно создать в корневой папке сайта) добавить строчку:

AddType application/x-httpd-php .php .htm .html

AddHandler application/x-httpd-php .php .htm .html .phtml

AddHandler x-httpd-php .php .htm .html .phtml

AddType application/x-httpd-php5 .php .htm .html

AddHandler application/x-httpd-php5 .php .htm .html .phtml

AddHandler x-httpd-php5 .php .htm .html .phtml

AddHandler cgi-script .html .htm

LEOnidUKG:
Вопрос: У меня сайт на чистом HTML, как мне вставить скрипт?

Ответ: В корневом файле .htaccess (если его нет, то нужно создать в корневой папке сайта) добавить строчку:

AddType application/x-httpd-php .php .htm .html

AddHandler application/x-httpd-php .php .htm .html .phtml

AddHandler x-httpd-php .php .htm .html .phtml

AddType application/x-httpd-php5 .php .htm .html

AddHandler application/x-httpd-php5 .php .htm .html .phtml

AddHandler x-httpd-php5 .php .htm .html .phtml

AddHandler cgi-script .html .htm

Спасибо, пробовал без результатно, сейчас еще раз попробую.

 

Увы но результат такой же, php не обрабатывается, а в большинстве случаев и вовсе сайт перестает работать и вместо открытия страницы предлагает скачать файл _routing.php я так понимаю в нем и проблема наверное кроется.

Вот его содержание:

//———mysql———//
$conf[‘mysql’][‘host’] = ‘localhost’;
$conf[‘mysql’][‘user’] = ‘root’;
$conf[‘mysql’][‘pass’] = ‘qwerty’;
$conf[‘mysql’][‘db’] = ‘lookup’;
$conf[‘mysql’][‘table’] = ‘lookup’;

if (!$p || $p == «/») $p = ‘./’; // index page
if (preg_match(‘#^(\/|\.\./)#’, $p)||preg_match(‘#\./\.#’,$p)) die_not_found();

$get_node = «get_node_».$conf[‘active’];
$node = $get_node($p);

if (!$node) die_not_found();

if (!file_exists($node[‘realname’])) die_not_found();

// if (preg_match(‘/.*\.php$/i’, $node[‘realname’])) include_once($node[‘realname’]);
// else echo file_get_contents($node[‘realname’]);

$html = file_get_contents($node[‘realname’]);
parse_asserts($html);
echo $html;

function get_node_plain($uri) <
global $conf;

$routes = file_get_contents($conf[‘plain’][‘db’]);
$regex = quotez($uri).’\s*=>\s*(.*?)\s*=>\s*(.*)’;
$regex = str_replace(‘#’, ‘\#’, $regex);
//die($regex);
$row = array();

if (preg_match(«#$regex#», $routes, $matches)) <

$row[‘realname’] = trim($matches[1]);
$row[‘ctype’] = trim($matches[2]);

function get_node_sqlite3($uri) <
global $conf;

if (!_enabled(‘sqlite3’)) die();
if (!file_exists($conf[‘sqlite3’][‘db’])) die(«SQLITE ERROR: NO ROUTING DB»);

$db = new SQLite3($conf[‘sqlite3’][‘db’]);
if (!$db) die(«SQLITE ERROR: DB OPEN FAILED»);

$stmt = $db->prepare(«SELECT * FROM `».$conf[‘sqlite3’][‘table’].»` WHERE `uri` = :uri LIMIT 0,1″);
$stmt->bindValue(‘:uri’, $uri);
$res = $stmt->execute();
if ($row = $res->fetchArray(SQLITE3_ASSOC)) <
return $row;
> else <
return false;
>

function get_node_mysql($uri) <
global $conf;

$db = mysql_connect($conf[‘mysql’][‘host’], $conf[‘mysql’][‘user’], $conf[‘mysql’][‘pass’]) or die(«db open error: «.mysql_error());
mysql_select_db($conf[‘mysql’][‘db’]) or die(«cannot select db: «.mysql_error());
mysql_query(«SET NAMES utf8»);

$uri = mysql_real_escape_string($uri);
$query = «SELECT * FROM `».$conf[‘mysql’][‘table’].»` WHERE `uri` = ‘$uri’ LIMIT 0,1″;
$res = mysql_query($query) or die(mysql_error());
if ($row = mysql_fetch_assoc($res)) <
return $row;
> else <
return false;
>

function get_uri_heuristic() <
global $conf;
//$p = $_SERVER[‘QUERY_STRING’];
$z = $_SERVER[‘REQUEST_URI’];

$z = preg_replace(‘/^’.quotez($conf[‘site_uri’]).’/’, », $z, 1); // только 1 замена
if ($z == «index.html») $z = «»; // на некоторых серваках такой сброс нужен

function die_not_found() <
global $p, $conf;
if ($p != ‘./’ && $p != ‘/’ && $p != ‘index.html’) < // redirect unless index page
header(«Location: $conf[site_uri]»);
die();
> else <
die(«NOT FOUND»);
>

function _enabled($opt) <
switch($opt) <
case ‘sqlite3’:

if (!class_exists(‘SQLite3’)) <
print nl2br(‘SQLITE_3 NOT ENABLED

<b>sudo apt-get install php5-sqlite</b>

and restart Apache’);
return 0;
> else <
return 1;
>

function get_site_dir() <
/*
$p = $_SERVER[‘QUERY_STRING’];
$z = $_SERVER[‘REQUEST_URI’];
if ($p == «index.html») $p = «»; // на некоторых серваках такой сброс нужен
*/
$script_name = «_routing.php»;
$s = $_SERVER[‘SCRIPT_FILENAME’];
if (preg_match(‘#.*/(\S+)#’, $s, $m)) $script_name = $m[1];
$r = $_SERVER[‘DOCUMENT_ROOT’];

$ret = preg_replace(‘/^’.quotez($r).’/’, », $s);
$ret = preg_replace(‘/’.quotez($script_name).’$/’, », $ret);
if (!$ret) $ret=»/»;
return $ret;
>

foreach (glob(«$_dir/*.inc.php») as $filename) <
include_once($filename);
>

foreach($assert as $mask => $val) <
foreach(glob(«$_dir/*$mask») as $fname) <
if (file_exists($fname)) <
ob_start();
include_once($fname);
$assert[$mask] .= ob_get_clean();
>
>
>

PHP script not working in HTML file

I’m new to PHP. I installed XAMPP and have Apache running. I created helloworld.php in XAMPP’s htdocs and got PHP to display in my browser. My question is, why does my PHP script in my HTML file not display in my browser? Ive never installed PHP on its own. Should I also install it? Would it conflict with XAMPP. My code is below. Any assistance will be appreciated. Thanks in advance:

Domenik Reitzner's user avatar

6 Answers 6

I assume you are trying to use php inside .html file? Try adding .htaccess file or changing apache config with the following line:

XAMPP already includes PHP, but unless you end the script name with .php it is unlikely to be processed by the PHP engine.

Stop the apache service, then add one change in c:\xampp\apache\conf\httpd.conf in the section by adding.

This looks like a big fat ‘feature’ in the current xampp distribution for win 32-bit.

Josh Crozier's user avatar

You should add mime type at http conf for instance in apache at httpd.conf entry

The php module for apache registers itself as handler for the mime type application/x-httpd-php . And the configuration file apache\conf\extra\httpd-xampp.conf contains the lines

which tells the apache that all files having .php as name extension are to be processes by the handler for application/x-httpd-php.
If you (really) want to have your .html files handled by the php module as well you have to add something similar for .html extensions. (there are other methods to tell the apache which extension maps to which mime type/handler. But FilesMatch/SetHandler is fine.)
If you want to enable this «feature» for only one directory you can use an .htaccess file to change the configuration for that directory (and its subdirectories).

Too much overkill. All these suggestions lead me down the wrong path for like 5 hours. JK, but I did read a lot of google search items all giving wrong answers and each suggestion was just adding more wrong answers.

The answer is in fact so simple you would want to bang your head: Simply change the file extension from «.html» to «.php». Remember that you can build a webpage entirely out of PHP and all JavaScript and stuff built off JavaScript like, JQuery, bootstrap, etc will work.

Here is a simple example of proof:

Notice that I am using your standard html, even though it doesn’t show my HTML tags(trust me it’s there), web page stuff and have php code inserted inside. Of course the result is 15 and the html element h4 renders correctly too. Change the extension back to «html» and you will get only the h4 element and you will find that your php code has been commented out using multi-comment for html.

Почему не работает php код в html?

У меня есть форум, на движке phpbb. На форуме висит баннер-картинка, описаная в файле /www/myforum.com/styles/mytheme/template/overall_header.html
Я набросал php код, который рандомно выбирает картинку из базы. Этот код в файлах с расширением php работает отлично, но в файлах html как вставка <?php><?> похоже просто игнорируется.
Да что там, даже <?php>echo 123;<?> в test.html не выводится.

Подскажите, как выйти из этой ситуации и заставить работать код?
Спасибо.

UPD: Все спасибо, сам разобрался. Решилось включением галочки в админке и использованием тега

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *