Pass PHP variable to javascript src [duplicate] - php

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
Okay, so I have a php variable which stores:
http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback
This is working fine and i want to do the following:
<script type="text/javascript" src="<?php echo $string; ?>"></script>
But it doesn't seem to be working
Thanks for any help
EDIT:
Here is my code, tried all 3 answers below but didn't work:
http://pastebin.com/xYKW8TTd

This seems to work as expected:
<?php
$string="http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback";
?>
<script type="text/javascript" src="<?php echo $string; ?>"></script>
with the output of:
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback"></script>
Edit: in your source code on pastebin, you seem to have:
$string = "http://gdata.youtube.com/feeds/api/videos/" . $id ."?v=2&alt=json-in-script&callback=youtubeFeedCallback";
which contains & in the place of & which would stop the link working. Was this somethign that pastebin did or was it in your original code?
You can't send HTML codes to the URL window and expect it to work the same way as if it was in a HTML body.
The following code (just edited $id as I am not putting anything in GET and modified & symbols gave:
<html>
<head>
<?php
//$id = $_GET['id'];
$id=0;
$string = "http://gdata.youtube.com/feeds/api/videos/" . $id ."?v=2&alt=json-in-script&callback=youtubeFeedCallback";
?>
<title></title>
</head>
<body>
<?php echo $string; ?><br>
<script type="text/javascript" src="<?php echo $string; ?>"></script>
Had the output of:
<title></title>
</head>
<body>
http://gdata.youtube.com/feeds/api/videos/0?v=2&alt=json-in-script&callback=youtubeFeedCallback<br>
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/0?v=2&alt=json-in-script&callback=youtubeFeedCallback"></script>

Try this:-
<?php
$str = 'http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback';
?>
<script type="text/javascript" src="<?php echo $str; ?>"></script>

<?php
$string = 'http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback';
?>
<script type="text/javascript" src="<?=$string;?>"></script>

Try this:
echo "<script type=\"text/javascript\" src=\"".$string"\"></script>\n";
If this "does not work", you have some error in string constant which cause javascript error.
Please provide more info, like generated source or exact browser error.
UPDATE:
#user1641732 : As of Mahan's comment. You are including JSON object, not javascript.What you are try to achieve? Did you understand difference between JSON object and javscript code?

Why are you trying to do this? Surly the best way to retrieve data from YouTube would be to do a php cUrl request and decode the json data their, or alternatively, if you really have to you can save the contents to a file with file_put_contents or fopen.
Here is a cUrl example, add your own $url variable:
// get the data via curl
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_ENCODING, "" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );
$rsp = json_decode(curl_exec($ch));
curl_close($ch);

<?php
$string = "http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback";
?>
<script type="text/javascript" src="<?php echo $string; ?>"></script>

Related

php) code inside if(empty($param1)){} still runs even $param1 is not empty

I have been working on this problem for several hours but I couldn't figure out why empty() in if statement doesn't work as I expected.
fetch.php
header('Content-Type: application/json');
function fetchApi($param1){
$apiKey="SOME TEXT WHICH I WILL NOT POST HERE";
$curl = curl_init();
if(empty($param1)){
$body = json_decode(file_get_contents('php://input'), true);
$bodyObject = (object) $body;
if($bodyObject->target=="main"){
$bodyObject->link = $bodyObject->link . "random?number=4".$apiKey;
curl_setopt($curl, CURLOPT_URL, $bodyObject->link);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
echo $output;
}
}else{
echo $param1;
}
curl_close($curl);
}
fetchApi('');
this is my fetch.php code, I need to run fetchApi in two different situations.
The first situation is when index.html is loaded. Javascript will automatically fetch to fetch.php and runs function fetchApi with empty string as parameter. Have tested hundreds time and it works fine.
But the problem is, I need to run this function in search.php too, when user searches something.
form in index.html
<form action="search.php" method="GET">
<label for="check">ingradients</label><input id="check"type="checkbox"/>
<input type="text" name="search" placeholder="SEARCH"/>
</form>
search.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<?php
$searchId = $_GET["search"];
include ('fetch.php');
fetchApi($searchId);
?>
</body>
</html>
as you can see, in search.php I include fetch.php and calls function fetchApi with argument $_GET["search"] , but I get this error when I search something.
Notice: Undefined property: stdClass::$target in C:\xampp\htdocs\spoonacular\fetch.php on line 16
I can't understand why php shows such error. I passed an argument, it's not empty, why php still runs algorithms inside if(empty($param1)){}? I tried if($param1==''){} also but it doesn't work too.
How to do if I want totally ignore everything inside if(empty($param1)) if function parameter is not empty string or NULL?
Answering to my question myself.
It had nothing to do with if(empty(....))
The reason why I got that error was
fetchApi('');
was always being called when I include fetch.php
Thank you user3783243 for your comment.
And I solved this problem so
if(empty($_GET)){
fetchApi('');
}
fetchApi('') will only run when user hasn't made a GET request.

