I'm making a small CMS for practice. I am using CKEDITOR and is trying to make it avaliable to write something like %contactform% in the text, and then my PHP function will replace it with a contactform.
I've accomplished to replace the text with a form. But now I need the PHP code for the form to send a mail. I'm using file_get_contents(); but it's stripping the php-code.
I've used include(); to get the php-code from another file then and that works for now. I would like to do it with one file tho.
So - can I get all content from a file INCLUDING the php-code?
*UPDATE *
I'll try to explain in another way.
I can create a page in my CMS where I can write a header and some content. In the content I am able to write %contactform%.
When I get the content from the database I am replacing %contactform% with the content from /inserts/contactform.php, using file_get_contents(); where I have the form in HTML and my php code:
if(isset($_POST['submit'])) {
echo 'Now my form is submitted!';
}
<form method="post">
<input type="text" name="email">
<input type="submit" name="submit">
</form>
Now I was expecting to retrieve the form AND the php code active. But If I press my submit button in the form it's not firing the php code.
I do not wan't to show the php code I want to be able to use it.
I still have to guess, but from your update, I think you ultimatly end up with a variable, which contains the content from the database with %contactform% replaced by file_get_contents('/inserts/contactform.php').
Something like:
$contentToOutput = str_replace(
'%contactform%',
file_get_contents('/inserts/contactform.php'),
$contentFromDatabase
);
If you echo out that variable, it will just send it's content as is. No php will get executed.
Though it's risky in many cases, if you know what you're doing you can use eval to parse the php code. With mixed code like this, you maybe want to do it like the following.
ob_start();
eval('; ?>' . $contentToOutput);
$parsedContent = ob_get_clean();
$parsedContent should now contain the results after executing the code. You can now send it to the user or handle it whatever way you want to.
Of course you'll have to make sure that whatever is in $contentToOutput is valid php code (or a valid mixture of php with php-tags and text).
Here is a link to the symfony Templating/PhpEngine class. Have a look at the evaluate method to see the above example in real code.
yes...
$content = file_get_contents( 'path to your file' );
for printing try
echo htmlspecialchars( $content );
From reading the revised question, I think the answer is "You can't get there from here." Let me try to explain what I think you will encounter.
First, consider the nature of HTTP and the client/server model. Clients make requests and servers make responses. Each request is atomic, complete and stateless, and each response is complete and usually instantaneous. And that is the end of it. The server disconnects and goes back to "sleep" until the client makes a new request.
Let's say I make a request for a web page. A PHP script runs and it prepares a response document (HTML, probably) and the server sends the document to my browser. If the document contains an HTML form, I can submit the form to the URL of the action= script. But when I submit the form, I am making a new request that goes back to the server.
As I understand your design, the plan is to put both the HTML form and the PHP action script into the textarea of the CKeditor at the location of the %contactform% string. This would be presented to the client who would submit the form back to your server, where it would run the PHP script. I just don't think that will work, and if you find a way to make it work, you're basically saying, "I will accept external input and run it in PHP." That would represent an unacceptable security exposure for me.
If you can step back from the technical details and just tell us in plain language what you're trying to achieve, we may be able to offer a suggestion about the design pattern.
Related
Can you put PHP anywhere in a file? Inside tags and quotes? For example, is something like this guaranteed to work (even though it isn't always recognized by an IDE's syntax highlighter):
<tr><tbody <?php if(!$row) echo "style='display: none;'"; ?>>
<!-- stuff that we only want to show if $row exists -->
</tbody></tr>
Or for example:
<a href="http://www.google.com/search?q=<?= echo $searchTerm; ?>"</a>
I know I can test this sort of thing on my machine, but I'm wondering if it is guaranteed/defined behavior and if there are any edge cases that don't work that I've missed.
Also, is there good reason not to do this? Is it dangerous because the next person looking at the code might miss it? Should I put a comment in? Does having to add a comment defeat the purpose of this method - succinctness?
Yes you can put the php tags anywhere in the page (html) there is no stopping you on that.
If we go under the hood, your web server sends the code to the php interpreter via a handler and merges the output with your static html file and sends the merged file as the response.
To add to my answer, developers usually go for MVC based frameworks so that the php code inside html page is restricted to only printing the variables and the business logic is performed in the controllers. I personally prefer CakePHP. Apart from that you might not want to put code that manipulates session or performs redirection between html tags else you will recieve the headers already set error as you have already printed certain html code before modifying the headers.
I'm coding an website which must have same functionality as SO. My server use Litespeed, which increase the speed of runing php files.
When I'm trying to send php code in regular form, everything seems to be ok, data being sent to the action file without interpreting the code inside the variable. But when I'm trying to send the same data in comments textareas, with jQuery $.post method, I'm getting Forbidden 403 error. Data is blocked on the road by Litespeed server. I don't know why is happening this, why is $_POST data auto-evaluated when using ajax?
This situation doesn't appear everytime, but just in some cases, for example:
this is a new message which presents this php code: <?php mysql_query("SELECT * FROM my_table"); ?>
Note that if I remove <?php and ?> from my message, it is ok. I've already tried to use encodeURI() method but this don't change anything.
Is there any setting which must be applied in .htaccess for not auto-evaluate $_POST data?
or I should replace the open and close tags, before sending the comment?
Later edit
This is how I managed to resolve this right now, but I'm still waiting for a suggestion with .htaccess:
$but.prev('textarea').val().replace(/(<\?php)/gi,'-?php ').replace(/(<\?)/gi,'-? ').replace(/\?>/gi,' ?-');
and on the server side
str_replace(array('-?php','?-','-?'), array('`<?php','?>`','`<?'), $_POST['comment']);
What is the quickest and easiest way to run a small php script on my html page and what do I need to do to get it running? I'm asking because I use html and css all the time, but have never done anything in php. I'll be using it to create an email form that doesn't open an email client to send it.
First, your host needs to support PHP. Most do.
Make a basic script like this:
<?php
mail('your#email.com', 'Some Subject', print_r($_POST, true));
?>
Then, build yourself an HTML form that points to this script...
<form action="yourscript.php" method="post">
<input type="text" name="SomeField" />
<input type="submit" name="submit" value="Submit" />
</form>
That's all there is to it. HOWEVER, this is problematic. You will get spam. You need to implement CAPTCHA and such. Otherwise you will get e-mails all the time, even if someone just hits this script with their web browser and no POST data.
Read a tutorial and learn some PHP. It will help you in the long run.
There is also a great form example on tizag.com that will help you understand the components at work here. Basically, you have an HTML form with a few fields (SomeField, submit) and when someone submits this form it will send the data to yourscript.php via the POST method. The PHP script can then read the data in the $_POST array. PHP has a convenient mail() function that is great for sending basic e-mail messages. The print_r() function is used to show everything in an array, such as $_POST.
well, the form itself is html, your form will post ( or GET) to your php script and this will send the email and show output.
To execute the php script you need a webserver that supports php (IIS with the php module, apache with php module etc). Your webserver will host the script and then will execute it and return the output to the browser.
Also you need access to an SMTP server in order to send the email.
Look at php mail for basic usage, and mostly pear mail for a more complete solution ( including smtp auth).
You need to have php installed and configured properly with your server. Then it's as easy as this:
<?php
echo 'Hello World';
?>
Edit: Also, you may need to use the file extension .php on the page you are trying to run the script on. For example index.php - It may or may not work if the extension is .html
Does that work? If so you are ready to make your script. If not please provide more information about your hosting environment.
The .php file is translated just like a normal HTML page if you don't use the opening tag for PHP (), so you can just have normal HTML, and put the PHP somewhere on the page in tags.
So I have an 'export' application that arrives the user at an end page with a textarea with lots of text. Now the workflow is to copy and paste that text from the textarea into a file.
The exported code is getting larger, and we want to encourage users to do this more often, so the copy/paste route is no longer desirable. (Not to mention that my xterm->ssh->screen->vi chain doesn't paste 250K characters so well)
So the problem is this: I have a textarea that has exported code in it, and I want to provide a button that is 'Download this Code to a file'
I'm fairly sure that I will have to hit the server again, but I just want to check all my bases. The ways I can think of doing this (sending generated textarea value as a file ot the browser)
Create a script that receives said text as a POST and sends it back with the right Content Headers. This is no desirable because we would be POSTing 250k, which would be slower than:
Create a script that regenerates the text area and provide a button the original page that hits the scripts and downloads the file. This is the option I am leaning towards
Use Javascript somehow and perhaps beable to skip the server all together and just send the $('.exported').val() to the browser with the right headers? Not sure how to do this atm.
So if anyone has suggestions that'd be great, maybe I'm overlooking something. Thanks!
edit: Download textarea contents as a file using only Javascript (no server-side)
This question says the JS route is not possible (probable)
I would go with option 2. Simplest and fastest. The other ones are a bit contrived.
If you go with option 2, why even leave the textarea at all?
I would suggest the following: make your button replace the whole DOM of the page with your text. After that, user will be able to simply press Ctrl+S or ⌘S. Not exactly what you want, but still a shortcut.
I guess you can do it with the following (jQuery):
$ (document.body).html ($ ('#textarea-id').html)
(Not tested)
Following your second option, you could trigger your script with a keyword to send the data as attachment.
Here’s an example of how it could look like:
if (isset($_GET['download'])) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;filename="dump.data"');
echo $data;
exit;
} else {
echo '<textarea>', htmlspecialchars($data), '</textarea>';
}
options:
TEXT ALREDY IN THE SERVER:
MAKE A GETFILE.PHP that reponse that text in a file.
TEXT IN THE CLIENT
POST THE TEXT TO A GETFILE.PHP and response the file.
POST THE TEXT TO A GETFILE.PHP, storage the file and provide a LINK to DOWNLOAD (then you could delete or not the file, depending of your needs)
Here is some example of this
http://www.osix.net/modules/article/?id=773
I'm new to PHP and I'm trying to do something that may be bad practise and may well be impossible. I'm basically just hacking something together to test my knowledge and see what PHP can do.
I have one webpage with a form that collects data. That is submited to a PHP script that does a bunch of processing - but doesn't actually display anything important. What I want is that once the processing is done, the script then tells the browser to open another page, where the results are displayed.
I know I can use header('Location: page.php'); but I can't work out how to provide POST data with this. How can I do that? Alternatively, is there another way to tell the browser to open another page?
EDIT: What I'm taking from the responses is that it's possible to do this using various hacks but I'd be better off to just have the processing and the display code in one file. I'm happy with that; this was an experiment more than anything.
You could store that data in the session e.g. in the first file that handles the post
session_start();
$_SESSION['formdata'] = $_POST; //or whatever
then you can read it on the next page like
session_start();
print_r($_SESSION['formdata']);
or you could pass it through GET: (but as per comments this is a bad idea)
header('Location: page.php?' . http_build_query($_POST));
If you do that make sure you do additional processing/validation on page.php as a malicious user could change the variables. also you may not need the whole post transmitted to the next page
Edit
I should make clear that I think the second option is possibly worse, as you are limited by the size of data you can send through get and it is possibly less secure as users can more obviously manipulate the data.
Is it really necessary to call another page after the processing is done? I'd probably do the following:
<form method="post" action="display.php">
...
</form>
display.php:
if ($_POST) {
require_once(process.php);
process($_POST);
display_results;
}
with process.php containing the code necessary for processing the post request.
Alternatively, you could use something like the cURL library to pass the results of the processing to a page specified by yourself. Don't know if that's really what you're after though.
You could use JavaScript as a dirty work-around:
<form id="redirect_form" method="post" action="http://someserver.com/somepage.php">
<input type="hidden" name="field_1" value="<?php echo htmlentities($value_1); ?>">
<input type="hidden" name="field_2" value="<?php echo htmlentities($value_2); ?>">
<input type="hidden" name="field_3" value="<?php echo htmlentities($value_3); ?>">
</form>
<script type="text/javascript">
document.getElementById('redirect_form').submit();
</script>
(the script should be below the form)
There's no way to redirect the user's browser to an arbitary page and sent a POST request. That would be a bit security risk, where any link could cause you to make any form submission to an arbitrary site without you having any kind of clue about what was going to happen.
In short, it's not possible
AFAIK this is usually done as a two-step process:
On form.php, POST the data to script process.php
The process.php script processes the data but never outputs anything itself, it always calls header("Location: asdasd") to redirect to a success.php or failure.php page (if applicable)
Do it all in one script and just output different HTML for the results.
<?php if($doingForm) { ?>
html for form here
<?php } else { ?>
html for results
<? } ?>
This problem has vexed me for some time. My custom CMS does some quite complex processing, uploading and manipulation, and so sometimes ouputs quite lengthy error and information messages, which aren't suitable for converting to GET data, and I have always wanted to avoid the reload problem on data INSERT, but not yet found an adequate solution.
I believe the correct way to go about this, is to create message arrays for each possible state - each message or error you could want to display, and then you only need to send error/message numbers which are a lot easier to handle than long data strings, but it's something I have always shied away from personally as I find it a bit tedious and cumbersome. Frankly, this is probably just laziness on my part.
I quite like the SESSION variable storage solution, but this raises the question of how do you ensure the SESSION data is properly destroyed?
As long as you ensure you are only sending information (messages/errors) and not data that should/could be stored (and thus potentially sensitive) this should be an avoidable problem.
I hope i got your qestion right.
You might try this:
Adjust your form to look like this:
form method="POST" action="process_data.php"
2.
Then you create the file process_data.php, wich surprisingly processes the data.
And in this file you use header:
For example:
$head = sprintf("page.php?data1=%d?data2=%d",$data1,$data2);
header($head);
I hope i could help.