how can I use curl with javascript - javascript

i am using curl to open a page and want to play video using javascript that was shown on the page . i have used following code
$url = "https://www.example.com/";
$link = "http://www.example.com/oembed?url=" . $url. "&format=json";
$curl = curl_init($link);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
$result = json_decode($return, true);
echo '<pre>'; print_r($result);
echo $result['html'];
play();
function play(){
document.getElementById("play-button").click();
}
my curl is working but it didn't play the video.where am iI wrong? do i have pass the x-path of the button to play video?

PHP scripts are executed on the server, while JavaScript is executed on the browser (Node.js is an exception). Thus your PHP code is already executed when the JS wanted to call the click action and there's no way that the PHP code will execute on the browser, thus the curl is not getting called.
What you need to do is call the URL using JavaScript asynchronously. You can either use Ajax or Fetch for this.

Related

How to refresh the web page when index changes without lagging the server

I would like to refresh my static web page running on apache when the index changes. I've already tried to use server-side events, where I had a PHP file checking if the index changed and if yes, it sent the event to the webpage. This works exactly how I want, but there is a problem. Because the page is used by a lot of people sometimes (tens or up to a hundred opened tabs), it quickly starts to spam many apache processes. Then, it reaches the limit, and the apache freezes.
The question is how to handle this. If a user closes the tab, the process is killed, however, if not, the apache freezes.
The PHP script looks like this (it is checking two things, first, if the file chenged, or second if the status is something. As I said, this works fine, the problem is its lagging the server):
<?php
session_start();
session_write_close();
ignore_user_abort(false);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$filename = "index.html";
while(True){
if ( connection_aborted() ){
exit();
}else{
try{
$string = file_get_contents("current_status.json");
$json = json_decode($string, true);
$pom1 = $json["state"];
$t1 = shell_exec("date -r index.html");
sleep(3);
$pom2 = $json["state"];
if($t1 != shell_exec("date -r index.html")) {
sleep(2);
echo "data: file changed \n\n";
} else if($pom2=="ready") {
sleep(2);
echo "data: new shot available \n\n";
} else {
echo "heartbeat";
}
ob_flush();
flush();
}
catch (\Error $e){
echo "data: error, json not available \n\n";
}
}
}
ob_end_flush()
?>
Then, there is a classical javascript function in the index file with event source on the PHP file.
My question is, how can I do this to not make apache crashing? Can I somehow set up SSE to handle it? I know I can allow more processes on apache, but my resources are limited.
Is there any other way how to do this? For example, live.js works as well, but the problem is the sam, a lot of processes when opened multiple times.
Yes, I can see how this would put far more strain on your server than necessary.
What you should do is poll for changes from javascript. You send an asynchronous request for the last time the index file changed from your javascript. You do it once when the page loads and store the time. Then you check again on an interval and compare the result with the first one. If it changed you refresh the page.
The PHP script should get the last change date, output it and exit - no continuously running PHP scripts.
Here is what the PHP file should look like:
<?php
header('Content-type: text/plain');
echo filemtime('index.html');
?>
Keep this minimal. The built in filemtime function is more efficient than running shell_exec commands.
Here is an example javascript:
chk_index_change_time(false);
function chk_index_change_time(last){
fetch('http://yourdomain.com/yourpath/get_index_change_time.php')
.then(res => res.text())
.then((index_change_time) => {
if ((false !== last) && (last != index_change_time)){
location.reload();
} else {
setTimeout(chk_index_change_time, 3000, index_change_time);
}
});
}
Feel free to error handling or whatever, but this will work. I used a timeout here instead of interval so that if the server is slow the server response time doesn't come out of the 3 second delay.

Web scraping for dynamic content

I am trying to scrape the information from a couple sites (mega.nz, openlaod.co) and the content is loaded dynamically so the code i am actuallu using doesn't work
<?php
require 'simple_html_dom.php';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://openload.co/f/41I9Ak_QBxw/DPLA.mp4");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
$html = new simple_html_dom();
$html->load($response);
foreach ($html->find('img[id=imagedisplay]') as $key ) {
echo $key;
}
?>
when i use it on openload (like the example above) it redirects me to "https://oload.download/scraping/" being "/scraping" the folder where i have my script at.
Is there any javascript/jquery framework (or php) that i can use to scrape the content on the fly??
It's not suitable for a large amount of scraping, but in the past when I've needed to grab some basic data from a dynamic web page I've found that Selenium works pretty well.
Depending on your stack of choice, I'd recommend looking into headless browsers. This way you can render a page in the background and parse the resulting HTML.

How can i access javascript variable in kirby cms for “limit” functionality

Just like in demo of kirby
<?php foreach(page('projects')->children()->visible()->limit(3) as $project): ?>
I want to make dynamic limit of records.
How can i do that?
I have tried JavaScript but it not worked.
Here is JavaScript code that no worked
<script>
var p1 = 3;
function load()
{
p1=p1+3;
}
</script>
<?php
$number="<script>document.write(p1)</script>";
// echo $number;
<?php foreach(page('projects')->children()->visible()->limit($number) as $project): ?>
//Code Here
<?php endforeach ?>
<div class="text-center">LOAD MORE</div>
suggest me if anyone has done it.
You can't, at least not in this way.
Think of when and where your code is getting executed. PHP is executed by the server, before the browser even receives the page. JavaScript is executed by the browser, after the page is done loading.
You can either have a separate script that generates what you need from your number, and pass that as a GET or POST value to the script via an AJAX request, or generate the number you need in PHP.
So in case of an AJAX request you'd have your PHP script doing something like:
<?php
$number = $_GET['number'];
foreach (page('projects')->children()->visible()->limit($number) as $project) {
echo .....
}
?>
and your JavaScript would call that script via an AJAX request and put the resulting HTML into your page, with something like:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
document.getElementById("container").innerHTML = xht.responseText;
}
xhr.open("GET", "script.php?number=" + p1, true);
xhr.send();

