What about calling aspx in php? - php

Here is my code
<html>
<body>
<?php
include("Default.aspx");
?>
</body>
</html>
but it keeps giving me the output of
<%# Page Language="C#"
AutoEventWireup="true"
CodeFile="Default.aspx.cs"
Inherits="_Default" %> <%
Response.Write("Hello world!"); %>
I just need to run the Hello World on the site.

If you want the output of the aspx file, you will need to request it via a web server which can understand aspx files rather than the file system, e.g.
include("http://example.com/Default.aspx");
Your PHP installation must have URL fopen wrappers enabled for this to work.
As Magnus Nordlander notes in another answer, you should only use include if you expect to find php code in the file. If you don't, you could simply use readfile to output the data verbatim:
readfile("http://example.com/Default.aspx");

You seem to be going about this in a very wrong way.
What include() (and require(), for that matter) does is that it parses the specified file with the PHP interpreter. If your aspx-code for some reason generates PHP-code, which is supposed to be parsed by the PHP interpreter, then the way Paul Dixon suggests would be the right way of going about this. However, I would strongly advice against doing this.
For one thing, it's a huge security disaster waiting to happen. It's also incredibly bad architecturally speaking.
If you want to include HTML markup etc. generated using aspx, what you should do is to use
echo file_get_contents("http://www.example.com/Default.aspx");
This way, any PHP code in the output remains unparsed, thus avoiding the aforementioned security disaster. However, if you're able to do without mixing languages like this, that's probably going to be a much better solution.

Related

Are there any limitations on where PHP code can go inside a file?

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.

search-and-replace on PHP code before it is executed

Is there a way to perform search and replace on PHP code before it is interpreted by PHP engine ?
Desired timeline:
PHP code is <?php echo("hello"); ?>.
Search and replace operation is hello → good bye
PHP code is now <?php echo("good bye"); ?>.
PHP engine interprets the code (output is good bye).
It is possible to manipulate the output of the PHP engine, using ob_start or even mod_substitute as an output filter of Apache. However, is it possible to manipulate the input of the PHP engine (PHP code, request, etc)?
Edit:
I'm working with thousands of PHP files and I don't want them to be modified. I would like to replace host1 with host2 in these files, since the files were copied from host1 and they have to be executed on host2. Indeed, several tests are made on the host name.
You could use a php script that opens a .php file, makes the necessary replacement, then includes that file.
Request is unusual)
Looks stupid. But if you really need it try this..
For example you need to change file test.php before execute it.
Try following steps (in index.php for example):
1) Open test.php for reading and get its content.
2) Replace everything you want.
3) Save changed text as test2.php
4) Include test2.php.
EDIT
Better thin why you need it? Try using variables.
It will help)
You should study template engines like smarty and various forms of prefilters.
Modifying code like this isn't good idea, however to answer your question... You may load original code, preprocess it and store in new file:
$contents = file_get_contents( 'original.php');
// ...
file_put_contents( 'new.php', $contents);
include( 'new.php')
But I don't see any valid use of this...
You also may possibly use eval() but every time you do that a kitty dies (no really, it's dangerous function and there's really just a few valid uses of it).

Custom stream wrapper with include or eval?

