changing a js file location only when the source-code is showed - javascript

i'm trying to change a js file location when a visitor shows the source-code
, depending on that :
javascript functions don't work when the visitor shows the source-code
.
my idea is creating a file , put a javascript code to delete the file , in this situation the file won't be deleted if someone showed the source-code :
$check="$ip-$views-$id";
fopen("$check.txt","w"); //CREATING A FILE
// DELETING THE FILE ABOVE BY JAVASCRIPT , IT WON'T BE DELETED IF SOMEONE ENTERED VIA THE SOURCE-CODE MODE
?>
<div id="countno"></div>
<script type="text/javascript">
$('#countno').load('del.php?name=<?echo $check;?>&location=' + ' #countno');
</script>
<?
if (file_exists("$check.txt")) { //IF SOMEONE SHOWED THE SOURCE CODE
$new_location="fake_location.js";
}
else{
$new_location=$old_location;
}
?>
<script src="<?echo $new_location;?>"></script>
the problem now , is that the file_exists php function shows that the file still exists even though it was already deleted by the javascript code .
the file_exists function was executed before the javascript code !
any help / solution to make that php function check the file after that javascript code ? i know it's kinda impossible but it worth it !

What you are describing is not possible. php is a server side language while javascript is a client side language. Thus, the PHP on your page will always execute before the Javascript on your page executes. There is no way to make your Javascript execute first when you have it this way.
Instead, what you could do is to separate the PHP and Javascript. Have your file_exists check in another page. e.g. check.php.
if (file_exists("$check.txt")) {
echo "fake_location.js";
} else {
echo $old_location;
}
Then use an ajax call to make a request to check.php, and load your other script depending on what check.php outputs.
<script>
$.ajax({
method: "GET",
url: "check.php"
})
.done(function(script) {
$("#check").attr("src", script);
});
</script>
<script id="check"></script>
However, if your goal is to prevent people from figuring out where your javascript is located, it is not possible. Most browsers nowadays can inspect the HTML as it changes. They can see the loaded script without having to load the source separately.

Related

Why does the PHP file not read the javascript properly? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I'm making a website, and have been trying to write javascript in a PHP file to create an alert, then depending on if the user clicks "ok" or "cancel", it takes them to different pages. I got a javascript code that should work in an HTML file, but the PHP file doesn't read it for some reason.
This is for a XAMPP server, running MySQL, PHP, HTML, CSS, javascript, and Apache. I tried pasting this into my PHP file, but it doesn't read properly.
if ($sessioncode != "Admin-placebojoe" || "Mizzy-renegade") {
loginFail();
} else {
loginSuccess();
}
function loginFail() {
var txt;
var r = confirm("Account does not exist. Either check credentials and try again, or press ok to Sign Up.");
if (r == true) {
txt = header("refresh:6; url=Signup.html");
} else {
txt = header("refresh:0; url=Login.html");
}
}
The PHP file rejects the line where it says var txt; on line 8. The error message reads:
Parse error: syntax error, unexpected 'var' (T_VAR) in C:\xampp*****
on line 13
(I left out a few lines at the beginning that's why it's line 13). This tells me that the error is the PHP file cant read the JavaScript.
How can I make the PHP file read and execute all of the JavaScript code?
PHP doesn't read or execute JavaScript. JavaScript runs in the browser.
If you include a JavaScript block in your .php file, PHP will (just as it would if you include a raw HTML or CSS block in a .php file) simply pass that code as-is to the browser in the response it gives to the HTTP request coming from that browser.
However if you are getting the error mentioned it implies that you tried to put this code inside a <?php block. This means the PHP interpreter will try to execute it as PHP code on the server. But as you said yourself: it isn't PHP code, it's JavaScript. Therefore (obviously I hope) the PHP interpreter cannot understand it and you get a syntax error.
If you want to include some JavaScript code to run in your browser, then move it outside the <?php ... ?> tags and put it inside a <script> block instead, e.g.
<script>
alert("Hello, World");
</script>
P.S. For background you may want to read this popular and informative thread: What is the difference between client=side and server-side programming?

