Since I couldn't find the answer to this question anywhere, so here comes the question. But before that, Thanks to anyone who answers/helps in anyway.
The pseudo-code of the index.php page is:
<html>
<head><script>
<?php
$links = parse_ini_file('links.ini');
if(isset($_GET['l']) && array_key_exists($_GET['l'], $links)){
$my_phpvar = $links[$_GET['l']];
}
else{
header('HTTP/1.0 404 Not Found');
echo 'Unknown link.';
}
?>
var myjsvar= <?php echo $my_phpvar; ?>
function go(){
document.cookie = "visited=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
window.location.href = "myjsvar";
}
</script></head>
<body><a id="myA1" href="javascript:go();" target="_blank">Click</a></body>
</html>
As is evident, in the above code the myjsvar comes from my_phpvar, and my_phpvar comes from a seperate file links.ini (sorry if I'm boring you, since it's all evident in the code, but I don't wanna miss anything out for anyone who can help)
I have added some rules to the .htaccess file in the root of this directory where index.php is located. The rules that have been added are
RewriteEngine On
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php?l=$1 [L]
The links.ini file looks like this:
ex = https://www.example.com
So the Main Issue is: When I browse the URL http://www.yoursite.com/short/index.php?l=ex , and Click the Button to initiate the function go(), it doesn't take me to the website https://www.example.com
Once again, Thanks to anyone who solves/helps to solve the issue.
Enclose jsvar inside quotes:
var myjsvar = "<?php echo $my_phpvar; ?>";
and later, use it as a variable (and not sring):
window.location.href = myjsvar;
Related
I have the following script that works perfect.
<script type="text/javascript">
$(document).ready(function() {
php_test();
});
</script>
<script type="text/javascript">
function php_test() {
alert('<?php echo(DIR); ?>myfile');
}
</script>
The output is as expected:
http://localhost/mvc_framework/myfile
when I put the function php_test in a file lets say ‘php_test.js’ and bind it to my footer it executes with this output:
<?php echo(DIR); ?>myfile
Any explanation? Im confused…
The way you asked the question makes it confusing. It is possible to make PHP run on all types of files on your server with a bit of Apache tweaking. My solution will make your JS files be processed by the PHP interpreter.
What you need to do is create a .htaccess file if you are using Apache. I am going to assume you are. Then you add this line into it:
AddType application/x-httpd-php .php .js
The above code will force the PHP interpreter to run on all the formats listed in the command. You can also add .htm or even .css if you need PHP to do something with those files on the server side.
Refer to this question here for a previous solution to similar question > Using .htaccess to make all .html pages to run as .php files?
Or you can just store a whole bunch of variables from the PHP end on the page as Javascript variables like this example from one of my projects:
<script type="text/javascript">
var trackFilterFlag = null;
<?php
echo "trackFilterFlag = \"". $displayedPageType ."\";\r\n";
?>
var trackFilterCategory = null;
<?php
if(strcmp($displayedPageType, "mood") === 0 || strcmp($displayedPageType, "genre") === 0) {
echo "trackFilterCategory = \"". $filterCategory ."\";\r\n";
}
?>
var sortingTracksBy = null;
<?php
if( isset($chosenSortFlag) && strlen($chosenSortFlag) > 3 && !($defaultSort) ) {
echo "sortingTracksBy = \"". $chosenSortFlag ."\";\r\n";
}
?>
</script>
Of course I was still a novice when I wrote that code, it's possible to make it much neater and just make PHP echo the whole thing, but you understand what I mean :)
I have a PHP variable that I am declaring upon loading the page, and want to use it in a JavaScript/jQuery function that loads upon a button click.
I have the following on my index.php page:
// Creating a random name for a file and creating it. Working properly.
$fname = substr(md5(rand()), 0, 7);
$file = fopen("temp/" .$fname, 'w');
And when I click a button, the following JavaScript function should run:
//Use the generated filename in the JavaScript function
var fname = <?php echo $fname; ?>;
var fileName = "temp/" + fname;
My understanding is that the PHP variable is outside of the scope of the JavaScript function, since I believe this is the way it should be done.
Can you please help with this?
PHP generates a page and presents it to a browser. As far as the browser is concerned, by the time the page is received, PHP is finished. So to answer your question, that should work, since PHP will essentially just spit out the text on to the page, which will act as normal. That is, unless I am terribly misinformed.
The "scope" of a PHP variable is long gone by the time Javascript gets to run, so that isn't really an issue.
Try do this. in a php file of course.
var fname = '<?php echo $fname; ?>';
I think you need an extension on your filename:
$extension = ".txt";
$fname = substr(md5(rand()), 0, 7).$extension;
$file = fopen("temp/" .$fname, 'w');
The problem is the missing apostroph like anant kumar singh mentioned.
I tested the following code in a webpage:
<?php
$fname = substr(md5(rand()), 0, 7);
$file = fopen("temp/" .$fname, 'w');
?>
<html>
<head
</head>
<body>
<script>
var fname = "<?php echo $fname; ?>";
var fileName = "temp/" + fname;
</script>
</body>
</html>
I have a javascript file called in my webpage. It contains only one var :
var tab = [ "img1.jpg" ,
"img2.jpg" ,
.......... ,
"img100.jpg"
]
"img_i_.jpg" in tab are from my data base.
I've written a php code to update this file.
...
$res = mysql_query($sql) or die(mysql_error());
$script="var tab= [\n";
while($r = mysql_fetch_assoc($res) )
$script .= "\t\"" . $r['name']"\",\n";
$script = $script."];\n";
$fileName = fopen("js/tab.js", "w");
fwrite($fileName, $script);
fclose($fileName);
...
When I check out my js file, all is correctly written, but when I reload my page, nothing has changed.
Curiously, when I edit that js file manually, and then save it then my webpage changes after reload.
Why ? And how to solve it ? Thanks
You might be writing your file in a different location. Check the current directory under which the php page is run, and try to specify an absolute path to fopen rather than a relative one.
dirname(realpath(__FILE__)) will return the path to the folder where the current php file is stored, so you can generate absolute paths through that.
Edit: I'd also suggest doing some error checking around fopen, so that you know if the file was really opened.
Extra
You should really change your mysql_* calls to at least mysqli_* or PDO. The original mysql extension is old, doesn't support prepared statements and has been deprecated (and is due for removal).
I have a IP Camera and I would like to show liveview at my webpage.
IP Camera don't allow for anonymous log in so I need to put username and password while connecting.
I have javascript:
<img src="http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi?" width="640" height="480" name="refresh">
<script language="JavaScript" type="text/javascript">
image = "http://camera_ip_address/cgi-bin/jpg/image.cgi?"
function Start() {
tmp = new Date();
tmp = "?"+tmp.getTime()
document.images["refresh"].src = image+tmp
setTimeout("Start()", 100)
}
Start();
</SCRIPT>
And it works ok in firefox but:
http://user:password#camera_ip_number
don't work in other browsers (it popup a form to enter username and password).
But in PHP you can use user:password I've check it by using:
<?php
header('Content-type: image/jpeg');
print( file_get_contents( 'http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi?' ));
?>
of course it shows only one frame but you don't have to enter username and password.
How can I log in into IP Camera using PHP ? If I could log in one time while enetering webpage, my javascript will work ok because browser will remember username and password until I close the browser.
I don't know how to send username and password to log in.
Sorry for my English.
Ok, so I've made it work using PHP and JavaScript. Maybe it will be helpful for someone else:
Save the PHP file as, for example, snapshot.php:
<?php
$img="http://user:password#camera_ip/cgi-bin/jpg/image.cgi?";
header ('content-type: image/jpeg');
readfile($img);
?>
In the HTML file, add this script:
<img src="http://domain.com/snapshot.php" width="640" height="380" name="refresh">
<script language="JavaScript" type="text/javascript">
image = "http://domain.com/snapshot.php"
function Start() {
tmp = new Date();
tmp = "?"+tmp.getTime()
document.images["refresh"].src = image+tmp
setTimeout("Start()", 300)
}
Start();
</script>
It works ok under every browser. If I set timeout to less then 300, there is some lag. I don't know why that would be caused by; maybe internet connection or website speed.
You may be able to use Apache mod_rewrite instead - Less overhead from the PHP stack, and probably generally faster. See this page for more information.
Choose one of these.
Apache .htaccess - Your page requests http://yoursite/livecam/image.jpg, which is run through Apache's proxy to your camera.
RewriteEngine on
RewriteBase /livecam/
RewriteRule ^image.jpg$ http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi [P]
ProxyPassReverse /livecam/image.jpg http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi
In PHP, create a file called image.php - Your page requests http://yoursite/image.php, which streams the image to whatever requests it.
<?php
$file = 'http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi';
if (file_exists($file)) {
header('Content-Type: image/jpeg');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
Both will proxy the image through your server. It's generally bad practice to give the username and password on any public page, even if an attacker can't damage anything of concern.
See readfile() on PHP.net
Your code would look like (replace image.php with livecam/image.jpg if using the Apache version). I also shortened your code a bit.
<img src="http://yourserver/image.php" width="640" height="480" name="refresh">
<script language="JavaScript" type="text/javascript">setTimeout(function() {document.images["refresh"].src = "http://yourserver/image.php?"+math.random();}, 100);</SCRIPT>
IP:port/cgi-bin/jpg/image.cgi?&user=XXX&pwd=XXX
IP:port/cgi-bin/jpg/image.cgi?&usr=XXX&pwd=XXX
IP:port/snapshot.cgi?&user=XXX&pwd=XXX';
IP:port/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=XXX&pwd=XXX';
I'm trying to use PHP variables in Javascript but I couldn't. After over 2000 lines of writing different JS functions I was fine avoiding that but now I really needed it. I'm a bit lost on all the ways to go about this but nothing really worked. Here is my sequence:
index.html file:
...
<script src="myfunctions.js" />
....
myfunctions.js file:
....
function test() {
var x = <?php echo $_conf['user_id'];?>
console.log(x);
}
I was trying to rename the .js file into .php file and add
header("Content-type: text/javascript");
at the beginning - that didn't work. I was trying to make .htaccess file with
AddType application/x-httpd-php .js
But that didn't work either. I'm probably missing just a tiny thing. I just need someone fresh and bright to point it out.
You can do something like this within your JS code.
var php_var = "<?php echo $_conf['user_id'];?>"
Your javascript file should be named as "javascript.php" (just put the name you want, the only important thing is the .php
You have an index.php
Write in your index.php
include("javascript.php");
Then in your javascript.php
<script>
function test(){
var variable = "<? echo $conf['user_id'] ?>";
alert(variable);
}
<script>
PS: Yo don't need any header.
Since you're doing this via a <script> tag, your PHP script MUST output valid Javascript code, as if you'd literally type your variable assignment in manually. That means doing something like:
HTML/JS:
<script src="myscript.php"></script>
PHP:
<?php
$myvar = 'foo';
?>
var myvar = <?php echo json_encode($myvar); ?>;
Which in the end, will produce somethign that will function exactly as if you'd manually typed in the following:
<script>
var myvar = 'foo';
</script>
Note the use of json_encode(). Using this ensures that whatever you're outputting from PHP will become syntactically valid Javascript.
You're not assigning PHP value to a Javascript variable. Try:
var v = "<?php echo $_conf['user_id'];?>";
index.html
..
<script src="myfunctions.js.php" />
...
myfunctions.js.php
<?php
header('Content-Type: text/javascript');
...
?>
var val = <?php echo json_encode($val); ?>;
...
Other possible solution is to assign server-side data to attributes in html and read them in javascript. For example index.html could contain something like this:
<div id="user-profile" data-user-id="<?php echo $conf['user_id']; ?>"></div>
and in js file you can get them while necessary(example with jQuery):
var userID = $('#user-profile').attr('data-user-id');
Of course you should adjust your server-side settings to process html files.