PhP Curl SFTP File Editing

I am trying to create a online editor for multiple server. I want to edit a custom file on a server and I need to get it via sftp. My current code looks like this:
<?php
$user="user";
$pass = 'pass';
$c = curl_init("sftp://$user:$pass#0.0.0.0/path/to/file/file.txt");
curl_setopt($c, CURLOPT_PORT, 3206);
curl_setopt($c, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
curl_setopt($c, CURLOPT_FILE, $fh);
curl_exec($c);
curl_close($c);
//the next line is not working and from now on am I stuck
$text = file_get_contents($fh);
?>
<!-- HTML form -->
<form action="" method="post">
<textarea name="text"><?php echo htmlspecialchars($text) ?></textarea>
<input
type="submit" />
<input type="reset" />
</form>
I want to edit this file on the website and then reupload it to the sftp server in the same directory (overweite the existing one). I do not know how to continue. Thanks for the help.
First off if it's a file containing some programming language, check ACE.js.
It's simply an incredible JS module for use as a web IDE and it has all the features any programmer looks for in an IDE, it's so good I would ALMOST consider switching to it as my primary IDE.
Then use this PHP code:
<?php
$_POST = json_decode(file_get_contents('php://input'), true);
$filename = 'sftp://user#location/file/name.js';
//Use SSH public key authentication
$handle = fopen($filename,'w') or die('Cannot open file: '.$filename);
$data = $_POST['src'];
fwrite($handle, $data);
fclose($handle);
?>
and use this JS code to call the PHP script:
<script src="../scripts/ace/ace.js" type="text/javascript"></script>
<script>
var editor = ace.edit("editor");
editor.setTheme('<?php echo $theme; ?>');
editor.getSession().setMode("<?php echo $language; ?>");
editor.setShowPrintMargin(false);
editor.setReadOnly(true);
<?php //Save shortcut binding ?>
editor.commands.addCommand({
name: 'Save',
bindKey: {win: 'Ctrl-S', mac: 'Command-S'},
exec: function(editor) {
var xhr = new XMLHttpRequest();
xhr.open("POST", './scripts/save_file.php', true);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.send(
JSON.stringify(
{src:editor.getValue()}
)
);
}
});
</script>

Should all files have the .php extension or should PHP output a string? [closed]

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 5 years ago.
Improve this question
I want to show the server status of an IP address on every page, but to check the status I need a PHP script. This script is what I found on the Internet:
<?php
$server = 'google.be:80';
$split = explode(':', $server);
$ip = $split[0];
$port = (empty($split[1])) ? '80' : $split[1];
$server = $ip . ':' . $port;
$fp = #fsockopen($ip, $port, $errno, $errstr, 1);
if($fp) {
echo $server . ' is online';
fclose($fp);
}
else {
echo $server . ' is offline';
}
?>
I want the echoes to be formatted like my CSS content is formatted, so I could just replace the echoes with:
?>
<p>Server is offline<p>
<?php
and
?>
<p>Server is online<p>
<?php
But then I would have to make every HTML file a PHP file. Would you recommend that or is there a different way to handle this?
On my server all the files are a PHP since I need to include PHP functions such as echo username and such, and I believe it doesn't hurt to convert .html to .php. Another thing is that the following page provides information on styling PHP echoes with CSS.
How can I style a PHP echo text?
I think it would be better have all PHP files.
You could use jQuery AJAX to send the PHP data to your HTML page. You could json_encode the response and receive that data as a JSON object and get the data out of it.
EDIT: In a production enviroment and for efficiency, it would be best if you convert the HTML files to PHP files, it will be worth the labour. However this little snippet below could be used for other functionality if modified or built upon so it's a learning experience for you to see basic jQuery AJAX calls.
The following code is a working example of calling your PHP file and getting back the result. Seeing a basic example of using jQuery and AJAX will help you get a firm grounding of how to use it.
check_server.php
<?php
$server='google.be:80';
$split=explode(':',$server);
$ip=$split[0];
$port=(empty($split[1]))?'80':$split[1];
$server=$ip.':'.$port;
$fp = fsockopen($ip, $port, $errno, $errstr, 1);
$result = new stdClass();
if($fp){
$result->result = 'success';
fclose($fp);
}
else{
$result->result = 'offline';
}
echo json_encode($result);
?>
index.html
<html>
<head>
<title>Website</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$.ajax({
url : "check_server.php",
type : "POST",
dataType: "json",
success : function(results){
if (results.result === 'success')
{
$('#status').append('Server online.');
}
else
{
$('#status').append('Server offline.');
}
},
error : function()
{
$('#status').append('An error has occurred.');
}
});
</script>
</head>
<body>
<div id="status"></div>
</body>
</html>
It is not possible to implement PHP in an HTML file. To create HTML in a .php file is the best solution to solve this.
You can use HTML in a PHP file and you do not have to use PHP in the file if you name it a PHP file.

get a text file using php and send the string to javascript

Ok, what I am trying to do is make a javascript loop of images, but first I have to get a list of the images. In javascript there is no way to directly grab this text file... http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt but it can be done eaisly in php, I am currently gettung the txt file using php, but the javascript cannot read the variable. How can I make javascript be able to read this variable. Here is what I have...
<?php
$file = "http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt"; //Path to your *.txt file
$contents = file($file);
$string = implode($contents);
echo $string;
?>
<script type="text/javascript">
function prnt() {
var whatever = "<?= $string ?>";
alert(whatever);
}
</script>
You can use echo or print to write to the page in PHP.
var whatever = "<?php echo $string; ?>";
Although, if the file has line breaks in it, you will need to remove those.
Make it a bit more interesting: go ahead and split the fields and use JSON encoding. It should read directly in javascript without needing to call JSON.parse() on the client.
<?php
$lines = file_get_contents('http://...');
$lines = explode("\n",trim($lines));
foreach ($lines as &$line) {
$line = preg_split('/,? /',$line);
}
$js = json_encode($lines);
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var dar = <?php echo $js; ?>;
</script>
</body>
</html>
You should also consider using a local proxy to cache the results of that file if you plan to run this frequently and especially if you are going to serve it up on a public web server somewhere. Store the file locally as "noaa_data.txt" and have a second script on a cron job (12 hours or something):
<?php
file_put_contents("/var/www/noaa_data.txt",file_get_contents("http://www.ssd.noaa.gov/goes/east/tatl/txtfiles/ft_names.txt"));
?>

Why doesn't file_get_contents work?

Why does file_get_contents not work for me? In the test file code below, it seems that everyone's examples that I've searched for all have this function listed, but it never gets executed. Is this a problem with the web hosting service? Can someone test this code on their server just to see if the geocoding array output actually gets printed out as a string? Of course, I am trying to assign the output to a variable, but there is no output here in this test file....
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>
Check file_get_contents PHP Manual return value. If the value is FALSE then it could not read the file. If the value is NULL then the function itself is disabled.
To learn more what might gone wrong with the file_get_contents operation you must enable error reporting and the display of errors to actually read them.
# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);
You can get more details about the why the call is failing by checking the INI values on your server. One value the directly effects the file_get_contents function is allow_url_fopen. You can do this by running the following code. You should note, that if it reports that fopen is not allowed, then you'll have to ask your provider to change this setting on your server in order for any code that require this function to work with URLs.
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?php
# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>', $url, '</p>';
$jsonData = file_get_contents($url);
echo '<pre>', htmlspecialchars(substr($jsonData, 128)), sprintf(' ... (%d)', strlen((string)$jsonData)), '</pre>';
# Output information about allow_url_fopen:
if (ini_get('allow_url_fopen') == 1) {
echo '<p style="color: #0A0;">fopen is allowed on this host.</p>';
} else {
echo '<p style="color: #A00;">fopen is not allowed on this host.</p>';
}
# Decide what to do based on return value:
if ($jsonData === FALSE) {
echo "Failed to open the URL ", htmlspecialchars($url);
} elseif ($jsonData === NULL) {
echo "Function is disabled.";
} else {
echo '<pre>', htmlspecialchars($jsonData), '</pre>';
}
?>
</body>
</html>
If all of this fails, it might be due to the use of short open tags, <?. The example code in this answer has been therefore changed to make use of <?php to work correctly as this is guaranteed to work on in all version of PHP, no matter what configuration options are set. To do so for your own script, just replace <? or <?php.
If PHP's allow_url_fopen ini directive is set to true, and if curl doesn't work either (see this answer for an example of how to use it instead of file_get_contents), then the problem could be that your server has a firewall preventing scripts from getting the contents of arbitrary urls (which could potentially allow malicious code to fetch things).
I had this problem, and found that the solution for me was to edit the firewall settings to explicitly allow requests to the domain (or IP address) in question.
If it is a local file, you have to wrap it in htmlspecialchars like so:
$myfile = htmlspecialchars(file_get_contents($file_name));
Then it works
Wrap your $adr in urlencode().
I was having this problem and this solved it for me.
//JUST ADD urlencode();
$url = urlencode("http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false");
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?php
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>
The error may be that you need to change the permission of folder and file which you are going to access. If like GoDaddy service you can access the file and change the permission or by ssh use the command like:
sudo chmod 775 file.jpeg
and then you can access if the above mentioned problems are not your case.

Categories