php response text empty when using password_hash or password_verify

I have an application that uses javascript to get a string and POST it to a receiver php file on the server for further processing. The receiver's job is to parse the string, pass things along, and report to javascript how stuff is going. Recently I've tried to add password-based security to this whole shebang, but now receiver.php passes back an empty response.
What I'm finding is that if I call password_verify anywhere in the receiver (no matter what I do with it... I could even just call it without using it) the following echos in the script don't run - any responseText from those echos will be empty - and I've no idea why. Though, if I just run the php script raw from command line, everything DOES work.
Before continuing, I would note that I am pretty new to web development and password-based security, so don't skewer me too hard. Good news, though - unlike every OTHER problem I can find on the web, I AM getting correct hashes and correct verify-responses.
Using php 5.6.23
A scaled down version of the JS file "test.html":
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript">
function reviewAndSubmit() {
//bigOlString is usually built as a result of TONS of script on this page, use this as a test
var bigOlString = "password=1234 name=test otherParams=barglebargle"
var postString = new XMLHttpRequest();
//build function to receive post response
postString.onreadystatechange = function() {
if (postString.readyState == 4) {
window.alert("responseText: " + postString.responseText)
}
}
postString.open("POST", "receivertest.php", true);
postString.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
postString.send(bigOlString);
}
</script>
</head>
<body>
<button class="button" id="pushMe" onClick="reviewAndSubmit()">Why does PHP hate me so bad?</button>
And receivertest.php:
<?php
//hashed version of '1234' and debug name 'test'
$debugPass = '$2y$10$b.08/4NfawKOwrBYJqguc.AWsI3mQiGGaz1eYvfc9Uid1auQKKABm';
$debugName = 'test';
//get incoming string
$inString = file_get_contents('php://input');
//get challenge content
$challengePass = substr($inString, strpos($inString, "password=") + 9, strpos($inString, "name=") - 10); //10 because of the space
$name = substr($inString, strpos($inString, "name=") +5, (strpos($inString, "otherParams=") - strpos($inString, "name=") - 6)); //ugly!
//begin authentication
$auth = False;
echo $name;
echo $challengePass;
password_verify($challengePass, $debugPass); //yes, I'm not doing anything with this. Doesn't matter.
echo "this line won't echo";
?>
If you comment out the 'password_verify' line in receivertest.php, everything echos perfectly. If you don't, no luck - the 'alert' window in test.html just spits out 'responseText test123'. If you run receivertest.php in console (php receivertest.php), however, everything echos correctly.
Why is my responseText empty?
EDIT: I've edited the php script to better illustrate the problem. Yes, I know I'm not USING password_verify for anything. It doesn't matter. The 'this line won't echo' line doesn't echo out in test.html like the other lines do. My question is: why NOT?
The code is all fine. I made a quick edit in my httpd.conf file and restarted apache, and everything started working. I undid that edit to check and restarted - everything still worked. So I guess all I needed was an apache restart.
Apache seems to have more to do with php than I thought, I guess?

Is it possible to get javascript to take a screenshot?

Bit of a long shot, but is there a javascript function/process which allows automatically takes a screenshot of a specified area, and outputs a picture to a folder on my computer. Ideally, it would be able to put within a loop so that it takes a picture for each loop iteration.
Is this at all remotely possible?
If you have a web server with PHP installed, you can simulate this using wkhtmltoimage. To generate a new file every 5 seconds, your JS would be:
$(document).ready(function() {
function takeImage() {
$.post(
'htmltoimage.php',
{ currentUrl : window.location + "?stopTimer=1" }, // data that your script might need
function(data) {
if (data.url !== undefined) {
console.log("The URL where you can download your image is " + data.url);
}
},
'json' // use JSON for expected return type
);
}
var startTimer = <?php echo (isset($_POST['stopTimer']) ? "false" : "true"); ?>
if (startTimer) { setTimeout(takeImage, 5000); }
});
Your PHP file would simply use wkhtmltoimage to go to your URL. In its most simple form:
<?php
function() {
$outputLocation = "/images/output_" . strtotime(date()) . ".png";
// assuming wkhtmltoimage is in your PATH (otherwise specify full path to executable below)
`wkhtmltoimage $_POST['currentUrl'] $outputLocation`;
return array('url' => $outputLocation);
}
?>
You can then crop it at the positions you desire using ImageMagick or a similar PHP image processing library.
This can also be achieved using Adobe AIR, or really any program that uses WebKit.
Yes, you can. There is a useful library for that. You might want to take a look:
http://phantomjs.org/screen-capture.html
Since PhantomJS is using WebKit, a real layout and rendering engine,
it can capture a web page as a screenshot. Because PhantomJS can
render anything on the web page, it can be used to convert contents
not only in HTML and CSS, but also SVG and Canvas.
Hope it helps.

