I want to send a POST request to some file when I load index.php. I use this code:
$query = http_build_query(array('ajax' => 'gwonline', 'session' => $current_session));
$contextData = array (
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
"Connection: close\r\n".
"Content-Length: ".strlen($query)."\r\n",
'content'=> $query );
$context = stream_context_create (array ( 'http' => $contextData ));
$result = file_get_contents(PATH::Includes . 'ajax.php', false, $context);
$result_decoded = json_decode($result, true);
echo '<div id="gwonline">' . ($result_decoded['isonlinestr'] ?: '<span class="fa fa-circle" style="color:orange"></span> Unavailable') . '</div>';
The problem is, $result ends with getting the PHP code instead of whatever the file actually printed. How can I fix it without changing the site to http://... as it's not an option for me at the moment.
Use include with output buffering. file_get_contents is reading the file from the filesystem, it isn't going to use PHP to analyze it. The only reason it works when you use http:// is because then the web server is serving the file, not the filesystem.
ob_start();
include "ajax.php";
$result = ob_get_clean();
Related
This is my code:
if ($_SERVER ["REQUEST_METHOD"] === "GET") {
include_once('../database/dbSource.php');
$databaseSource = DataBaseSource::getInstance();
//Parse
$ini_array = parse_ini_file("../../pto/config.ini");
$user = $_GET['userSid'];
$username = $ini_array['ctsi_CIBMON_fid'];
$password = $ini_array['ctsi_CIBMON_pass'];
$ctsi_url = $ini_array['ctsi_url'] . $user . '&view=full';
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Content-Type: application/json\r\n" . "Accept: application/json\r\n" .
"Authorization: Basic " . base64_encode("$username:$password")
)
);
$context = stream_context_create($opts);
echo file_get_contents($ctsi_url, false, $context);
} else {
echo $_SERVER ["REQUEST_METHOD"];
}
I get the following error :
There was an error parsing the JSON document. The document may not be
well-formed.
I tried checking addiitonal spaces in code (which i removed) etc.
Also there is no issues with authorization.
Can't figure out what's the issue.
Please help.
Note: Also it used to work but stopped working without any change to code even. so Strange.
also the url that i am trying to access is https://xxx.xxx.net not http - does it matter?
I need to send a POST request to another file called global.php, for this I try this code below:
$url = 'global.php';
$data = array('stack' => 'overflow');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
This is the global.php file that should process the request:
if(isset($_POST['stack'])){
echo 'exists';
}else{
echo 'error';
}
The problem is that instead of the command var_dump ($ result); show exists, it shows the PHP code? how can I solve this problem?
And why when I try to do the same thing using ajax it returns me the text exists and not PHP code?
You should use full url, to process php file through server.
$url = 'http://YOURURL.com/global.php';
AJAX call is made from browser, to absolute URL, thats why You are getting desired response.
I setup a function to get the output of another page. But i am only getting back the file contents. I cant figure out why? Here is my code:
$from = date('d.m.Y');
$to = date('d.m.Y', strtotime('+30 day', time()));
$postdata = http_build_query(
array(
'set' => $from,
'to' => $to
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$list = file_get_contents($_SERVER['DOCUMENT_ROOT'] . 'Events.php', false, $context);
file_get_contents() on filesystem will read the file as a text file. You have to call it through its uri instead to get it to execute.
it is not 1 function, but two, alternating what it does given filesystem (pretty much fopen the file, read the entirety of the file, return the content), and what it does given a url (do a GET call on the url, get its contents, return the entirety of its contents)
so just replace $_SERVER['DOCUMENT_ROOT'] with $_SERVER['HTTP_HOST'] and you should be ok
If you want to include another local php file you have to include() or require() it.
$list = include($_SERVER['DOCUMENT_ROOT'] . 'Events.php');
While include() throws a warning if the file does not exist or is unreadable, require() throws a fatal error. With this way you get what the named file returns using the return-keyword.
To get the php output you can use ob_start():
ob_start();
include($_SERVER['DOCUMENT_ROOT'] . 'Events.php');
$list = ob_get_clean();
Another way is to use a separate http-Get but this means more overhead.
i want to send a custom header to a domain.
i tried like the following :
header("myheader: value1");
//i want to redirect above header to a samplesite now
header('Location: http://localhost/samplesite', FALSE);
exit;
And now in samplesite, I could not get myheader.
How to achieve it, please help me.
You can simply send a custom header with file_get_contents() and give it a context.
It would look something like this:
$data = http_build_query(array("username" => $uid));
$opts = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
$context = stream_context_create($opts);
$returnedData= file_get_contents("example.com", false, $context);
Remember that the remote host needs to allow this kind of requests or you will get an error
The header() function you tried to use in your example will just change the header send back from your server so header('Location: http://localhost/samplesite', FALSE); would just be a simple redirect to that site.
If you already have request and you need to add request header, try set function
$request->headers->set('key', $value);
My server does not support cURL.
I want to update my status via php.
How to do that without cURL?
Again: WITHOUT CURL!
Here’s how you can tweet without using cURL with PHP.
We have two options-
With stream context
Php function stream_context_create has the magic. It creates and returns a stream context with any options passed.
<?php
set_time_limit(0);
$username = 'username';
$password= 'WHATEVER';
$message='YOUR NEW STATUS';
function tweet($message, $username, $password)
{
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => sprintf("Authorization: Basic %s\r\n", base64_encode($username.':'.$password)).
"Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query(array('status' => $message)),
'timeout' => 5,
),
));
$ret = file_get_contents('http://twitter.com/statuses/update.xml', false, $context);
return false !== $ret;
}
echo tweet($message, $username, $password);
?>
With socket programing
PHP has a very capable socket programming API. These socket functions include almost everything you need for socket-based client-server communication over TCP/IP. fsockopen opens Internet or Unix domain socket connection.
<?php
$username = 'username';
$password= 'WHATEVER';
$message='YOUR NEW STATUS';
$out="POST http://twitter.com/statuses/update.json HTTP/1.1\r\n"
."Host: twitter.com\r\n"
."Authorization: Basic ".base64_encode ("$username:$password")."\r\n"
."Content-type: application/x-www-form-urlencoded\r\n"
."Content-length: ".strlen ("status=$message")."\r\n"
."Connection: Close\r\n\r\n"
."status=$msg";
$fp = fsockopen ('twitter.com', 80);
fwrite ($fp, $out);
fclose ($fp);
?>
Taken from here: http://www.motyar.info/2010/02/update-twitter-status-with-php-nocurl.html
Hope htis helps.
If you need any more help let me know as i am a php programmer myself.
thanks
PK
<?php
/*
* using file_get_contents
*/
$key = '';
$secret = '';
$api_endpoint = 'https://api.twitter.com/1.1/search/tweets.json?q=news'; // endpoint must support "Application-only authentication"
// request token
$basic_credentials = base64_encode($key.':'.$secret);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Authorization: Basic '.$basic_credentials."\r\n".
"Content-type: application/x-www-form-urlencoded;charset=UTF-8\r\n",
'content' => 'grant_type=client_credentials'
)
);
$context = stream_context_create($opts);
// send request
$pre_token = file_get_contents('https://api.twitter.com/oauth2/token', false, $context);
$token = json_decode($pre_token, true);
if (isset($token["token_type"]) && $token["token_type"] == "bearer"){
$opts = array('http' =>
array(
'method' => 'GET',
'header' => 'Authorization: Bearer '.$token["access_token"]
)
);
$context = stream_context_create($opts);
$data = file_get_contents($api_endpoint, false, $context);
print $data;
}
?>
You can do that using the oauth pecl extension. See here for details.
EDIT: you need to install the pecl extension