So I just started making a new website, or rather modifying an old one. All the code is the same, the only difference is I changed some text here and there. The old website worked perfectly, so this one should as well, so I'm not sure why this is happening, but only the main page can be found using the URLs that I wish to be used. Try going to, for example, the projects page, and not only is the file not found, but my custom not found page won't even be shown. First I'll show some examples then I will show some code.
Main page that works: teivodov.com
Projects page that worked on old site, but not on this one: teivodov.com/projects
Projects page that works, but ugly url form https://teivodov.com?page=projects
Not found page working only if ?page= used: https://teivodov.com?page=blahblah
Here is my htaccess file:
//deny access to this file
<Files ~ ".htaccess">
deny from all
</Files>
//start RewriteEngine
RewriteEngine On
//if the called file is NOT a directory, file or link, we call index.php?page=
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]
//disable file listing
Options -Indexes
//set error page 403 (no permission) and 404 (page not found) to our notfound page
ErrorDocument 403 /notfound
ErrorDocument 404 /notfound
order deny,allow
(# replaced with //)
My index.php:
<?php
function dump_error_to_file($errno, $errstr) {
file_put_contents('/errors.log', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler('dump_error_to_file');
//load needed settings, constants, page array and functions
include 'variables.php';
include 'constants.php';
include 'functions.php';
//setting timezone to America/Chicago, needed by some functions
date_default_timezone_set('America/Chicago');
//gets changed to the return of the include file
$ret = 1;
/*
* The include file has to contain the following values:
* Array('filename' => string, -- Filename for template
* 'data' => Array()) -- Array with data for the template
* - At an exception
* string -- Errormessage.
*/
//if no page was called, include the main page
if (!isset($_GET['page'])) {
$ret = include 'includes/' . $files['main'];
} else {
if (isset($_GET['page'])) {
$page = trim($_GET['page']);
} else {
$page = 'main';
}
if (isset($files[$page])) {
//if the file exists include it, else print error message
if (file_exists('includes/' . $files[$page])) {
$ret = include 'includes/' . $files[$page];
} else {
$ret = "Include-File was not found: 'includes/" . $files[$page] . "'";
}
} else {
$ret = include 'includes/' . $files['notfound'];
}
}
//include header template
include 'templates/header.html';
//if the include returns an array, it contains the templatestring and the data array, try to include the template
if (is_array($ret) && isset($ret['filename'], $ret['data']) && is_string($ret['filename']) && is_array($ret['data'])) {
//if the template exists include it, else print error message
if (file_exists($file = 'templates/' . $ret['filename'])) {
$data = $ret['data'];
include $file;
} else {
$data['msg'] = 'Template "' . $file . '" was NOT found.';
include 'templates/error.html';
}
//if the include file returns a string, it returned an exception. So we print it
} else if (is_string($ret)) {
// Exception
$data['msg'] = $ret;
include 'templates/error.html';
//the defualt value of $ret didnt change, so the include didnt return anything. Print error message
} else if (1 === $ret) {
//No return array
$data['msg'] = 'No return in the template!';
include 'templates/error.html';
} else {
//include file has a complete other return like a boolean or something, print error
//everything left
$data['msg'] = 'Include file has an invalid return.';
include 'templates/error.html';
}
//include footer template
include 'templates/footer.html';
Variables.php:
<?php
$files = array();
$files['main'] = 'main.php';
$files['projects'] = 'projects.php';
$files['projects/jda-extended'] = 'projects/jda-extended.php';
$files['contact'] = 'contact.php';
$files['about'] = 'about.php';
$files['notfound'] = 'notfound.php';
An example include file, projects.php:
<?php
$a = array();
$a['filename'] = 'projects.html';
$a['data'] = array();
return $a;
Example template file, projects.html:
<div class="fluid">
<p>
This website is still under construction.
<br><br>
<strong>JDA Extended</strong> - Extension to the JDA API. Allows for quick and easy discord bot development.
</p>
</div>
I believe that should be all the code someone might ask for, but feel free to ask for more if need be. The only difference between my last site and this one, is that the last site was hosted on shared web hosting. This one is hosted on my vps using apache2. It really confuses me as the site is able to find for example includes/main.php and templates/main.html, but not any other files in those folders. The only thing I can think of is something went wrong in the htaccess file as ?page=projects works but /projects does not, but I can't see anything wrong with it?
After playing around, I realized it was an issue with Apache2. By default in /etc/apache2/apache2.conf AllowOverrides is set to None when I needed it to be All. I had done all my testing of the website in windows, which I did not need to bother changing that.
Related
I have a sitename.net and in a root directory i have .htaccess and index.php
.htaccess is:
FallbackResource /index.php
so basically as it's empty site (no sub directories, no files etc...) I will get a fallback to index.php which contains this:
$path = ltrim($_SERVER['REQUEST_URI'], '/'); // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
echo "Domain is: $domain <br>";
if(empty($elements[0])) { // No path elements means home
echo "ShowHomepage()";
}
else switch(array_shift($elements)) { // Pop off first item and switch
case 'tests':
echo "First is test";
case 'sample':
echo "First is sample";
default:
header('HTTP/1.1 404 Not Found');
Show404Error();
}
my problem is that when visitor enters: https://username.sitename.net/tests/test1
I get error as subdomain doesn't exist...
When I go to "https://sitename.net/tests/test1" i get what I want but I need username as a variable as well.
Should I first do rewrite in .htaccess so it translate https://username.sitename.net/tests/test1 as https://sitename.net/username/tests/test1 and than redo index.php so it pickup a first array element as username or there is another option ?
Can somebody help me out ?
------------- EDIT ----------------
I've ended up pointing A record *.sitename.net to server IP
I've changed .htaccess so it's:
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^(.*)\.sitename\.net
RewriteRule ^(.*)$ subdomains/%1/$1 [L,NC,QSA]
FallbackResource /index.php
...and still getting 404 error... still can't get:
https://username.sitename.net/tests/test1 to act like https://sitename.net/username/tests/test1 so index.php will do it stuff...
I think wildcard DNS records is what you're looking for.
https://en.wikipedia.org/wiki/Wildcard_DNS_record
All subdomains will then redirect to your DNS, which you can redirect to your server.
EDIT:
Once the subdomains are up and running, you can use
.htaccess rewrite subdomain to directory
to fix the htaccess.
This work with php redirect too:
$url = "https://gbr8295.sitename.net"; //$_SERVER['HTTP_HOST']
if (substr($_SERVER['HTTP_HOST'], 0, 16) != 'https://sitename') { // You need edit 16 to a correct number for your domain
$username = substr($url, 8, ((strpos($url, '.') - 8)));
$new_url = "https://sitename.net/".$username."/";
echo $url."<br>"; // Output: https://gbr8295.sitename.net
echo $new_url; // Output: https://sitename.net/gbr8295/
header("Location: $new_url");
exit;
} else {
echo 'ok';
}
I have a code I'm trying to make work. Excuse my ignorance, I'm trying to learn but I can't find anything that specifically helps me.
What I want to do is:
On my index, display show_news.php
When index.php?page=blank is used, display the contents of blank.php
and if the chosen page doesn't exist I want to display a custom 404 page. Say if blank2.php was used and doesn't exist it includes 404.php
The 404 page is what I'm struggling with.
<?php
$number = 4;
if(!$_GET[page]){
include "show_news.php";
} elseif ($_GET[page]) {
include $_GET[page].".php";
} else {
include "404.php";
}
?>
try to use file_exists() function
http://php.net/manual/ru/function.file-exists.php
<?php
$number = 4;
define('ROOTPATH', __DIR__);
$project_path = ROOTPATH . "/path/to/page/files/";
$page = $_GET["page"];
$is_file_existing = $file_exists($project_path . $page . ".php");
if(!$page){
include "show_news.php";
} elseif ($is_file_existing) {
include $page . ".php";
} else {
include "404.php";
}
?>
I didn't quite get your question.
But here's how I would do it:
if (isset($_GET['page']))
include_once(dirname(__FILE__) . '/' . $_GET['page'] . '.php');
else
include_once(dirname(__FILE__) . '/show_news.php');
Then in your .htaccess file:
RewriteEngine On
RewriteBase /
ErrorDocument 404 /404.php
Edit:
Make use of mysqli_real_escape_string before passing it in to $_GET.
I have 1000 images in my website (running in codeingiter), which are named as
My_image_1.png, My_image_2.png ........ My_image_1000.png
and available in this url http://example.com/files/My_image_1.png
But i want the url is http://example.com/images?cid=1.png = My_image_1.png
How can i do this in php?
This is what i'm trying
if ( !function_exists('get_img_by_cid')) {
function get_img_by_cid() {
if ( isset($_GET['cid']) ) {
$cid = $_GET['cid'];
return '/path_to_image/My_image_'.$cid.'.png';
} else {
return 'Please specify compound id';
}
}
}
This function return the original path, but i need url like the example below.
In address bar or img tag wherever i use
Here is an example
https://pubchem.ncbi.nlm.nih.gov/image/imgsrv.fcgi?cid=2244
Any help or tutorial will be greatly appriciated :)
You can achieve it by following code.
Your URL = http://example.com/images.php?cid=1.png
write below code to images.php file
<img src="<?php echo "My_image_".$_GET['cid'];?>">
Above line will display image with named My_image_1.png
Hope this will helps you
Thanks & Regards
You need to write .htaccess rule :
RewriteCond %{QUERY_STRING} cid=([0-9]+) [NC]
RewriteRule ^images$ /files/My_image_%1.png [L]
Edit :
nginx configuration
location / {
if ($query_string ~* "cid=([0-9]+)"){
rewrite ^/images$ /files/My_image_%1.png break;
}
}
Building on the code provided by #Shishil Patel, a friend and I wrote this:
<?php
$file = "My_image_".$_GET['cid'];
$size = getimagesize($file);
$fp = fopen($file, "rb");
if ($size && $fp) {
header("Content-type: {$size['mime']}");
fpassthru($fp);
exit;
} else {
header("HTTP/1.0 404 Not Found");
}
readfile("{$file}");
?>
With this, https://example.com/?cid=1.png will display your image without any issues... as long as it's stored to index.php, otherwise your url is similar to https://example.com/index.php?cid=1.png, but with the proper php file name in the url.
EDIT:
On an additional note, $file should contain the folder path to your file, for example
$file = "/path_to_image/My_image_".$_GET['cid'];
Let me know if this was of use, your question was the same issue we had!
I made a PHP framework with my own templating system, which works as I want it to in the frontend. The templating system uses the ?url=($page) part of the of the URL to figure out what page the user requests, then displays the content of the file with the name ($page). I then use htaccess to "pretty up" the URL.
However, I'm now expanding the framework to identify if $_GET['url'] contains backend, and if it does, see if it has a trailing slash with another string. For example, if the value of $_GET['url'] is backend/manage-gallery, I want it to return the page manage-gallery from within the the backend folder. Here is the code that I have now. Currently, I got it to retrieve a page statically (index.php) if the value of $_GET['url'] is backend.
public function addTpl() {
global $zip;
if(!isset($_GET['url']) || empty($_GET['url'])) {
$_GET['url'] = 'index';
}
$front = '_zip/_templates/_front/'. $zip['Template']['Front'];
$back = '_zip/_templates/_back/'. $zip['Template']['Back'];
if(strpos($_GET['url'], 'backend') !== false) {
if(file_exists($back . '/')) {
if(file_exists($back . '/index.php')) {
ob_start();
include($back . '/index.php');
$this->tpl .= ob_get_contents();
ob_end_clean();
} else {
if($zip['Template']['Front'] == 'Refresh/multi-page') {
ob_start();
include($back . '/404.php');
$this->tpl .= ob_get_contents();
ob_end_clean();
} else {
die(zipError('File Not Found', 'The file <b>' . secure($_GET['url']) . '</b> could not be found. Please re-check the URL; If you were directed here using a link, please report that link <b><a href="mailto:IntactDev#gmail.com">here<a/>.</b>'));
}
}
} else {
die(zipError('Template Not Found', 'The template <b>' . $zip['Template']['Front'] . '</b> could not be found. Please check your configuration file for a mistake.'));
}
} else {
if(file_exists($front. '/')) {
if(file_exists($front. '/' . secure($_GET['url']) . '.php')) {
ob_start();
include($front. '/' . secure($_GET['url']) . '.php');
$this->tpl .= ob_get_contents();
ob_end_clean();
} else {
if($zip['Template']['Front'] == 'Refresh/multi-page') {
ob_start();
include($front. '/404.php');
$this->tpl .= ob_get_contents();
ob_end_clean();
} else {
die(zipError('File Not Found', 'The file <b>' . secure($_GET['url']) . '</b> could not be found. Please re-check the URL; If you were directed here using a link, please report that link <b><a href="mailto:IntactDev#gmail.com">here<a/>.</b>'));
}
}
} else {
die(zipError('Template Not Found', 'The template <b>' . $zip['Template']['Front'] . '</b> could not be found. Please check your configuration file for a mistake.'));
}
}
}
How can I make my code check if the get value contains backend, AND see if it has a traling slash with a string after it? Here is my htaccess
RewriteEngine On
RewriteRule ^(|/)$ index.php?url=$1
RewriteRule ^([a-zA-Z0-9_-]+)(|/)$ index.php?url=$1
Since the slash will always be right after the backend string, I would change the strpos by adding the slash:
if(strpos($_GET['url'], 'backend/') !== false) {
Also, if backend occurs in the string, it will always be at the beginning of the string, so I would look for it at position zero:
if(strpos($_GET['url'], 'backend/') == 0) {
Then, I would use && and add another condition to that if statement to check to see if the string is longer than 7 characters. In other words, if backend/ is at the beginning, and the string is longer that 7 characters, there are more characters after backend/.
if(strpos($_GET['url'], 'backend/') == 0 && strlen($_GET['url']) > 7) {
EDIT: There is a problem in your .htaccess file. Change $1 to $2.
First of all, I apologize. I looked up a lot of questions but so far nothing has worked. I don't know why.
I have a site www.mysite.it
and one URL is
www.mysite.it/home.php?pagina=home
I want to see
www.mysite.it/home or www.mysite.it/home.php is the same
I added this in .htaccess:
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)/$ home.php?pagina=$1
and I have this expression in my php:
<?php
$get= #$_GET ['pagina'];
$pagina = (isset($_GET['pagina']) ? $_GET['pagina'] : 'home') . '.php';
if(file_exists($get)){
include($pagina);
} else {
include("404.php");
}
switch ($get){
default :
include ('contenuto/home.php');
break;
case "tournament":
include ('torneo/torneo.php');
break;
case "arena":
include ('contenuto/modalita/arena.php');
break;
etc
Your RewriteRule only matches URLs that end with "/". You'll need to change your rewrite rules. Consider using an R directive as well as L.
RewriteRule ^(.*)/$ home.php?pagina=$1 [L]
RewriteRule ^(.*)$ home.php?pagina=$1 [L]
Then change your logic. The 404 if block should go below case. It seems like you're figuring out what page you're going to at multiple places. I tried to sort that out below. Also, use the debug statements to determine if the variables are getting set how you want them. Also remember that pagina must match an actual file on the disk, including directory. For example, if you ask for torneo, it won't be found. tournament only works because it has a special listing in the switch block.
$get = #$_GET['pagina'];
if (!isset($_GET['pagina'])) {
$get = 'home';
$pagina = 'contenuto/home.php';
} else {
$pagina = $get . '.php';
}
// debug
echo $get . '//' . $pagina
switch ($get) {
default :
$pagina = 'contenuto/home.php';
break;
case "tournament":
$pagina = 'torneo/torneo.php';
break;
}
if (file_exists($pagina)) {
include($pagina);
} else {
include("404.php");
}
Here you check for the existence of one file and you include another :
if(file_exists($get)){
include($pagina);
This cannot work. It must be :
if(file_exists($pagina)){
include($pagina);