Overview
I'm currently writing a template engine. It even supports multiple "format"s. Currently it can parse .php files and .tpl (specific to this engine).
I'll give you a little example of both, just to give you an Idea.
template.php:
Name: <?php echo $this->h($name) ?>
Posts:
<?php foreach($posts as $post): ?>
- <?php echo $this->h($post->name) ?> (<?php echo count($post->comments) ?> comments)
<?php echo $this->render('post/shortpost', array('post' => $post)) ?>
<?php endforeach ?>
This is basicly just a standard PHP.
template.tpl
Name: {>$name}
Posts:
{foreach($posts as $post):}
- {>$post->name} ({=count($post->comments)} comments)
{=:render('post/shortpost', array('post' => $post))}
{endforeach}
This templating "language" simply gets translated into PHP above.
Comparission
eval()
Currently these template's are parsed using eval().
Pro
I don't have to change any code
Contra
when an error occurs in a template you only get a useless error message which doesn't
tell you in which file the error occurs and sometimes the line number is even wrong.
Security? Template files are only need to be readable?
It's difficult to debug the code.
Code is harder to understand
more .. ?
stream wrappers and include()
I recently read about stream wrappers in php. You even could create your own. A other solution than eval would be to create a custom stream wrapper for every template "format" and use include to parse the template.
This has the following (potential) flaws:
Pro
may solve the problems with showing the wrong file/line-number in error messages (has anyone experiences with this?)
you could handle the template file exactly how to want it to be handled. Full control.
Contra
allow_url_(fopen|include) has to be on?
it is slow? (is eval() slow too?)
no gain in security. include does basically the same thing as eval.
more ... ?
EDIT: cached parsed files and include()
A third option would to to parse the template to PHP code and cache them (as suggested by #Jen-YaKovalev).
Pro
includes caching
Contra
if an error occurs while including the rendered template and an error occurs
the error message doesn't point you to the correct file/eventually shows you
the wrong line number.
You need an extra tmp/ directory to save the parsed files. You need write
permissions for PHP/webserver. Would be more insecure because hackers
would append some malicious code easier.
EDIT: stream filters and include('php://filter')
lately found the following php.net pages:
php://filter: http://php.net/manual/en/wrappers.php.php
strea_filter_register http://fr2.php.net/manual/en/function.stream-filter-register.php
This would be an other possibility to solve this problem. Using include('php://filter/read=filtername/resource=file.php'), I could include a file which would first go through the filter filtername, before it gets executed.
Pro
doesn't need so much code as stream wrappers
Contra
not so much possibilities as with stream wrappers (caching?)
security?
speed?
Question
Have experiences using stream wrappers for parsing template files or similar?
Is there yet an other solution?
Are there more pro's and contras?
Which one would you recommend?
I think it's just a taste of one's coding-style, you'd better vote it or something.
I personnaly think eval is evil (in every language),
had bad experiences with include + php wrappers (even integrated ones*),
knowing all big(gish) template systems use compiling to a php file (smarty, twig), this it the one, i would use.
(*) In an earlier project we used a 1-line code (an empty class-extension) in a data-url wrapped include, and its performance was awful.
You certainly don't want to parse templates at every request on the production environment, it would be a waste of resources and consequently a slow and not a very smart approach, so I'd strongly suggest going with the cached parsed files and include() approach.

Why is javascript not able to use a javascript variable I declared in a php file?

Hey everybody, this issue has had me stumped for the last week or so, here's the situation:
I've got a site hosted using GoDaddy hosting. The three files used in this issue are index.html , milktruck.js , and xml_http_request.php all hosted in the same directory.
The index.html file makes reference to the milktruck.js file with the following code:
<script type="text/javascript" src="milktruck.js"></script>
The milktruck.js file automatically fires when the site is opened. The xml_http_request.php has not fired at this point.
On line 79 out of 2000 I'm passing the variable "simple" to a function within the milktruck.js file with:
placem('p2','pp2', simple, window['lla0_2'],window['lla1_2'],window['lla2_2']);
"simple" was never initialized within the milktruck.js file. Instead I've included the following line of code in the xml_http_request.php file:
echo "<script> var simple = 'string o text'; </script>";
At this point I have not made any reference whatsoever to the xml_http_request.php file within the milktruck.js file. I don't reference that file until line 661 of the milktruck.js file with the following line of code:
xmlhttp.open('GET',"xml_http_request.php?pid="+pid+"&unLoader=true", false);
Everything compiles (I'm assuming because my game runs) , however the placem function doesn't run properly because the string 'string o text' never shows up.
If I was to comment out the line of code within the php file initializing "simple" and include the following line of code just before I call the function placem, everything works fine and the text shows up:
var simple = 'string o text';
Where do you think the problem is here? Do I need to call the php file before I try using the "simple" variable in the javascript file? How would I do that? Or is there something wrong with my code?
So, we meet again!
Buried in the question comments is the link to the actual Javascript file. It's 2,200 lines, 73kb, and poorly formatted. It's also derived from a demo for the Google Earth API.
As noted in both the comments here and in previous questions, you may be suffering from a fundamental misunderstanding about how PHP works, and how PHP interacts with Javascript.
Let's take a look at lines 62-67 of milktruck.js:
//experiment with php and javascript interaction
//'<?php $simpleString = "i hope this works"; ?>'
//var simple = "<?php echo $simpleString; ?>";
The reason this never worked is because files with the .js extension are not processed by PHP without doing some bizarre configuration changes on your server. Being on shared hosting, you won't be able to do that. Instead, you can rename the file with the .php extension. This will allow PHP to process the file, and allow the commands you entered to actually work.
You will need to make one more change to the file. At the very top, the very very top, before anything else, you will need the following line:
<?php header('Content-Type: text/javascript'); ?>
This command will tell the browser that the file being returned is Javascript. This is needed because PHP normally outputs HTML, not Javascript. Some browsers will not recognize the script if it isn't identified as Javascript.
Now that we've got that out of the way...
Instead I've included the following line of code in the xml_http_request.php file: <a script tag>
This is very unlikely to work. If it does work, it's probably by accident. We're not dealing with a normal ajax library here. We're dealing with some wacky thing created by the Google Earth folks a very, very long time ago.
Except for one or two in that entire monolithic chunk of code, there are no ajax requests that actually process the result. This means that it's unlikely that the script tag could be processed. Further, the one or two that do process the result actually treat it as XML and return a document. It's very unlikely that the script tag is processed there either.
This is going to explain why the variable never shows up reliably in Javascript.
If you need to return executable code from your ajax calls, and do so reliably, you'll want to adopt a mature, well-tested Javascript library like jQuery. Don't worry, you can mix and match the existing code and jQuery if you really wanted to. There's an API call just to load additional scripts. If you just wanted to return data, that's what JSON is for. You can have PHP code emit JSON and have jQuery fetch it. That's a heck of a lot faster, easier, and more convenient than your current unfortunate mess.
Oh, and get Firebug or use Chrome / Safari's dev tools, they will save you a great deal of Javascript pain.
However...
I'm going to be very frank here. This is bad code. This is horrible code. It's poorly formatted, the commenting is a joke, and there are roughly one point seven billion global variables. The code scares me. It scares me deeply. I would be hesitant to touch it with a ten foot pole.
I would not wish maintenance of this code on my worst enemy, and here you are, trying to do something odd with it.
I heartily encourage you to hone your skills on a codebase that is less archaic and obtuse than this one before returning to this project. Save your sanity, get out while you still can!
perhaps init your values like this:
window.simple = 'blah blah blah'
then pass window.simple
You could try the debugger to see what is going on, eg. FireBug

What are the advantages to putting your Javascript in a .php file?

I occasionally come across pages where some Javascript is included via a PHP file:
<html>
<head>
<script type="text/javascript" src="fake_js.php"></script>
</head>
<body onload="handleLoad();">
</body>
</html>
where the contents of fake_js.php might look something like this:
<?php header('Content-type: text/javascript') ?>
function handleLoad() {
alert('I loaded');
}
What are the advantages (or disadvantages) to including Javascript like this?
It makes it easy to set javascript variables from the server side.
var foo = <?=$foo?>
I usually have one php/javascript file in my projects that I use define any variables that need to be used in javascript. That way I can access constants used on the server-side (css colors, non-sensitive site properties, etc) easily in javascript.
Edit: For example here's a copy of my config.js.php file from the project I'm currently working on.
<?php
require_once "libs/config.php";
if (!function_exists("json_encode")) {
require_once "libs/JSON.php";
}
header("Content-type: text/javascript");
echo "var COLORS = ". json_encode($CSS_COLORS) .";\n";
echo "var DEBUG = ". ((DEBUG == true) ? "true" : "false").";";
?>
If you don't need it, don't use it:
The first thing you need to keep in
mind is YAGNI. You Ain't Gonna
Need It. Until a certain feature,
principle, or guideline becomes useful
and relevant, don't use it.
Disadvantages:
Added complexity
Slower than static files.
Caching problems (server side)
Scalability issues (load balancers offload static files from the heavy PHP/Apache etc processes)
Advantages:
User specific javascript - Can be achieved by initializing with the right variables / parameters in the <head> </head> section of the HTML
Page specific javascript - JS could also be generalized to use parameters
JSON created from database (usually requested via AJAX)
Unless the javascript is truely unique (i.e. JSON, parameters/variables) you don't gain much. But in every case you should minimize the amount of JS generated on the server side and maximize the amount of code in the static files. Don't forget that if it's dynamic, it has to be generated/downloaded again and again so it's not wanted for it to be a heavy process.
Also:
This could also be used to minimize the amount of server configuration (for example if the web server doesn't serve file.js with the correct content type)
There's no benefit for the example you gave above (beyond peculiar deployment scenarios where you have access to .php files and not .js files, which would be insane but not unheard of).
That said, this approach allows you to pass the JS through the php parser - which means you can generate your JS dynamically based on server variables.
Agree with tj111. Apart from what tj mentioned, I also found php-generated javascripts a great weapon to fight the browser's caching tricks. Not that long ago I was cursing the whole javascript for its being constantly cached by the browser. Refreshing the page helped me not, had to clear the whole cache in order to force the browser to reload the javascript files. As soon as I built a php wall in front of my javascripts:
fake_js.php:
<?php
header('Content-type: text/javascript')
include('the_real_javascript.js');
?>
A fresh new javascript would always show up at the client side. However this approach is obviously only good in the development phase, when it can save the developer quite some headache to have the correct javascript loaded in the browser. Of course when connecting to localhost, the penalty of repeatedly loading the same file is not as big.
In a live web application/site client-side caching is welcome to reduce network traffic and overall server load.
Advantage (not PHP specific - I used this technique in EmbPerl and JSP) would be the ability to dynamically generate or tweak/customize the JavaScript code on the server side.
An example usage would be population of an array based on the contents of a DB table.
Or application of localization techniques.
If you don't have full server access and can't turn on gzip encoding then it's pretty useful to put the following in your javascript file (note: will need to be renamed to file.js.php or parsed as PHP through .htaccess directive):
<?php
ob_start( 'ob_gzhandler' );
header("Content-type: text/javascript");
?>
// put all your regular javascript below...
You could also use it for better cache control, visitor tracking, etc in lieu of server-controlled solutions.
Absolutely none, IMHO. I use a js framework that I wrote to handle the setting of whatever server-side variables I need to have access to. It is essentially the same as embedding PHP in JavaScript, but much less ambiguous. Using this method allows you to also completely separate server-side logic and html away from javascript. This results in much cleaner, more organized and lowly-coupled modular code.
You could do something like this in your html:
<script type="text/javascript">
registry = {
myString : '<?php echo $somePhpString; ?>',
myInt : <?php echo $somePhpInteger; ?>
}
</script>
And then do something like this in your js:
if (registry.myInt === 1) {
alert(registry.myString);
}

Categories