简体   繁体   中英

load php scripts from a mysql database table

I have a mysql database and in one of the fields I have a bunch of normal html and a php script in the middle of it. When I pull from the database and display the field the php does not render as php, but as html. Was wondering if it is possible to put php scripts in a mysql database field and then have them render as php when pulled onto a web page, and if so how do i do this.

I have done this before using the eval function. However, eval is dangerous because if malicious code gets injected it could cause serious harm, so proceed with caution.

What I have done as an alternative is store a class name and parameters in a database and then generate the given class to generate the html and php.

What you are looking for is eval() ... because when you pull the code from the database it is stored as a string.

BUT be warned! ...

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged .

Taken straight from the PHP docs .

If you take user input into the database fields, do not use eval() as the user can upload malicious scripts into your database.

In fact why do you need to store PHP in the database? This sounds poorly designed and I would strongly encourage you to find another method. Check out Mustache or search for PHP templating engine.

If you must use eval() read about it a lot first , make sure you understand the security risks.

It's not a good idea to do this in the first place - out of security, design and other considerations.

The usual way to do this is called templating .

Your HTML code in the database would contain placeholders, say like

<h1>Title of this page: {$title}</h1>
<p>Contents: {$contents}</p>
...

you would then fill in those placeholders using PHP, after pulling them from the database. There are also full-blown template engines that do the job, eg Smarty or Twig . (The latter is a bit more light-weight)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM