I am relatively new to php. There is a very basic thing that has been troubling me. I understand that php is used to make web sites dynamic. I also understand that php is one of the many server side scripting languages that can be used to make dynamic web sites.
However, what I do not understand is that when do i need to use an index.php page. Say for example if i have just a simple login page on my index page, it could very well just be a simple html page as well. Right? Then why would i want to make it index.php instead of index.html?
An example of a sample situation would be great.
You will have to choose the PHP extension (.php) when you want php code to be executed in the file. PHP code is code between the opening <?php or <? and the closing ?> tags.
When no PHP code should be executed you can use the .html extension.
Usually when using the .php extension you are telling the web server, that it should use a php interpreter to process the file before it will be delivered to the browser. The php interpreter will then replace all content between the <?php and ?> by the output of the PHP code. Just as if you wrote it manually. The processed file will then be delivered to the browser.
However, using the .php extension to tell the web server to process php code is configurable. If you want you can use other file extensions too.
There is another thing that should be pointed out. When you only type the url path (without a filename) like :
http://www.myserver.com/
there is an order of extensions (filenames) which the webserver (apache) searches for an index document. For example an apache config may contain a section like:
<IfModule mod_dir.c>
DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
</IfModule>
Meaning that the index document is searched in the order above. This means if you place an index.html and a index.php in the same folder - and having the configuration above - always the index.html would be delivered by the server.
It will not hurt a website if you serve every page as .php. Apache is very fast to serve any php, let alone one which contains only static html.
As a beginner you may find php will benefit you, by allowing you to creating simple templates. Site header and footer includes for instance could be written in one file, then included in all the other pages.
Its not a big deal whether you use index.php or index.html. You ca use anyone of either. Only thing is you need PHP(or any other server side scripting language) to make your site dynamic.
Like you have a login page,you can surely make it as inde.html but your logics would either have to be in a different file or embedded in HTMl.
You can use which-ever you prefer:
If you prefer keeping forms and basic pages that don't use data in HTML,
and keep pages that use php in php format that is fine.
But one method I and I assume most others use is just make all of your pages php files. This is because you can include a html document in the php file and display it just the same. But you cannot do php queries from a html file so it is easy to just always use php just incase you want to add some php scripts to it.
Index.php:
<?php
$var = 5;
?>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h2>Your variable was <?php echo $var; ?></h2>
</body>
</html>
By default, the apache server needs a file with .php extension to parse the PHP code inside it. Though, if you wish, you may configure your server, by adding a single line to the configuration file, to use files with any extension with PHP code inside it. You can edit the apache by yourself to support php also in .HTML extension.
In simple terms, you can easily access index.html file and get the data beneath it.But index.php is difficult to access. For your simple application index.html will do the trick. If you are planning for some big and secure application go for index.php
It is beacuse sometimes you may have some logic written on index.php. Like you may check if user is logged in or not and then redirect user to some specific page. Also you may do device based redirection as in case of mobile devices.
You can always choose to create index.html but you do not know when youy may need to have some logic there.
For example, in my index.php or another main page I mainly use php because I use variables w/ them in the rest of my site:
<?php
$sitepath="http://www.example.com/public";
$author="your name here";
?>
Because I <?php echo $sitepath ?> every time I link an image in my website so it doesn't break or something. Since I'm reusing the name all the time, I use .php to be able to have that service, because if I use the name, I can change it globally.
I think that simple pages like 404.html, aboutus.html, or ViewOneBlogPost.html could be an HTML page, you might not need any functionality/variables for that.
To check current settings for file extension priority in apache2 with linux
/etc/apache2/mods-enabled/dir.conf
Well you can use HTML if you have a simple few pages where the code doesn't repeat itself a lot. But trust me, if you have a whole website in HTML with more than a thousand lines per file, you will want to use PHP. Why? Because of require and include. These will clean up your code when you need to use layouts, so you don't need to keep copying the hole code of your layout header, footer etc... It can be really difficult to maintain when you need to insert content and there's a lot of code in the way.
Here's some documentation about it
https://www.php.net/manual/en/function.include.php
Related
For a "classic" website, one would create a /foldername/index.php for every web page. With WordPress, however, this is not the case. For example, if a page was created with WordPress whose URI was http://myblog.org/some_page, you would not find the folder www/myblog.org/some_page in your web host's FTP.
My question then, is, How can I serve up pages located at http://[MY_WEBSITE].com/[page_name] for any arbitrary page_name, without creating a new folder for every page_name?
One method would be to use the page_name as parameter to a common file and use that to serve the contents of the required page.
That behaviour is handled (in an Apache server) by a .htaccess file, wherein rewrite rules are defined. Rewrite rules basically capture incoming traffic and directs those requests to a file on the server (typically a single page which will act as a router).
The router is then responsible for taking the input URI (usually via $_SERVER["REQUEST_URI"] in PHP) and working out what to do with it, and ultimately what the output will be for that request.
As for a decent router, you could look at klein.php. Also, a brief example:
# htaccess file
RewriteEngine On
RewriteRule ^[^\.]+$ index.php
And the index.php:
$route = $_SERVER["REQUEST_URI"];
if($route === '/home')
{
echo 'This is the homepage';
}
You tell your server to rewrite the URL. Most servers do it in their own way, so to find out how to do it look at your server's documentation.
Wordpress uses templates that make use of the require() function and a foreach loop commonly called "The Loop" to retreive content.
Different pages are called using different templates. If you want to know exactly how this logic is calculated, look into this.
I have use this to generate this code:
<?php
require_once('mobile_device_detect.php');
mobile_device_detect(true,false,true,true, true,true,true,'http://m.mydomain.com',false);
?>
But the only directions are to "copy and paste this code". Um.. copy and paste where? Do I need to create a new php file? Is this index.php? What if I already have an index.html file?
EDIT: I understand that I put mobile_device_detect.php in the root of mydomain.com. My question is where to put the above php code.
Copy and paste this at the beginning of your PHP based pages that you want to detect the visitors for their device. If your server parses HTML files as PHP which I doubt then add this in your HTML files as well. If you're just building the website then yes you need this in files which are parsed by the PHP engine for example: ".php".
If you paste this in page that is HTML and not parsed by the server you'll see this same code as output which will do nothing. In order to have it working you need it in PHP files.
If your script is well written and well structured you may need to include it in only one place. It all depends how your website is structured.
------ UPDATE ------
Why you shouldn't be using this class? It have a special license which is not absolutely free.
Instead you can use this simple class: https://github.com/serbanghita/Mobile-Detect
Download Mobile_Detect.php
Include the file at the top in your PHP page where you want the device to be checked:
// Include the mobile device detect class
include 'Mobile_Detect.php';
// Init the class
$detect = new Mobile_Detect();
// And here is the magic - checking if the user comes with a mobile device
if ($detect->isMobile()) {
// Detects any mobile device.
// Redirecting
header("Location: http://your_redirected_url.com"); exit;
}
Creating rewrite rules for using html extension.
If you still want to use '.html' as extension just create rewrite rule that will rewrite your .php as .html. Or otherwise said create your_page_name.php and add the PHP code there. Create .htaccess file in the same DIR and add the following lines:
RewriteEngine On
RewriteBase /
RewriteRule ^your_page_name.html/?$ your_page_name.php [L]
Save, close! Now you should be able to use your php page with .html extension. To access your page now just type: http://yourdomain.com/your_page_name.html
Simple as that!
Suggestion: If I was you I'd add the rewrite rules in the web server's config file. It will be faster and more secure. But that's another lesson. If you decide to use this method just search the Stack.
Copy and paste the code anywhere you want. Just make sure the function is defined on any page that needs it.
You should either buy the script mobile_device_detect.php from the site or use a free method called pay with a tweet option.. Go to the download page and you will see them there..
ok, in case this helps someone, here are the details of what's working for me:
Create an index.php file with just this:
<?php
require_once('mobile_device_detect.php');
$mobile = mobile_device_detect();
// redirect all mobiles to mobile site and all other browsers to desktop site
if($mobile==true){
header('Location:http://m.yourdomain.com/');
}else{
header('Location:http://yourdomain.com/index.html');
}
exit;
?>
Drop the mobile_device_detect.php file in the root of your site.
Then, add this line to your .htaccess file:
DirectoryIndex index.php index.html
How can I alter url or part of it using php? I lost the code that I have used and now I cannot find answer online.
I know using header('Location: www.site.com') gets redirect but how can I just show fake URL?
I don't want to use mod_rewrite now.
It is impossible in PHP, which is executed server side. Any change to the url you make will trigger a page loading.
I think it may be possible in javascript, but I really doubt this is a good idea, if you want to rewrite an url only in the user adressbar, you're doing something wrong, or bad ;)
What you've actually asked for isn't possible in using PHP (Although, in JavaScript you can use the dreadful hashbang or the poorly supported bleeding edge pushState).
However, in a comment on another answer you stated that your goal is actually friendly URIs without mod_rewrite. This isn't about showing a different URI to the real one, but about making a URI that isn't based on a simple set of files and directories.
This is usually achieved (in PHP-land) with mod_rewrite, so you should probably stick with that approach.
However, you can do it using ScriptAlias (assuming you use Apache, other webservers may have different approaches).
e.g. ScriptAlias /example /var/www/example.php in the Apache configuration.
Then in the PHP script you can read $_SERVER['REQUEST_URI'] to find out what is requested and pull in the appropriate content.
You can make somewhat SEO-friendly URLs by adding directories after the php script name so that your URLs become:
http://yoursite.com/script.php/arg1/arg2
In script.php:
<?php
$args = preg_split('#/#', $_SERVER['PATH_INFO']);
echo "arg1 = ".$args[1].", arg2 = ".$args[2]."\n";
?>
if you use some more htaccess trickery, then you can make the script.php look like something else (see #David's answer for an idea)
You can try using,
file_get_contents("https://website.com");
This is not going to redirect but fire the api and you can catch the output by assigning a variable to above function.
Say i have a .html file that contains a web design and has variables in it like $time $comment $title.
how would i enter them variables from a php file
Sorry i cannot really explain it well enough but i hope somebody understands
Well.. I'll just guess what you want. Since the question isn't very clear.
In a PHP script, load the HTML in with something like file_get_contents, then use str_replace to replace the 'variables' in the HTML, then echo the new HTML.
Or, don't use an HTML file, use a PHP file, and just use echo where you want the variables to be.
Or... use something like smarty templates which is probably more advanced than you're looking for.
Learn PHP
Learn an MVC Framework of your choice
Change the .html file into .php
Put it in with your "Views"
Call it from your Controller (defining your view variables)
You can get apache to parse .html files as PHP by adding this directive to your .htaccess (or httpd.conf):
AddType application/x-httpd-php .htm .html
It might be necessary to change this line in your httpd.conf:
AllowOverride None
to:
AllowOverride All
That will enable .htaccess overrides to the apache configuration.
This answer assumes two things:
1 - That I understood the question.
2 - That you are in fact using Apache web server.
I also take a chance that I understand you right. If you think of a template system for PHP, I recommend you Smarty, which makes it very easy to divide HTML from php
Why would I use Smarty (when PHP is a template engine)?
Some might argue that Smarty does what
PHP can do already: separate the
presentation from business logic. The
PHP programming language is great for
code development but when mixed with
HTML, the syntax of PHP statements can
be a mess to manage. Smarty makes up
for this by insulating PHP from the
presentation with a much simpler
tag-based syntax. The tags reveal
application content, enforcing a clean
separation from PHP (application)
code. No PHP knowledge is required to
manage Smarty templates.
This sounds more like a utilization problem. As others have noted, static html files are just returned as such, static files. If you want the variables replaced whenever those files are accessed, then define a handler like that from your .htaccess:
RewriteRule (.+\.html) vars.php?file=$1
And a template function (vars.php) to works on those placeholders:
<?php
// define all placeholder variables here
$html = file_get_contents(basename($_GET["file"]));
print preg_replace('/\$(\w+)/e', '$GLOBALS["$1"]', $html);
?>
But it's certainly easier to just rename your .html files into .php, and put a heredoc around them:
<?php
echo<<<END
<html>$vars</html> ...
END;
?>
I have designed a website, and within it I have a range of PHP scripts which interact with my system. For example, if a user uploads an image, this is processed by the script
image.php
and if a user logs in this is processed by the script
login.php
All these scripts are stored in the folder called: scripts
How do I ensure someone cannot access these pages, however still ensure they can be used by the system? I want to ensure the PHP pages will accept post values, get values and can redirect to other pages, but not be directly accessed via the address bar or downloaded?
I attempted to block access using .htaccess using deny from all and Limit GET, POST but this prevented the system from working as I could not access those files at all.
Blocking files with htaccess makes the files inaccessible to the requestor, e.g. the visitor of the page. So you need a proxy file to pass the visitor's request to the files. For that, have a look at the MVC pattern and the Front Controller pattern.
Basically, what you will want to do is route all requests to a single point of entry, e.g. index.php and decide from there, which action(your scripts) is called to process the request. Then you could place your scripts and templates outside the publicly accessible folder or, if that is impossible (on some shared hosts), protect the folders with htaccess like you already did (DENY FROM ALL) then.
To use the upload script you'd have a URL like http://example.com/index.php?action=upload.
A supersimple FrontController is as easy as
$scriptPath = 'path/to/your/scripts/directory/';
$defaultAction = 'action404.php';
$requestedAction = $_GET['action']; // you might want to sanitize this
switch($action) {
case 'upload':
$actionScript = 'image.php';
break;
case 'login':
$actionScript = 'login.php';
break;
default:
$actionScript = $defaultAction;
}
include $scriptPath . $actionScript;
exit;
Your actionScript would then do everything you need to do with the request, including redirection, db access, authentication, uploading stuff, rendering templates, etc - whatever you deem necessary. The default action in the example above could look like this:
<?php // action404.php
header('HTTP/1.1 404 File Not Found');
fpassthru('path/to/template/directory/error404.html');
There is numerous implementations of the FrontController pattern in PHP. Some simple, some complex. The CodeIgniter framework uses a lightweight MVC/FrontController implementation that might not be too overwhelming if this is new to to you.
Like Atli above suggested, you could use mod_rewrite to force all requests to index.php and you could also use it to pretty up your URLs. This is common practice with MVC frameworks and has been covered extensively here and elsewhere.
You can't really prevent direct requests to the files, and still have them remain accessible to other requests. The best you can do is mask their location, and control how they are accessed.
One way you could go is to create a PHP "switch" script, which would include the scripts for you, rather than have Apache request them directly.
For example, if you had your scripts/image.php rule target switch.php?file=image.php instead, somewhat like:
RewriteRule ([^\.]+\.(jpe?g|png|gif)$ switch.php?file=image.php&rw=1&meta=$1 [L,QSA]
You could add deny from all to the scripts/.htaccess file and do this in your switch.php file.
<?php
/** File: switch.php **/
$allowed_files = array(
'login.php',
'image.php'
);
$script_dir = 'scripts/';
if(isset($_POST['rw']) && in_array($_REQUEST['file'], $allowed_files)) {
include $script_dir . $allowed_files[$_REQUEST['file']];
}
else {
header('HTTP/1.1 404 File Not Found');
include 'error404.html'; // Or something to that effect.
}
?>
The $_POST['rw'] there is a weak check, to see if the rule came from a RewriteRule, meant to prevent direct requests to the file. Pretty easy to bypass if you know it is there, but effective against random requests by bots and such.
This way, direct requests to either scripts/image.php and switch.php?file=image.php would fail, but requests to any image file would trigger the scripts/image.php script.
You can set deny from all on .htaccess and include these files from some accessible directory
I want to ensure the PHP pages will accept post values, get values and can redirect to other pages, but not be directly accessed via the address bar or downloaded?
As long as Apache is configured to associate all .php files with the PHP application, no one can download the PHP content itself. So, if someone browsed to "mysite.com/image.php", PHP will run. The user will NOT see your PHP content.
This should already by done in your httpd.conf file as :
AddType application/x-httpd-php .php .phtml
Now, image.php will be expecting certain post parameters. Short of implementing an MVC architecture as Atli suggested above, you could gracefully and securely deal with any missing parameters if they aren't provided. Then, users can get to the page directly but not do anything with it.
A lot of applications just put files like your scripts not in the public (like /public_html/ or /www/) folder but in the same root folder as your public folder.
so not
root/public_html/ and
root/public_html/scripts/
but
root/public_html/ and
root/scripts/
Anything in a folder above the public folder can't be accessed by visitors, but by specifying in for example /public_html/index.php the file '../scripts/yourscript.php' PHP can access these files and visitors can't. (the folder ../ means "go up one step in the folder hierarchy")