This question already has answers here:
PHP file_get_contents() returns "failed to open stream: HTTP request failed!"
(16 answers)
Closed 4 years ago.
I have created script for lk domain search.
this is the code
<form action="" method="GET">
<input type="text" name="dm" placeholder="tx">
</form>
<?php
if (isset($_GET["dm"])) {
$domain = $_GET["dm"];
$res = file_get_contents("https://www.domains.lk/domainsearch/doDomainSearch?domainname=$domain");
echo $domain;
}
?>
<script type="text/javascript">
var data = '<?php echo $res ?>';
document.write(data);
</script>
var data will show in local host. but i have hosted it in my server then result will not show.
this is server hosted file http://vishmaloke.com/dm/ser.php
SOLUTION #1
There is PHP setting by name allow_url_fopen. This must be enable to get content from remote url. You can do it via .htaccess file.
Put following line in an .htaccess file in the directory you want the setting to be enabled:
php_value allow_url_fopen On
Note: This above setting will apply only into same directory where .htaccess file placed.
SOLUTION #2
Alternatively you can update php.ini
PHP.INI UPDATE
add following line to php.ini
allow_url_fopen = On;
SOLUTION 3
It is recommended to use curl instead of file_get_contents
CURL UPDATE
if (isset($_GET["dm"]))
{
$domain = $_GET["dm"];
// curl
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,"https://www.domains.lk/domainsearch/doDomainSearch?domainname=$domain");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($curl_handle);
curl_close($curl_handle);
echo $domain;
}
Related
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.
Is it possible to inject/modify a java script before a html page is loaded without a browser extension?
Im trying to get the value of a function scope variable during loading of the page
because this variable gets unset after the canvas is rendered(im trying to get the value of a canvas chart)
I succeeded using a php script hosted on a local server,
<?php
// Set your return content type
header('Access-Control-Allow-Origin: *');
$url = $_GET['url'];
//Get that website's content
$handle = fopen($url, "r");
// If there is something, read and return
if($handle)
{
while(!feof($handle))
{
$buffer = fgets($handle, 10000000);
echo $buffer;
}
fclose($handle);
}
?>
<?php
if(isset($_POST["submit"]))
{
$adm=$_POST["admno"];
$phn=$_POST["phn1"];
include("model.php");
$db = new database;
$r=$db->register($adm);
while($row=mysql_fetch_array($r))
{
if($row["phn_no1"]==$phn || $row["phn_no2"]==$phn || $row["phn_no3"]==$phn)
{
$formatted = "".substr($phn,6,10)." ";
$password = $formatted + $adm;
echo $password;
$db->setpassword($adm,$password);
$pre = 'PREFIX';
$suf = '%20ThankYou';
$sms = $pre.$password.$suf;
session_start();
$ch = curl_init("http://www.perfectbulksms.in/Sendsmsapi.aspx? USERID=ID&PASSWORD=PASS&SENDERID=SID&TO=$phn&MESSAGE=$sms");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
$result = curl_exec($ch);
curl_close($ch);
header("Location:password.php?msg=new");
}
else
{
header("Location:register.php?msg=invalid");
}
}
}
?>
this code is working perfect on my local host .. but when i put it on server ... it takes lots of time but the code in curl command is not working it only refers to next page ... i checked that curl is enabled .. if i use only sms api without curl command it sends sms immidiately.... but i want to run both header and also want to hide my sms api.... is there any alternate of this ???
Check if simple wget or curl from server to SMS API working fine or not ?
bash~/$wget "http://www.perfectbulksms.in/Sendsmsapi.aspx? USERID=ID&PASSWORD=PASS&SENDERID=SID&TO=$phn&MESSAGE=$sms"
bash~/$curl "http://www.perfectbulksms.in/Sendsmsapi.aspx? USERID=ID&PASSWORD=PASS&SENDERID=SID&TO=$phn&MESSAGE=$sms"
If wget or curl is fine then something wrong with your code.
If wget or curl not working from server then might be port 80 is blocked by your ISP for outgoing traffic. Check with ISP for same.
Also you can try
telnet www.perfectbulksms.in 80
and see if its getting connected or not.
I know there are many different posts concerning this, but none of the posts seemed to help.
I have tried inputting
include_path=".:/path/to/dir"
along with
safe_mode_exec_dir=".:/path/to/dir"
into php.ini. I have tried turning safe_mode on, turning allow_url_fopen to On and then putting ftp:// in front of the path, and without the ftp://. I have tried using multiple different ways of opening it including...
$folder = $_GET['dir'];
$path = $folder;
$file = fopen($path, 'r');
$lines = array();
while(!feof($file)){
$lines[] = fgets($file);
}
fclose($file);
and
$lines = explode("\n", file_get_contents('doc.txt'));
I have tried setting permissions to 777 under /var/www/html and permissions on the other directory which is under /home/pi/
Nothing seems to be working.
So. I am completely out of ideas. Please help before my head banging becomes dangerous.
Here is my code for what I am trying to do...
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$folder = $_GET['dir'];
$path = $folder."/myfile.txt";
$file = fopen($path, 'r');
$lines = array();
while(!feof($file)){
$lines[] = fgets($file);
}
fclose($file);
for($x = 0; $x < sizeof($lines); $x++){
echo $lines[$x];
}
echo '</response>';
?>
xmlHttp = createXmlHttpObject();
xmlHttp.open("GET", "getClientData.php?folder="+dir, false);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && (xmlHttp.status == 200 || xmlHttp.status == 206)) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
var message = xmlDocumentElement.firstChild.textContent;
}
};
xmlHttp.send();
I am running this on a Raspberry Pi 3 Model B, Rasbian Jessie, if that has anything to do with it. And Apache2.
It's interesting to note that when I change the php file a little bit to have an if/else statement like "if(file_exists($path)){}else{echo "null"}", if I call alert() in javascript from the input, I DO get "null". That's why my first assumption was a file permission thing or php.ini setting.
So I have solved it. And I will give a detailed description as to how I solved it.
First of all, do make sure that allow_url_fopen to be On and to have safe_mode off. Look through both the Apache2 php.ini and the regular php.ini as there is two of them and I believe both have to be set in order for it to work. If you installed php with apache2 on your platform, both php.ini files should be under "/etc/php5". There will be a folder called "apache2" and "cli". Each one has a file.
Secondly, Chrome Web Development Tools are amazing. Press F12 with Chrome open and go to the "Networks" tab. There will be a checkbox that says "Disable Cache" at the top of the tab. This makes sure that Chrome won't cache the results of your changes to your website. KEEP THIS WINDOW OPEN BECAUSE IF YOU CLOSE IT, IT WON'T DISABLE THE CACHE ANYMORE!!! You can also download a Chrome extention like "cache killer" which will disable cached results just the same. Also, with CWDT, the Console Tab is a debugging miracle. I have been programming the site on Aptana, which is not very good at all at noticing small semi colon or bracket errors. Utilize this tool! It will save your life as it did mine!!
Please ask questions or comments if I didn't explain something in detail.
I tried to output a simple ping command on a web page in a similar way( and same time) as it is displaying in terminal, using shell_exec; But it is displaying only after the complete execution, while I needed it to display whenever it is displaying on terminal, My code is
<?php
$i= shell_exec("ping -c 4 google.com");
echo "<pre> $i <pre>";
?>
It is waiting for a while and the dumping the whole thing on a single shot.. can PHP recognize the outputting of each line and display it on the web page
EDIT I tried this also
<?php
$proc = popen("ping -c 4 google.com", 'r');
echo '<pre>';
while (!feof($proc)) {
echo fread($proc, 4096);
}
echo '</pre>';
?>
But still I gets the same result..
EDIT When I tried to execute this PHP code in terminal , ( php test.php) it is working properly in the same way it gives when we directly do ping on server. but in web page it is still the same.
Uhm, strange behavior from the web browser. I'm using this code:
<?php
ob_end_flush();
ini_set("output_buffering", "0");
ob_implicit_flush(true);
function pingtest()
{
$proc = popen("ping -c 5 google.com", 'r');
while (!feof($proc))
{
echo "[".date("i:s")."] ".fread($proc, 4096);
}
}
?>
<!DOCTYPE html>
<html>
<body>
<pre>
Immediate output:
<?php
pingtest();
?>
</pre>
</body>
</html>
In the browser the content appears after all bytes has been received.
But, the content is actually delivered on time, do this test:
wget -O - -q "http://localhost/ping.php"
You will see that the response is delivered by php & apache2 on time.
I'm using this kind of execution on long task for a while, but using a more complex solution:
an html file for interface
a php file that run the long task
Connect html interface with php long execution using EventSource object (available on html5)
interface (test.html)
<!DOCTYPE html>
<html>
<head>
<title>Simple EventSource example</title>
</head>
<body>
<script type="text/javascript">
function eventsourcetest() {
var ta = document.getElementById('output');
var source = new EventSource('test.php');
source.addEventListener('message', function(e) {
if (e.data !== '') {
ta.value += e.data + '\n';
}
}, false);
source.addEventListener('error', function(e) {
source.close();
}, false);
}
</script>
<p>Output:<br/><textarea id="output" style="width: 80%; height: 25em;"></textarea></p>
<p><button type="button" onclick="eventsourcetest();">ping google.com</button>
</html>
Server Side Component (test.php)
<?php
ob_end_flush();
ini_set("output_buffering", "0");
ob_implicit_flush(true);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
function echoEvent($datatext) {
echo "data: ".implode("\ndata: ", explode("\n", $datatext))."\n\n";
}
echoEvent("Start!");
$proc = popen("ping -c 5 google.com", 'r');
while (!feof($proc)) {
echoEvent(fread($proc, 4096));
}
echoEvent("Finish!");
Put both files in one place on a webserver and enter test.html, I think this is what you are looking for from the beginning.
Use output buffering and flush. You might also want to look into the Symfony 2 process component.
Its not a PHP matter, or rather its a shared matter between php and the browser.
In PHP: Make sure output buffering is off, you can do this by running ob_end_clean() before outputting anything.
As this SO post suggests you have to either pad the very first string outputted to 512 bytes OR specify a charset encoding via http header. The padding solution may very well be the easiest way around this, its basically this: echo(str_pad("Live Ping Test!",512)); and then start echoing the result of your fread.
You might want to try using flush() to flush the output as and when its ready, and use passthru() to execute the command.
Carlos C Soto is right, you have to use javascript. EventSource is the way to go. Basically, it's javascript code that will constantly call a url
You can write the output of ping in a file, and write a php script that will read the last line, then call this script with eventsource.
Search "Server Sent Events" on the web to find more examples
if can resolve using apache execution user. if your root user is diffrent and server user different then it will not allow to execute command line command.
I tested Carlos's answer on my side...
and I HAD to add flush();ob_flush(); for it to work properly (both needed flush AND ob_flush)
like this
<?php
$proc = popen("ping -c 5 google.com", 'r');
while (!feof($proc))
{
echo "[".date("i:s")."] ".fread($proc, 4096).'<br>';flush();ob_flush();
}
?>