Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
$('#tip2').qtip({
content: {
text: '<?php echo "I do work."?>'
},
In this case I'm using a jquery plugin but that doesn't matter for the question I believe.
I thought I had to go trough json calls (or other ajax call methods) because php runs first, and only later runs javascript, but, I actually tested this code, and it actually displays the text.
Can anyone please take some words to explain, on what circumstances should we NOT use php inside javascript. Is this one of them? If so, why?
I'm clearly not getting some client side, and server side workflow... please forgive my newbielity towards those matters.
Sorry if this was an inconvenient question.
Update
Please note that I'm asking about facts. Not opinions.
Someone states:
"You shouldn't do that way."
I'm asking:
"What facts (not opinions) sustain that claim?"
It might be sensible to externalise most, if not all, of your JavaScript to another, static file for caching reasons.
It is possible to have a PHP file generate JavaScript, but as all dynamic content, it can not cache as well (while you can set-up caching headers, changes to the generated content will not be immediate, so you'll be forced to find a compromise between content accuracy and bandwidth savings).
I would externalise your example as so:
$('#tip2').qtip({
content: {
text: my_var
},
Then create the following <script> block in your dynamic file before linking the static one:
my_var = '<?php echo 'I do work'; ?>';
This way, the vast majority of your JavaScript will be static, and eligible for Max-Age caching.
To provide you with a real-world example, I have recently implemented a pure JS plotting library that draws discrete data onto a canvas. The data to be plotted is supplied by the CGI (I didn't use PHP, but it shouldn't matter), so I used this approach to declare an array of values in the dynamic file, while externalising the actual handling and drawing code. It works beautifully, uses minimum bandwidth due to caching nicely, and is still very maintainable.
Unlike some other answers, I won't say you should avoid mixing server-side code with client-side; hell, HTML is client-side code that you are generating server-side. Depending on your needs, mixing JS and CGI can extend your possibilities, and applying my caching trick, there is no real downside.
A php file is interpreted by the web server and converted to a pure html file. That html file is then passed to the client's browser, which displays it.
In your case, the php echo is rendered as a string in the html page.
Keep in mind that if you do what you did in your example, the values rendered to the page are the values that exist when the page is rendered by php.
You should try not to use it as much as possible. However, there might be some very rare cases when you do need to pass values from your PHP code (say from a $_SESSION array) into your jQuery/JavaScript functions. In that case, if you don't have any other option then you can pass values like you did above. But in all other cases, try not to do it as much as possible since it is not a good practice. When you are combining 2 different languages like this, there might be cases when you get unpredictable behavior from the application/web-page.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I need to crawl a website and detect how many ads are on a page. I've crawled using PHPCrawl and saved the content to DB. How can I detect if a web page has ads above the fold?
Well simply put: You can't really. At least not in a simple way. There is many things to consider here and all of them are highly subjective to the web page you are crawling, the device used, etc. I'll try to explain some of the main issues you would need to work around.
Dynamic Content
The first big problem is, that you just have the HTML structure, which on itself gives no direct visual information. It would be, if we were in like 1990, but modern websites use CSS and JS to enhance their pages core structure. What you see in your browser is not just HTML rendered as is. It's subject to CSS styling and even JS induced code fragments, which can alter the page significantly. For example: Any page that has a so called AJAX loader, will output as a very simple HTML code block, that you would see in the crawler. But the real page is loaded AFTER this is rendered (from JS).
Viewport
What you described as "above the fold" is an arbitary term, that can't be defined globaly. A smartphone has a very different viewport than a desktop PC. Also most of modern websites use a very different structure for mobile, tablet and desktop devices. But let's say you just want to do it for desktop devices. You could define an average viewport over most used screen resolutions (which you may find on the internet). We will define it as 1366x786 for now (based on a quick google search). However you still only have a PHP script and an HTML string. Which brings us the next problem.
Rendering
What you see in your browser is actually the result of a complex system, that incooperates HTML and all of the linked ressouces to render a visual representation of the code you have crawled. Besides the core structure of the HTML string you got, any resource linked can (and will) chanfge how the content looks. They can even add more content based on a variety of conditions. So what you would need to get the actual visual information is a so called "headless browser". Only this can give you valid informations about what is actually visible inside the desired viewport. If you want to dig into that topic, a good starting point would be a distribution like "PhantomJS". However don't assume that this is an easy task. You still only have bits of data, no context whatsoever.
Context, or "What is an ad?"
Let's assume you have tackled all these problems and made a script that can actually interpret all the things you got from your crawler. You still need to know "What is an ad?". And thats a huge problem. Of course for you as a human it's easy to distinquish between what is part of the website and what is an ad. But translating that into code is more of an AI task than just a basic script. For example: The ads could (and are most of the time) loaded into a predfined container, after the actual page load. These in turn may only have a cryptic ID set that distinguishes them from the rest of the (actually valid) page content. If you are lucky, it has a class with a string like "advertisment", but you can't just define that as given. Ads are subject to all sorts of ad blockers, so they have a long history of trying to disquise themselves as good as possible. You will have a REALLY hard time figuring out what is an ad, and what is valid page content.
So, while I only tackled some of the problems you are going to run into, I want to say that it's not impossible. But you have to understand that you are at the most basic entry point and if you want to make a system that is actually working, you'll have to spend a LOT of time on finetuning and maybe even research on the AI field.
And to come back to your question: There is no simple answer for "How to detect if a page has ads". Because it is way more complex than you might think. Hope this helps.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have a form which has a textarea input. This text area will have some custom "tags" that I would like to make, similar to the * operator in SO's textarea which gets processed and interpreted as italics or bold depending on how it's used.
The end goal is to process this long string of text, make any formatting modifications needed, then write it to a database table. I'm not really sure how to approach this problem, however.
My first thought was to use $_POST, but I'm unsure it it's a good idea to store very large strings in this array as I cannot find any information as to how much data it is good to store in this array. Is there some best practice for transferring large amounts of data to another page? Should I be using jQuery for this? If so, how?
$_POST will most likely be used, whether or not you do this with jQuery. The default limit of $_POST is already high enough to handle most user input, short of file uploads. If you need it to be greater than 8MB, you can change that on the webserver in your php.ini file. I've had a similar application, and in testing I had no problem pasting >64MB into my textarea.
I would also consider changing the order of operations a little bit. I'd do one or the other of the following:
1) Rather than format your text prior to db insertion, format it on the way back out to the browser. That way, if you change the way your input gets formatted, you have the original data to apply it to. It's a little more work for the server when displaying the data, but it's likely you'll have a much easier time maintaining your application down the line.
2) Store both the formatted text and the raw text in the database. This has the benefit of speed by not having to format it on its way to the user every time it's called, and also allows you the ability to build a means of changing the format of the data later, at some coding expense.
EDIT: As pal4life stated in a comment, you want to avoid executing any of the user input. Essentially, if your method is to save the input to a file, and then recall it with an include() or require(), you open yourself up to some severe security vulnerabilities. An attacker could upload code like <?php var_dump($conn); or much worse. I believe you may safely readfile(), however the browser is still vulnerable to any potential javascript that may have been placed there by an attacker.
Using $_POST is a pretty good way to start, if it's getting bigger then 8MB change the php.ini. If it's getting much larger you can start slice your string and send the chunks via jQuery to your web server and concatenate them afterwards.
But at the first run I would prefer with the standard way and use $_POST.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a series of articles in files that are included in dynamic pages. I would like delete all the files and put the content in a database.
However, some of the articles include PHP code. I was surprised to learn on a recent thread that you can put PHP code in a MySQL database table. However, I forgot to ask how to do it. Can someone show me how you would modify the following text (which includes an echo value and an include) so that it can be stored in a database table?
<p>Mammals and reptiles evolved from a common ancestor.</p>
<h3><a name="Internal" id="Internal"></a><?php echo $EvoHeader; ?></h3>
<?php require_once($BaseINC."/AContent/Child/Life/Features/Classification/Order/Mammals.php"); ?>
<p>Evolution continues today.</p>
I see that nobody addresses how to run that code once you fetch it, but only how to escape it, etc... I don't think OP needs PHP snippets to show them on the page, but to run them.
If you want to run the PHP code after you fetch it from the database, you can use eval. But I strongly suggest you don't do it. There are millions of articles about it and why it's not safe. So, unless you're 110% sure you know what you're doing, don't do it.
However, since I doubt you'd need a dynamic code within a dynamic piece of code, I suggest you put the rendered version of every page into the database. This means that you take the output of each file, including whatever those php lines output (with their echoes and includes), and store it all together like that. If you still need some dynamic code within that (like maybe the logged user's name, or the current date, etc.), I'd suggest you add those after you fetch the data from the database, either by setting flags, making exceptions, whatever works.
The bottom line: use your database for content, settings, etc... do not use it for running code from it even though there are ways to do it.
Nice answers about eval: When is eval evil in php?
You might also find this topic interesting (no matter it's about Drupal): https://drupal.stackexchange.com/questions/70297/php-in-database-bad-practice-but
PHP code is just ordinary text as far as the database is concerned.
The issue isn't putting it in some special format, but escaping it properly. The best way is to use prepared statements, via MySQLi or PDO. You can also use mysqli_real_escape_string().
Edit: Based on your comment, it sounds like you are doing something like this: get the code from the database, then echo it. You're right, that will result in it being output as text. You would have to execute it with eval() or something, which is a very bad idea. As others have pointed out, this is not an ideal way to store PHP code; it will be hard to maintain, open up some security problems, probably result in naming conflicts, and generally introduce more headaches than it resolves.
If we forget that php code is only a text, and you just want not to save normal php code into your database, You can first serialize your php code, and then insert it into your database. While fetching your php code from database in future, you can unserialize it.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
If I'm hosting a website on a server that has PHP, would I ever need to host a .html file on it? PHP files can have raw HTML code inside of them as well as the added benefit of being able to inject PHP code, so isn't PHP a more inclusive language?
Serving HTML is generally a lot easier for the webserver than serving a page that has to be run through the PHP interpreter.
This can have huge benefits on high-traffic sites. For example, the Obama campaign ran their fundraising platform with a lot of static HTML for that reason.
it always can be situation that you would need to add e.g. maintenance page in pure html
It's not a question of whether you can simply make everything "a PHP file" but rather a question of whether any given file needs to be PHP. If a file contains only static content, there's no need for any server-side processing. So in such cases it would make more sense to make it an HTML file.
Don't look for a tool that covers all cases, look for the right tool for each case.
I read that it is recommended to have <?php flush(); ?> between </head> and <body>. I would assume that this should apply to every webpage, there really isn't a solid reason as to why you would only use HTML.
I agree with ceejayoz, but if that's not a problem for you, then using PHP is great.
It depends on your purpose. If your page uses PHP then the file extension needs to end in .php. If you don't have any PHP then you can just save the page with a .html file extension. A major difference is that PHP is processed on the server side. Meaning the user(client) will not see your PHP code if he views the source, he'll see what was processed from the server in the form of HTML.
One advantage of using .php files over HTML (in this trivial case) is that, you can wrap up all your footer files(if the are the same) or any redundant files, like sidebar, advertisingand just include them in your other files, instead of having to create/manage individual files later, So, you can just open one footer.php file and make as many changes as you want without wasting any time.
Your basic understanding is correct. You can absolutely have a .php file that has only HTML in it and given a simple page and a simple site there would be little difference.
However, the PHP preprocessor adds a bit of overhead to check for PHP code in the file. In most cases this is insignificant, but on a highly optimized site you probably would not want the pages to be processed for nothing.
I wouldn't say that PHP is a more inclusive language though, HTML and PHP are two different things. In many cases (but by no means all) PHP generates HTML. It's just that the resulting HTML from a PHP script that has no PHP tags in it would most likely be the same as it would be for an html file. Although it is likely that HTTP Response Headers would be different and there are other things outside of the file content itself that could be slightlu
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to know how to create a language like PHP. How does the server know how to translate a PHP file? How does it work? I want to do this for educational purposes. A simple language with basic features like echo, etc.
In basics, when webserver get's request to process php file it translating this request to php processor, it could be a module (like php.so in apache) or service (like php-cgi). Service or module compiles php script to machine code, executes it and gives the server the result of his job. You can download php source code from http://php.net. Source code include parser, thanslator, compiler and other components needed to execute php script as machine code
Divide your task in at-least two top level parts:
PHP as just another programming language - you need a lexical analyzer, parser and interpreter.
Libraries and modules for web servers likt Apache/TomCat to inteface with PHP.
This is a very big question. And not one which can really be answered here, but a few pointers to get you started...
PHP exposes some of its inner workings - if you have a look at:
<?php
$srctokens=token_get_all(file_get_contents(__FILE__));
print "<pre>\n";
foreach ($srctokens as $tok) {
print token_name($tok[0]) . ' -> ' . $tok[1];
}
?>
You'll see that it splits the code up into 'words' and assigns meta-data to each one (is it a function name, a variable, an operator...).
It then builds this into a tree structure, e.g. an 'if' statement might have three child nodes - an expression to evaluate (which itself would have child nodes), some code to evaluate if the expression is true, and some code to evaluate if the expression is false.
Typically it will use a set of built-in functions to read in data from the outside and to push data to the outside world.
Wikipedia or google are usually good starting points for finding out about stuff you don't know.
Its worth noting that because its an interpreted language, its simple to create executable code from PHP datastructures using eval() or create_function() (or just using temporary files). Indeed you could even implement a structured rewriting system such that the original data looks nothing like PHP code. e.g. lolcode
But you need to be very careful that you don't expose this mechanism to someone who might abuse it.
HTH
You could also write it in PHP, like BobX. Please note, BobX is actually an example of what NOT to do.