I am working on building a small php/mysql script that will act something like a wordpress blog but will just be a small site for my eyes only to store PHP code snippets. So I will have categories and then pages with sample code that I write with a javascript syntax highlighter. Instead of storing my php code snippets in the file I am wanting to save them to mysql DB. So what is the best way to save PHP into mysql and to get it out of mysql to show on the page?
My end result will be something like this
alt text http://img2.pict.com/c1/c4/69/2516419/0/800/screenshot2b193.png
Update:
I just wasn't sure if I needed to do something special to the code before sending it to mysql since it has all different kinds of characters in it
Just store in a text field, as is. Not much more beyond that.
If you're not using some kind of database abstraction layer, just call mysql_real_escape_string on the text.
Do you want to be able to search the php code? If so, I recommend using the MyISAM table type as it supports full text indexes (InnoDB does not). Your choices for column type when it comes to a fulltext index are char, varchar and text. I would go with text as your code snippets might get too long for the other types.
Another point worth mentioning, is make sure you properly escape all php code (or any value for that matter) before you insert it. The best way to do this is by using parameterized queries.
Unless I'm missing part of the problem, you should be safe storing it as a TEXT field in a MySQL database. Just make absolutely sure you sanitize the code snippets, as PHP code in particular is quite likely to contain the characters that will escape out of an SQL string. (If you're already using an SQL framework, odds are the framework is doing this for you.)
Store as text (varchar) in the database.
Use cascading style sheet (css) to format code.
http://qbnz.com/highlighter/
Try this:
mysql select ...
eval('?>' . $row['phpcode'] . '<?php ');
Related
I am trying to find out a way to do maths dynamically. I want to be able to add a formula to MySQL and then solve it in PHP and display the answer.
So I'll save it like getItemPrice(10) * getItemPrice(50) However I'm unsure how to execute functions in PHP if its saved like that.
I thought about splitting the date but I want to be able to do more advanced formulas then that. I have no idea how to do this to be honest...
If the text you stored in db is a valid php code you can use
eval — Evaluate a string as PHP code
http://php.net/manual/en/function.eval.php
otherwise if the text is a valid mysql code you can generate a dinamic sql statementes and the execute as a normal sql statemets ..
I'm trying to realize a dynamic website for exercise. All contents are stored in the database:
I included html code(FORMS) as DB content with no ploblem, but when i try to insert php code as DB content nothing happens. The field type for Content is TEXT.
I tryed various ways :
INSERT INTO TableContent(Name_Content, Content, ID_Menu) values ("Amministration Area", "<?php include('LogIn.php')", 5);
INSERT INTO TableContent(Name_Content, Content, ID_Menu) values ("Amministration Area", "<?php include(\"LogIn.php\")", 5);
In the website page i see Amministrazion Area, but not what Login.php does.
I thought i made a mistake in Login.php page code so i changed it in a simply echo ("Hi"); but nothing appears anyway. I see only the text Amministration Area.
How can i solve it ?
It's just text! Text in a database. Nothing happens when you just insert text into a database and read from it. You have to actually get something to execute that text as PHP code. That doesn't happen automatically, thankfully! In PHP, the way to execute arbitrary strings as code is by using eval. But this is overall a very bad idea; storing all PHP code in a database is not making anything easier, on the contrary it makes everything more difficult to work with and more prone to exploits if you execute arbitrary code. I'd advice you to stop doing that and go back to PHP code in .php files, not databases.
PHP see <?php include("LogIn.php");? as a string, when you look in the source code of your file, you'll probably see it. It doesn't show up on screen because it starts with a <.
To execute the code instead of handling it as a string, you can use the eval() function.
You however don't want every row of your database be seen as PHP code, so you'll probably need to add a extra column that defines what the row is, i.e. a string, php code. Or you make an extra table where you store your includes.
I want to store articles in a database, but I cannot seem to find much information on the best way to do this, from what I have read it seems split between most people on how to effectively do this. A lot of people will suggest a way and others will point out sql injection issues, and I cannot seem to find much about this topic that is fairly new.
Here is the html of an article:
<div id="main">
<article>
<header>
<h3> Title </h3>
<time pubdate="pubdate"> 2011-07-22 </time>
</header>
<p> Article Text </p>
</article>
</div>
Ideally I guess it would be best to store the chunk of html making up each article into a database but there seems to be a lot of problems with this, and like I said I can't find many posts over this particular topic, and as someone new to php and databases I want to get some input on the best way to go about this before I proceed.
When ever I store a large amount of user text, I just base64 it, then before you display it, make sure to run it through htmlspecialchars, this will keep html from working, so htmlspecialchars(base64_decode($content)) would work fine for displaying.
If you are using bbcode for formatting, then make sure to run htmlspecialchars before you start formatting your bbcode.
This isn't the only way, you can sanitize inputs without base64'ng it, but I see no reason not to, especially when nobody needs to see directly into the database.
Storing it in a SQL db is fine, but you can and you must protect against SQL injection in your code.
ie, cleaning all user input before sending it to the db.
PHP Manual on SQL injection
I think the best method is to just store pure text, but usually that is not the case when you want to use extra formatting. You can convert the html tags to bbcodes or similar tags which can prevent sql injection however if you escape the html content it would be as safe as any other content. so do mysql_real_escape_string on whatever data you put into the database and you would be fine.
However, the best practice would be to store the html code along with the article text as a html file which you can serve when the user requests the data but in the database you can just store purely text for indexing and search purposes. This is ideal as you would not need the html content for searching anyways and it will also prevent sql attacks if the content is purely text that is to be stored in the database. But as the user requests the file get the content of the html file for that article which contains the formatted text and serve that.
use lucene or sphinx, either from Zend_Lucene or through solr. they will make the indexing for the article faster, and you can also do a full text search on them too. using lucene or solar to index and search in these cases is pretty much a standard procedure, and will let you scale to millions of articles.
sphinx is a daemon that runs "in parallel" to the mysql daemon. for using sphinx, you can use the pecl sphinx extension.
if you want to go with lucene, you can try zend_lucene or solr, which is actually a tomcat distro with an webapp that exposes lucene as a web service, so you can access it in a standard way, independantly of the language.
choosing either of them is ok. you can index by full text (content), and categories, or whatever you need to index by.
the safest way to prevent sql injection here is to use prepared statement.
$stmt = $con->prepare("INSERT INTO Articles (Title, Date, Article) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $title, $currentDate, $articleBody);
The question marks represent the values you will pass. "sss" is saying that each of the 3 variables will be a string and then you can call this prepared statement and pass it the correct values.
$title = $_POST[title];
$currentDate = date("Y-m-d H:i:s");
$articleBody = $_POST[article];
$stmt->execute();
this will make sure that no malicious sql can be injected into your database.
hope this helps!
Store your article as TEXT :) Just pass it through this php function first to prevent injection attacks:
// Prevent MySQL Injection Attacks
function cleanQuery($string){
if(get_magic_quotes_gpc()) // prevents duplicate backslashes
$string = stripslashes($string);
return mysql_escape_string($string);
}
I have an HTML table with contents, I would like to have an feature of Edit/Delete to that table. How do I do it with PHP?
I actually think that this sounds more like a job for JavaScript, which can edit/remove rows on-the-fly and with much less code. (Implement some AJAX too, and you can edit/remove rows in database too).
But if you insist on using PHP, you might just want to add some GET parameters to the Edit/Delete links that would delete or edit those rows.
Well, there is a pure PHP way to do it, and then there is a combination of Javascript and PHP. You must use PHP one way or another if you want your changes to the database to be permanent as that is your gateway to communicating with the database (as far as I know you cannot do that with Javascript as that is client-based and runs entirely in your web browser).
If using just PHP, you must generate HTML documents for each change. E.g., you click on one cell in the table and that gets you to a new HTML page where the field is editable through an input element; or you can list all fields at once for that row and edit them all at the same time. The fields are then posted in a form to a PHP page which will take the new values and update the database (or insert new values or however you wish it to behave). Here's a tutorial for how to do this:
http://www.freewebmasterhelp.com/tutorials/phpmysql/1
You can also mix in some Javascript which allows a more interactive interface to modifying the values in a cell. However, this obviously requires more code and may be overkill for what you're trying to do. Nonetheless, here is a link which demonstrates just that and also shows the code:
http://www.java2s.com/Code/JavaScript/GUI-Components/Editabletablecell.htm
Hope this is what you're looking for.
EDIT:
Forgot that you also wished to delete content in the table. That is also explained in the first link.
If you intend to work with databases, and it seems like you have little understanding of how they work, pick up a good book like: SQL - The Complete Reference. When you have enough knowledge of SQL, look at PHP's PDO extension: http://php.net/manual/en/book.pdo.php
I wonder if there's any downside or bad practice in doing the following procedure:
$user_input -> htmlentities($user_input) -> mysql_escape($user_input) -> insert $user_input into DB
Select $user_input from DB -> echo $user_input
instead of doing the following:
$user_input -> mysql_escape($user_input) -> insert $user_input into DB
Select $user_input from DB -> echo htmlentities($user_input)
As we display the same $user_input on a lot of places it feels more efficient do to it on the input instead, are there any downsides / bad practice / exploit-ability in doing it this way?
Cheers!
Good replies to the question from:
#Matt: In general, to keep things readable and maintainable, try to store it as close to the original, unfiltered content as possible. It depends on two things:
Is any other person/program going to reference this data?
Does the data need to be easily editable?
#Sjoerd: There is a downside if you want to display the data as something else than HTML, e.g. a CSV download, PDF, etc.
It depends on two things:
Is any other person/program going to reference this data?
Does the data need to be easily editable?
The advantage of method one is that, in the case that the data is used in one place, and htmlentities() would be called every time, you'd be saving this step.
However, this would only leave a notable improvement if the HTML data is very large. In general, to keep things readable and maintainable, try to store it as close to the original, unfiltered content as possible.
In fact, you might find that HTML is the wrong thing to store anyway. It might be better to store something like Markdown and simply convert it to HTML when viewed.
I'd advice against it. If you ever need that data for anything other than displaying it as HTML (display in console, send in text email, write to log, etc) , you'll have to convert it back.
A good practice is to apply such transformations only at the last moment. Use mysql_escape before inserting into the database, use htmlentities (or htmlspecialchars) before displaying as HTML. That way you always know where your escape functions should be. If they're not there, you can easily tell you're doing something wrong. You also know that data in the database is always clean and you don't need to remember if you encoded it, what with and how to turn it back.
There is a downside if you want to display the data as something else than HTML, e.g. a CSV download, PDF, etc.