PHP work with JS Jquery - php

How do i make PHP work with JS?
I mean more like, i want to check if the user is logged in or not,
and if he is then it will:
$("#message").fadeIn("slow"); ..
How should i do this?
I have an idea maybe have a file that checks it in php, and then it echo out 1 or 0.
And then a script that checks if its getting 1 then do the message fade in.. But im not as so experienced to script that in JS

You cannot directly pass variables from Javascript to PHP because the PHP run on the server before it's sent to the client. But you can 'pass' variables from PHP to Javascript.
For example:
echo('<script type="text/javascript'> var phpvar = '.$variablefromphp.';</script>');
However, you can manipulate what javascript your browser will print. You can first check if the user is logged in in PHP, and based on that, conditionally print the HTML and Javascript.
For example
if($user->logged_in())
{
echo('<script type="text/javascript">$("#message").fadeIn("slow");</script>');
}
else
{
//php function
generateLoginBox();
}

I only javascript to enhance user experience. You should make your application work even when javascript turned off.
With the javascript enabled, you can add an enhanced experience, such as animated page element, AJAX request, etc.
In case of login state, you should have a way to know it in PHP script. Then in the output, you can have a conditional block that only executed if the login state is true. You can put anything you want here.
Javascript can be working in a static HTML page. You can use this to create a simple test for the code that you wrote, to see if it working as you want. Read the documentation in http://www.jquery.com/, there are many links there to many examples.

Related

PhP reading script erros from console

i am trying to test if my script is loaded on a given website and if the script is actually working without any errors onload (later on i will have to do the same for onclick)
So far i have
$testResult = array();
$homepage = 'http://www.example.dk/';
$data = file_get_contents($homepage);
if (strpos($data,'example_script.js'))
{
$testResult['scriptLoaded'] = true;
print_r("win");
}else{
$testResult['scriptLoaded'] = false;
}
Now this loads the page and checks if the javascript is on the page. But how can i read from the console to check if there is any errors while loading the script?
Also is this the right way to check if the script is on the page? The only restriction i have is that i HAVE to use PHP.
The only thing you can check with your code is weather or not somewhere in the code/contents you've gotten from the given url, there is a string example_script.js. If you were to use the url to this page, you'd get true and "win", too, because the substring will be found.
The JS might be riddled with fauklts, but since PHP doesn't understand Js, you won't be able to see that.
If you want to test your site, without a browser, the only thing I can think of is using phantomjs:
Which can be found Here
Using PHP alone, you might be able to do a couple of checks using scriptable browser, cUrl, and the DOMDocument class (to parse and validate the markup).

How to secure the php code?

I created now a Javascript Code that get the php variable into javascript code, my issue that the php variable is important and I don't want any can see this variable is there is any way to do that by the way I tried to use obfuscator but it doesn't work because of the PHP code inside the Javascript code, let's say this is my Code,
<?php
$var = "this is impotant";
?>
<script type="text/javascript">
var javaScriptVar = "<?php echo $var; ?>";
</script>
So, is there any way to use PHP variables in Javascript code or hide the result of the PHP code?
Nobody sees the PHP code. But if you expose values into Javascript, they are not secret anymore. There is no way to deal with this. You cannot use the value in Javascript and NOT reveal it.
If you want to keep process data secret on the server, and available for the next request of that user, use a session.
People will only see the value of the variable. They wont know what it is or how important it is supposed to be. Nobody will see the variable name because the PHP code is executed BEFORE the page is sent to the client. Therefore there is no need to obfuscate the value, and you cant anyway since you need the value.
An example. if I use this PHP code in my file
<p>Hello Mr <?php echo $MY_SUPER_SECRET_VARIABLE ?></p>
the only thing people will be able to see in the source when the page loads is
<p>Hello Mr Bond</p>
The same rule applies if it is placed in Javascript
First you need to understand that Javascript is executed on the client side, every piece of code and variable are in some way accessible by someone with some programming background.
Although you can obfuscate the source code and encrypt the variable to make it harder to read, there is no 100% protection when things happen on client side.
who wants to get the value, will get it. but you can
dynamically inject them via ajax
encode (base64 etc.) the value
obfuscate the code
PHP files will be interpreted into static (like html or xml format) file, means that all variables will be replaced with certain values.What users see is static, no php code displayed but just interpreted text.

PHP session: two values are ALWAYS sent

I'm pretty new to PHP but trying to find my way which has worked quite well up till now.
Problem is the following: I have a website with 2 links. Both should redirect to the same second website but depending on the link clicked, some values should change. I was trying to use a PHP session for this.
Here is the code up to now:
Link 1:
<a href="<? echo $link ?>" class="helsinki" onclick="<? $_SESSION['clicked']= "helsinki"; ?>"^^Helsinki^^</a>
Link 2:
^^Seattle^^
Now if I try to read which link was clicked on the next side like this:
<? if(isset($_SESSION['clicked']))
echo "clicked ". $_SESSION['clicked'];
?>
I always see "Seattle", Helsinki never appears although (I thought) I input Seattle if the Seattle link is clicked. Apparently it's not like that... Can anyone help me here?
This is because PHP code is server side, and thus executed at the time of the page request. So $_SESSION['clicked'] is set to helsinki then reset to seattle at the time your first page loads. You may want to use $_GET variables instead of $_SESSION variables.
Wait wait wait a second: PHP is "server-side", javascript is "client-side". That means you will ALWAYS execute PHP before javascript.
What you are trying to achieve can be simply done with a GET variable:
^^Seattle^^
^^Helsinki^^
And than in the second site you can get the value of our parameter:
$city = $_GET['city'];
Not sure if this is useful, but you could create a "redirector". It takes the user to a server side page that will redirect them to the final page and at the same time change the session.
The page:
...
...
The code for redirector.php:
<?php
session_start();
// determine where to redirect user (could be done with database or array of options)
switch ($_GET['link']) {
case 'helsinki':
header('Location: /link/to/helsinki');
break;
case 'seattle':
header('Location: /link/to/seattle');
break;
default:
return;
}
$_SESSION['clicked'] = $_GET['link'];
You're mixing up Javascript and PHP.
PHP is server side, that means that all PHP code is parsed and executed on the server side, and then is sent to the client.
So if you write
line #1: ^^Helsinki^^
and then
line #2: ^^Seattle^^
the value of $_SESSION['clicked'] is always first "Helsinki" (line #1), but then immediately overwritten by "Seattle" (on line #2).
In order to achieve what you want the script to achieve, is, for example, as follows:
^^Helsinki^^
^^Seattle^^
and then catch the sent variables from the PHP variable $_GET:
if (isset($_GET['location'])) {
if ($_GET['location'] == "helsinki") {
// Whatever
}
elseif ($_GET['location'] == "seattle") {
// You want
}
}
"^^Helsinki^^
"^^Seattle^^
and use $_GET['location'] at the other page to check weather it is helsinki or seattle.
$link should be the same for both links.
Also you can't mix PHP (server-side) with Javascript (client-side). Look it up for why that is.
You cannot write PHP code in the onclick event. If you want to do it like that, you should use Javascript/AJAX. Even if you do it like that, you won't still get the result as you desire, since AJAX request will delay some seconds.
I think the right way to do this kind of thing is like below:
Helsinki"
and this is the change_city.php:
<?php
$_SESSION["clicked"] = $_GET["city"];
?>
if you want to still use the $link, then you just put this above code top of your PHP file.

does a PHP page with includes get compiled and sent as one page?

I have a PHP page where the header and footer are PHP includes.
I want to know if there is any possibility of the includes loading asynchronously - or does PHP gather all the files required, compile them and send them as one file?
The reason I ask is that I've seen an interesting PHP app that seemed to keep the connection open and do things in sequence before closing the connection - I wondered if that's what happens with includes.
PHP version is 5.3.6
EDIT:
What I actually want is for the page to load all at once, to prevent my layout mashing as each bit loads. Sorry to any who misunderstood this
PHP does gather and compile them; everything goes to the browser as a single document. If you don't want this, you'll have to do something with XMLHTTPRequest on the frontend
Generally any output will be output as it is generated.
echo 'A';
sleep(1000);
echo 'B';
sleep(1000);
echo 'C';
This slowly outputs "ABC". Includes are included when they are encountered, the same way echo outputs anything at that specific point. It's all in order, never asynchronously.
A web server may buffer all output before sending any of it to the client. In the above example, you'd receive "ABC" all together after 2 seconds of nothing.
If your objective is to receive all the page at once you need to use ob_start() and ob_end_flush(). Do something like:
ob_start();
...
write all your outputs
...
ob_end_flush();
This will force the server to buffer the output until the whole page is prepared.
Good luck!
I use the following architecture when loading a page on my application:
index.php
<script src="path/to/js/lib/jslib.js" type="text/javascript"></script>
window.addEvent('load', function()
{
BuildPg(PgStatus); //PgStatus is a variable I use in a state machine to build different pages
});
<form>
<div id="DivPgTop"></div>
<div id="DivPgMiddle"></div>
<div id="DivPgBottom"></div>
</form>
This is the entire index.php
In my jslib.js I have functions like:
function BuildPg(Pg) {
BuildPgTop(Pg);
BuildPgMiddle(Pg);
BuildPgBottom(Pg);
}
function BuildPgTop(Pg) {
var Content="";
if (Pg == 1) {
Content = function_a(); // function_a builds the top of the page
else if (Pg == 2) {
Content = function_b();
etc...
}
document.getElementById("DivPgTop").innerHTML = Content; //here is where I load the top of the page
}
And I do the same for the other parts of the page Middle and Bottom.
Using this framework, if you changed my BuildPg() function to something like:
function BuildPg(Pg) {
BuildPgTop(Pg);
sleep(foo);
BuildPgMiddle(Pg);
sleep(bar);
BuildPgBottom(Pg);
}
Your user would experience the top of the page loading first, a delay, the middle of the page, another delay, and the bottom.
And if you change the order of the function calls you could even have the bottom of the page load first, then the middle and the top.
I hope this makes sense. Good luck!
PHP sends a single document. What you want to do is achieved with something called AJAX (http://en.wikipedia.org/wiki/Ajax_%28programming%29)
Basically you write some JavaScript code that uses XMLHTTPRequest object to connect to the server and download some extra info.

How can I generate Dynamic Javascript?

I render a page using YUI. and depending on the user I need to change how it is rendered. This change is not something that can be parametrized, it is drastic and different for each user.
Please tell me how can I generate Javascript dynamically?
I personally use a PHP file to pass a JavaScript object made up of some basic session and internal settings, nothing mission-critical as passing information to the client isn't overly secure, but I believe it might follow the same principles as what you are looking for.
Similarly, I use this to display certain elements once the client is logged in, although all the authorization is still done on the server-side. If my session handler gives the PHP file the ok, it outputs a JavaScript object using a PHP heredoc string, otherwise, it doesn't output anything. You can use attributes of this object to compare against, or you could output only the JavaScript for how a certain page should be rendered, based on settings in your PHP file.
HTML:
<script src="common/javascript/php_feeder.php" type="text/javascript"></script>
PHP:
//my session handler authorisation check has been removed
//although you could place your own up here.
//assuming session was authorised
//set content type header
header("content-type: application/x-javascript");
$js_object = <<<EOT
var my_object = {
my_attr: '{$my_attr}',
my_attr2: '{$my_arrt2}',
etc: '{$etc}'
}
EOT;
print($js_object);
You can probably create two separate Java script files, and include the required file, depending upon the user type.
Pseudocode
If user_type is One
<Script src='one.js' type='javascript'></script>
else
<Script src='other.js' type='javascript'></script>
End If
JavaScript has an eval function, so I think (I haven't tried it) that you can generate JavaScript by writing it into a string variable (and then calling eval on that string variable).
A little bit of elaboration here would most certainly help in getting you a more descript and helpful answer. That in mind, though, you could easily just use functions declared inside an if statement to provide distinctly varied experiences for different users.
A very basic example:
<script>
function do_something(userType)
{
if (userType == 'A')
{
// everything you need to do for userType A
}
if (userType == 'B')
{
// everything you need to do for userType B
}
}
</script>

Categories