accessing php variables using javascript

I've done created a webpage, set up appache2 on ubuntu server so I can view this page over the internet. I've installed php5 and MySQL and would like to access information in the database on the webpage that I've created.
Right now, I've got a file test.php that accesses the database and puts some of the information into variables. I've scripted using javascript something that will change the webpage content at the click of a button.
Now, the webpage crashes whenever the button is pushed as it says the variables are undefined or null references. Fair enough, but my question is how does one access variables on a .php file through the webpage? Can a browser use information in the .php file if I script it into the page?
I was told that the php file would be parsed automatically. I'm guessing that server side this page is being accessed but I can use it through web browser.
Edit:
//check connection
if (mysqli_connect_errno()){
echo "failed to connect to MySQL: " . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
?>
Ok so I changed the php file to this, so now all it is doing is defining variables. I installed a couple of MySQL mods and no problems now.
next issue is how do I get use php variables in javascript
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = "<?php echo $n1;?>;
}
}
}
So onload this ajax function should run and change itemNameLink1 to the php variable $n1, only it doesn't and I just get an empty string. Everything should be set up right but using the php variable seems impossible. would it be any easier with the jquery get command, I'm guessing that unless I sort this out I'm gonna struggle.
I'm also assuming a few things, I've checked error logs and the php file is active assuming I've connected right it should be accessing the database. I'm very new so I do not know how to test this.
I'm also assuming that when php file is in the server webpage file directory. that it is automatically working. again very new to setting up a server so using ubuntu server and being familiar with all the commands that I need to use or how apache2 operates is difficult for me.
PHP Is executed on the server, your client receives the result as a plain text/html document.
Your browser runs the javascript when it received the plain document, so you can't access PHP vars directly with javascript.
But you could set javascript variables when the page is generated on the server like this
<?php $myPhpVar = 'Hello World'; ?>
<script>
//This line would result in var test = "Hello World"; when send to client
var test = "<?=$myPhpVar?>";
alert(test);
</script>
Furthermore you can execute requests to your server with javascript (so you can read the result from test2.php as example, and use that somewhere on your page). http://en.wikipedia.org/wiki/Ajax_(programming)
Pure javascript: http://en.wikipedia.org/wiki/XMLHttpRequest
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE){
alert(this.readyState);
}
};
var action = 'doSomethingOnServer';
request.open('GET', 'test2.php?action=' + action, true);
request.send(null);
Jquery: http://api.jquery.com/jquery.ajax/
<script>
var action = 'doSomethingOnServer';
$.ajax({
url: "test2.php?action=" + action,
}).done(function(result) {
alert(result);
});
<script>
For testing if your php works on your server create a file info.php (or something). and add this to the file
<?php phpinfo(); ?>
If you access that page you should get a page with a lot of information about your php configuration.
I'm not sure how you did install your php, but on a development machine you can change a few things in your php.ini that makes life easier
display_startup_errors = 1
display_errors = 1
error_reporting = E_ALL
See http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting when you change your php.ini don't forget to restart your apache
JSON Example:
data.php
<?php
$db_result = array(array('name' => 'record1'), array('name' => 'record2'));
echo json_encode($db_result);
?>
index.php
<script>
$.ajax({url: 'data.php', dataType: 'json'}).done(function(result) {
//result = an object from your database (in this case an array with objects with the property name)
alert(result);
alert(result[0].name);
}
</script>

Session Start is very slow with AJAX

i have using Ajax to load the content of another page in my div with Twitter Bootstrap tabs.
I realized that Ajax was taking too long to load the request, so I decided to clean up the code and leave just the 'session_start ()'.
And the problem is exactly the 'session_start ()'.
Microtime used to measure the time of the requests.
Below is the result of tests:
PHP WITH session_start() loaded with AJAX - 29.041733980179 ms
PHP with session_start() loaded without AJAX - 0.00010895729064941 ms
PHP WITHOUT session_start() loaded with AJAX - 1.6927719116211 ms
This is my Javascript code:
$(function() {
$("#MainTabs").tab();
$("#MainTabs").bind("show", function(e) {
var contentID = $(e.target).attr("data-target");
var contentURL = $(e.target).attr("href");
if (typeof(contentURL) != 'undefined')
$(contentID).html('<img src="<?php echo IMG_DIR; ?>loading/loading-large.gif" width="64" />').load(contentURL, function(){
$("#MainTabs").tab();
});
else
$(contentID).tab('show');
});
$('#MainTabs a:first').tab("show");
});
This is my PHP Code:
<?php
$start = microtime(TRUE); // Start counting
set_time_limit(0);
// session_start();
$temp = microtime(TRUE) - $start;
echo $temp;
exit;
Does anyone know what is happening?
I had almost the same problem, it is called a session lock. When you do more than one ajax calls, the server prevents session writing for the the latter calls so they have to wait for the previous calls to end. Using session_write_close() when you are done with your session, unlocks the other calls.
Here's more info: session_write_close() on php.net

Categories