I have a few general questions I would like to have a better understanding on.
For a project I have been spending my free time on, I am attempting to display a ladder-based rankings table for a weekly-based chess tournament on a website. To do this, I have created a MYSQL database to hold each player's wins/losses/tournament wins. I understand that in order to display this data onto a html-based website, I need to use php to connect the database and the site.
I also have a very shallow understanding of php as a server-side language, and not a client-side one. Basically to me, this means that php can only be understood by the online server hosting the site, and not by the web browser (such as Google Chrome) itself. Consequently, this means that I can't simply run a .php file by opening it in Notepad++ and choosing "Run in Chrome". That will not work - I can only test php files by first saving them into the website directory and viewing them online. Is this the correct way of thinking about this?
My second question is more straightforward - and it involves the steps required to connect my website and the MYSQL server. Here is my first attempt:
<?php
//Connect to database
$db = mysql_connect("a2412233_ss","a2412233_ss", 'My_Password');
if (! $db){
die("Database connection failed: " . mysql_error());
}
else
echo("Success!");
?>
<html>
<head>
<Title> MySQL Table Connection </Title>
</head>
<body>
</body>
</html>
Two problems with this that I would love to get cleared up:
1) When I click the link to this file from my index.html on the website, the php file downloads rather than opening up on the browser window like a normal webpage should. So clearly something is wrong there.
2) Secondly, I am uncomfortable with the fact that written this way, anyone can view my database info/password by viewing this page source. So there has to be a better way of doing this where that php isn't visible by viewing the source.
Thank you all for the clarification and kick in the right direction! Slowly getting this html/MYSQL/php stuff figured out.
In regards to your first question, Yes that is correct, as it is server side and not client side, you can only view your php page if the code is running through a host.
I would recommend looking into getting XAMPP, which is a piece of software which allows you to use a local host to more quickly test out your code, this also comes with a free MySQL database (for local use only, but still serves a good purpose for testing). But anyway, you can look up on youtube tutorials on how to get XAMPP set up, it's not that complicated, and will save you tons of time when testing out your code, as it's then just as simple as editing your code, hitting the save button and then you can view the changes straight away in your browser.
Also I'd like to point out that you should rename your index.html to index.php, otherwise your browser won't/may not recognise your php code.
In regards to your second question, mysql_connect is generally an older way of connecting to the database, and a lot of people may advice you to avoid it, but I suppose it will do no harm at all to connect to a database this way, yet again, for this question you should be able to find many tutorials on youtube to help you set up your database and connect to it using a php script.
Oh and one last thing, to get rid of your doubts, as PHP is server side, it means that if someone was to 'view source code', they will not be able to see any of your PHP code, all they will see if the HTML and CSS code (or any other client side code), and therefore your username and passwords for your database are entirely safe.
EDIT: I'd also recommend looking at this PHP manual to pick up some of the basics of the language: http://php.net/manual/en/index.php
Related
I'am doing a dynamic site in php. The contents to my 'project' page can be added/edited/deleted from the backend. I'm able to do the same from my computer (localhost). When I upload the site online, I'm not able to perform these operations. I have given all user privileges from the cpanel. Still its not working. I'm able to login to my backend and even view the contents that's been loaded dynamically. But i'm not able to add/delete/edit (only when its online). This is my connection code:
<?php
$connection =mysql_connect("localhost","user_name","password");
$database=mysql_select_db("db_name");
if(isset($_SESSION["message1"]))
{
echo "<script language='javascript'> alert('{$_SESSION['message1']}'); </script>";
}
?>
Can Somebody help me solve this? Is it something related to my host name?
I cannot add comments and that's why I answer your question !
First check in your cPanel what PHP version you are using, if it's 7.x, you will not be able use mysql_* api, you may use mysqli_* or even better PDO, however, I think you can change your PHP version in cPanel to lower version, also if you can load contents with same connection using mysql_*, this might not be the problem !
Can you post your add/delete/edit queries here ?
Your host should be probably ok, however you can test the connection using try {} catch {}
One thing that I can think of would be different table name or column name between your local and online database, this things might happen often when working on two different environments
Newbie here. My hosting company recently upgraded their server(s) and that's where my website problems began:
FYI:
MySQL upgraded from 5.1.70 to version 5.5.32
Apache upgraded from 2.2.25 to version 2.4.6
PHP upgraded from 5.3.27 to version 5.4.22
I have a shared hosting account
For the last 2 days I've been searching Google, online manuals and developer/tech forums for possible answers to my "issues" and I'm having no luck finding good answers that help me fix my code to make my website display properly. Very frustrating. Obviously I need to learn more.
BKGD: I hired a developer to build a CMS for my website a couple of years ago and have since been trying to learn so I have a VERY basic understanding of Php, MySQL and HTML... but obviously not enough to fix these issues. Can you/anyone please help me get closer to fixing this nightmare.
I know my original website code worked fine a week ago - prior to the hosting updates.
The Index page and other "main Sections" currently display just fine for some reason. But if you click on any of the links to "articles", "news" and other "pages", those pages are not connecting properly >> not pulling table data from the associated MySQL database. Those pages showed a couple of different error messages.... initially displayed ONLY a "1064 syntax error" message OR "no page found" error (no "header", "footer", "page title", or any other info). I've since tweaked the code (I.e., I "hid" some of it with "//") and have it displaying the header and footer but nothing from MySQL database.
The original "php.ini" file needed extra code >> "register_globals=on" << to work properly after the second-to-last Php & MySQL update. That is now "deprecated" and "removed".
This newbie thinks that the following code is ONE EXAMPLE that isn't working properly (that I believe needs to be edited/updated to allow it to connect to MySQL). I think if I figure this one out I can apply similar tweaks to the other "news" and "article" pages:
//-- START: SAMPLE CODE ----
include "init.php";
$res = mysql_query("SELECT * FROM {$prefix}pages WHERE pag_name='$page_name'") or report();
if (mysql_num_rows($res)==1)
cdie("no page found");
else
$row=fetch($res);
$title = "$row[pag_title]";
$desc = "$row[pag_description]";
//------- END: SAMPLE CODE --
I realize I might be way off on this being the issue (E.g., the problem might be in the functions.php file) but that's where I'm at right now. Clueless. Ugh.
Any thoughts or suggestions? Need more info (just ask and I'll reply as soon as I get the email).
If your code relies on register_globals, you are going to run into undefined variable problems.
For example, if the $page_name variable comes from a query string like index.php?page_name=test, you could access it before like $page_name but now you must access it like $_GET['page_name'].
You need to check all your code to see if your variables are defined (a good IDE can help with that).
As a sidenote, you also need to double-check to see if you don't have any sql injection problems, injecting variables directly in a query is normally not a good sign. You should really switch to PDO or mysqli and prepared statements but at the very least use mysql_real_escape_string on your variables before you use them in your queries.
Ok , so many people are asking this question, and there are many approaches on how to make the connection to DB secure,
Now I did some googling , many suggest, putting the connection to DB code in a file outside the html_public , and to call it from there when I need to make a connection.
to be honest, am happy with what I have, though I'm not sure how secure it is,
this is how I connect to the DB:
first, I make sure all inputs are fully escaped and validated...
after , in the same page , i make the connection, for example:
mysql_connect("localhost","Admin","Password") or
die ("DB Connection Error");
mysql_select_db("Users") or die ("DB Error");
and the rest of the code after, I close the mysql connection.
Now , It just don't feel right that the DB user info are written in the page, but how can someone (a "hacker") , get this info?
I mean , all inputs are fully escaped and validated, the users I use have very limited previleges, like select and update... only.
Is this secure?? and if not, can u please suggest a more secure way?
Thank you very much for ur help in advance :)
shady
The reason you should consider putting this file outside the web root is that some hosting providers have temporarily stopped interpreting PHP from time to time (due to configuration faults, often after an update on their part). The code will then get sent in clear text and the password will be out in the wild.
Consider this directory structure, where public_html is the web root:
/include1.php
/public_html/index.php
/public_html/includes/include0.php
Now consider this index.php:
<?php
include('includes/include0.php');
do_db_work_and_serve_page_to_visitor();
?>
If the web server starts serving this file in the open, it won't take long before someone tries to download include0.php. Nobody will be able to download include1.php, however, because it's outside the web root and therefore never handled by the web server.
I've personally not heard of a hosting provider not interpreting PHP, leading to your php source code going public. I just did a quick test on this on a RHEL5-Based server without php installed, and just got back a blank page when trying to access a php document.
mysql_* functions have become deprecated with the latest releases of php, and are now moving towards mysqli, as an overall more efficient and secure solution; I'd recommend taking a look into that; http://php.net/manual/en/book.mysqli.php - there's no deprecation errors or anything of the sort yet in PHP5.4 for using plain mysql_ functions, but if you're looking to keep on top of things, take a look into mysqli.
As for a quick answer to your above question, to be honest, I'd see that method as reasonably secure. Just make sure you've got escape chars etc set up, and I don't think you'll run into any issues.
Edit: Some people have posted that in very rare cases, some providers can leak your php source code in this manner. If this is the case, my first advice would be to switch provider.. but using an include_once to load your db info from another php file/lib would be a quick workaround for this. But again, if your provider's setup does allow for leaks such as these, I would be more concerned about their security than yours.
You can have php grab your DB password from a text file stored outside of the public webspace (using fopen), but I personally don't see any real reason for doing this.
Best of luck!
Eoghan
The best pratice is to use PHP PDO instead of the old mysql API.
Take a look: http://php.net/manual/en/ref.pdo-mysql.connection.php
Also, here's an interesting article: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
I code a simple php/mysql web page, that there is page1.php, page2.php and so on. Because I make use of the database on every page (or at least the 90% of them) I place on the top of them the standard
mysql_connect("localhost"," "," ");
mysql_select_db(" ");
.
.
mysql_close();
with my queries.
My question is do I really need to connect to the database on each page or is there any way to avoid this and still stay connected? Some of the pages are linked to the others and I can make use of SESSIONS to post some variables, but my question goes to something more globalized.
The web works in a disconnected state by nature. Meaning that you have no idea if the client is going to come back for a second request or not.
Regardless you absolutely want to connect/disconnect from the database on every single page. This is the only way to ensure you aren't leaking connections and the site can stay responsive.
Most systems have built in ways to handle connection pooling which makes the act of requesting a new connection very very fast and therefore something you don't have to worry about.
You can use mysql_pconnect for a persistent connection, although its not going to help you that much and it can be a big pain to do properly. Its almost just better to connect on every page, especially if the database server is running on the same machine as the php server.
Try using
mysql_pconnect()
From PHP.net
"acts very much like mysql_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect())."
If you just want to make it so that you don't have to hard code it into the top of every file write the connection code in a file then use require /path/to/file/name.php and it will establish it everytime Note: it might be include and not require.
In my CMS I've added this code <div><?php include("my_contact_form.php") ?></div> which updates to a db. I can see it there OK.
I have this php code in my display page after the db call:
$content = $row['content'];
when I echo $content inside the body this is displayed in the HTML source:
<div><?php include("my_contact_form.php") ?></div>
How could this possibly be? Why wouldn't it show my contact form?
If anyone has any suggestions I would be extremely grateful.
Cheers.
It sounds like you are storing the PHP code in the database and expecting it to be executed when you echo it. This won't happen, as far as the PHP interpreter is concerned it's just text (not PHP code) so it will just echo it.
You can force PHP to interpret (/run) the code in your string with the eval() function, but that comes with a large number of security warnings.
Storing code in the database is rarely the right solution.
The simple solution is to run eval() on your content.
$content = $row['content'];
eval("?>".$content."<?php");
The closing PHP tag and opening PHP tag allow you to embed HTML and PHP into the eval() statement.
About the choice of storing your PHP and the DB vs Files.
Assuming you're goal is to have PHP that can be edited by admins from an interface, and executed by your server.
You have two choices:
Write the PHP to files, and include or exec() the files.
Write the PHP to the DB, and exec() or cache the content to files and include().
If you're on a dedicated or VPS server, then writing to files is the best choice.
However, if you're on a shared hosting system, then writing to DB is actually the safer choice. However, this comes with the task that you must use a very safe system for querying the database, to eliminated all SQL injection possibility.
The reason the DB is safer in a shared environment is due to the fact that you'll need write access for the PHP process to the PHP files. Unfortunately, on "every" shared hosting setup, the same PHP user runs on each account and thus has write access to the same PHP files. So a malicious user just has to sign up for hosting and land on the same physical machine as you, or exploit a different account to gain access to yours.
With saving the PHP in mysql, PHP cannot write to the mysql files since it doesn't have the privileges. So you end up with more secure code, if you eliminate the possibility of SQL injection. Note that if you have an SQL injection vulnerability with write ability, then you have also opened a remote code execution vulnerability.
Edit:
Sorry the correct syntax is:
eval("\r\n?>\r\n ".$php."\r\n<?php\r\n");
Thats been tested quite intensively to work on every PHP configuration/setup.
You're echoing $content, that just prints out the value, but it doesn't execute any PHP within it.
If you're using an existing CMS, like Joomla, Drupal, etc.
The CMS is handling the text from the DB as what it is - text. It won't execute the text, it's probably just pulling it as a string from the DB and echoing it onto the page. See Brenton Alker's answer for a better explaination.
If possible, it would be better to work within the functionality of the CMS, and avoid hacking your CMS's source to use eval(). Depending which CMS you're using, there may be a feature (ie: a button in your editor, or similar) to include code from another file.
Or perhaps there's a feature to create "objects", "modules", whatever-they-wanted-to-call-them, which would allow you to place the code (as HTML) that you're trying to include into an "object", stored in the DB, allowing you to include it in numerous pages. This would attain the same goals as doing an include() in PHP (code reuse, avoiding duplicates, making changes in one place, etc.) but it would also save you having to hack the CMS or start risking security.
If you've built your own CMS
You may want to build such a feature in. It all depends on your needs, and how important security is.
Ultimately if you use eval(), and if anyone hacks either:
Your DB
Your CMS's admin interface
then they will be able to execute any PHP code on your server. And if you have exec() enabled in your php.ini (which is not safe), then they will also be able to run any code they want on your server itself... eeek!
Thanks for this - simple solutions are the best for me! Thanks for the extra info too. Sadly eval() as you suggest it didn't work for me here. So, plan C, I've decided to create a selectable tinymce template that has an iframe which calls the contact_form page and all the processing happens in the iframe. This works. Thanks everyone!