Calling Javascript function in an external file through php file?

Javascript code (In another file in the same directory):
function js(str)
{
alert(str);
}
PHP code(in current file):
<?php
echo '<script type="text/javascript" src="C:\xampp2\htdocs\ARD\call_jsfunc_diff_page.js"> </script>';
echo '<script>js("hello!!")</script>';
?>
I have checked on many links on the internet, i think i'm doing the right way, but the javascript function js(str) doesn't get called !!
Can somebody help me please ??
Before you edited the question: You called the function js but you are trying to call the func function.
Access to local hard disks is also problematic. Use a relative URI and access the .js over HTTP instead.

How to (ajax) post and execute response?

we have the following situation:
in default.aspx we have a link:
test.
and the JS code:
function doPost() {
$.post('AnHttpHandlerPage.aspx',"{some_data:...}", function(data) {
if(data.indexOf("http://")==0)
window.open(data);
else{
var win=window.open();
with(win.document) {
open();
write(data); //-> how to execute this HTML code? The code also includes references to other js files.
close();
}
}
}).error(function(msg){document.write(msg.responseText);});
}
The callback can first be an url address or 2nd html code that must be executed.
Option 1 fits, but in option 2, a new window will be opened where the code has been written but not executed.
It's clear, since it happens in the stream, it can't be executed. So the question, how can you fix it? Maybe a refresh(), or similar?
Because of the requirement of the customer, the workflow can not be changed, so it must be solved within doPost().
EDIT
The response in case 2 is HTML like this. This part should be executed:
<HTML><HEAD>
<SCRIPT type=text/javascript src="http://code.jquery.com/jquery-latest.js">
</SCRIPT>
<SCRIPT type=text/javascript>
$(document).ready(function() {
do_something...
});
</SCRIPT>
</HEAD>
<BODY>
<FORM>...</FORM>
</BODY>
</HTML>
Please help. Thanks.
In your JS code it should be something like this:
function doPost() {
$.post('AnHttpHandlerPage.aspx',"{some_data:...}", function(data) {
//if(data.indexOf("http://")==0)
if (data.type!="url") //i will add a data type to my returned json so i can differentiate if its url or html to show on page.
window.open(); // I dont know why this is there. You should
else{
var win=window.open(data.url); //This data.url should spit out the whole page you want in new window. If its external it would be fine. if its internal maybe you can have an Action on one of your controllers that spit it with head body js css etc.
/* with(win.document) {
open();
write(data); //-> how to execute this HTML code? The code also includes references to other js files.
close(); */ // No need to write data to new window when its all html to be rendered by browser. Why is this a requirement.
}
}
}).error(function(msg){document.write(msg.responseText);});
}
The overall logic is this
You do your ajax call on doPost
Find out if data returned is of type url or anything that need to open in new window
If it is url type it would have a url (check if this is not null or empty or even a valid url) then open a new window with that url. Have a read of W3C window.open for parameters
If you want to open and close it for some reason just do that by keeping the window handle but you can do this on dom ready event of that new window otherwise you might end up closing it before its dom is completely loaded. (someone else might have better way)
If its not url type then you do your usual stuff on this page.
If this does not make sense lets discuss.

Categories