This question already has answers here:
How to post data in PHP using file_get_contents?
(3 answers)
Closed 8 years ago.
I have 2 files on a web server in the same directory: post.php and receive.php
The post.php file posts a username and password. The receive.php receives the username and password, and prints them out.
The receive.php file looks like this:
<?php
$user=$_POST["user"];
$password=$_POST["password"];
echo("The Username is : ".$user."<br>");
echo("The Password is : ".$password."<br>");
?>
I have this code for the post.php:
<?php
$r = new HttpRequest('http://localhost/receive.php', HttpRequest::METH_POST);
$r->addPostFields(array('user' => 'mike', 'password' => '1234'));
try {
echo $r->send()->getBody();
} catch (HttpException $ex) {
echo $ex;
}
?>
I tried various different ways of coding the post.php file, but none of them worked. I also tried following some tutorials online, but that didn't work either. I'm a PHP noob, please help!!
The following code for post.php worked for me. I'm not 100% sure what it does, but it works.
<?php
$params = array ('user' => 'Mike', 'password' => '1234');
$query = http_build_query ($params);
// Create Http context details
$contextData = array (
'method' => 'POST',
'header' => "Connection: close\r\n".
"Content-Length: ".strlen($query)."\r\n",
'content'=> $query );
// Create context resource for our request
$context = stream_context_create (array ( 'http' => $contextData ));
// Read page rendered as result of your POST request
$result = file_get_contents (
'http://localhost/receive.php', // page url
false,
$context);
// Server response is now stored in $result variable so you can process it
echo($result);
?>
Sending HTTP request with PHP is possible but not trivial. Have a look at cURL, or better yet - a library like Artax.
Related
Greatings,
Today i Want to Make some task to upload some pdf file using Chat-API whatsapp.
the task maybe I will Run on windows shell, but now I test it on PHP file.
I using the documentation like this
$to = 'myPhone';
$url = 'https://chat-apiurl?andtokenhere';
$imageLocation = 'http://localhost/chat-api/file.pdf';
$data = [
'phone'=> $to,
'body' =>$imageLocation,
'filename'=>"filepdf.jpg",
'caption'=>'test',
];
$send = json_encode($data);
$options = stream_context_create(['http' => [
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $send,
]
]);
// Send a request
$result = file_get_contents($url, false, $options);
echo $result;
?>
if i change the file to online url that's work fine, but when using local file I got the error on result like that
{"error":"Unsupported file type"}
I Have try to convert my file to base 64 but that's return error like this
{"sent":false,"message":"Message was not sent: empty body. Please provide message text in body parameter in JSON POST."}
and that's the way i convert to base64
$getExtension = explode(".",$imageLocation);
$base64 = 'data:image/'.$getExtension[1].';base64,'.file_get_contents($imageLocation);
can anyone help me to send the local file? or maybe have other way to do that. or other API?
Thankyou so much
I know the question was posted a long time ago, but I'll leave the answer in case anyone is looking for a solution.
$base64='data:image/'.$getExtension[1].';base64,'.file_get_contents($imageLocation);
for:
$base64='data:image/'.$getExtension[1].';base64,'.base64_encode(file_get_contents($imageLocation));
I have application which post data to another site(running other application) with API link, and now I need returned feedback like "Application started!" or "error".. I tried to control variable $result but It returns me nothing. Application is started and everything works fine if I visit link with posted results.
If I visit API link manually, it just give me blank page(runned).
proces.php
<?php
if(isset($_POST['submit'])) {
$ssId = $_POST['ssId'];
$red = $_POST['red'];
$id = $_POST['id'];
$user = $_POST['user'];
$postdata = http_build_query(
array(
'ssId' => $ssId,
'red' => $red,
'id' => $id,
'user' => $user
)
);
$opts = array('http' =>
array(
'user' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://apiLink.com/someKey&ssId='.$ssId.'&red='.$red.'&id='.$id.'&user='.$user.'', false, $context);
header("Location: startApp.php");
}
?>
Problem is your current code handles request using $_POST however links trigger http 'GET' method instead of 'POST', also you have some additional checks like $_POST['submit'], hence links redirect fails to work with your logic.
If you replace $_POST with $_REQUEST then things should work with links as well provided you send all the relevant parameters along with it. Other option is just give a button enclosed in form with hidden input fields.
Context
I have the following POST pipeline:
index.php -> submit.php ->list/item/new/index.php
index.php has a normal form with an action="submit.php" property.
submit.php decides where to send the following post request by some logic based on the POST variable content.
The problem is that I haven't found a successful way to debug this pipeline. Somewhere, something is failing and I would appreciate a fresh pair of eyes.
What I have tried
I have tried running list/item/new/index.php with dummy parameters through a regular GET request. DB updates successfully.
I have tried running submit.php (below) with dummy parameters through a regular GET request. The value of $result is not FALSE, indicating the file_get_contents request was successful, but it's value is the literal content of list/new/index.php instead of the generated content, which I expect to be the result of
echo $db->new($hash,$content) && $db->update_content_key($hash);
Here is submit.php
$url = 'list/new/index.php';
if($test){
$content = $_GET["i"];
$hash = $_GET["h"];
}else{
$content = $_POST["item"]["content"];
$hash = $_POST["list"]["hash"];
}
$data = array(
'item'=>array('content' => $content),
'list'=>array('hash' => $hash)
);
$post_content = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n".
"Content-Length: " . strlen($post_content) . "\r\n",
'method' => 'POST',
'content' => $post_content
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
echo "error";
//commenting out for testing. should go back to index.php when it's done
//header('Location: '.$root_folder_path.'list/?h='.$hash.'&f='.$result);
}
else{
var_dump($result);
//commenting out for testing. should go back to index.php when it's done
//header('Location: '.$root_folder_path.'list/?h='.$hash.'&f='.str_replace($root_folder_path,"\n",""));
}
And here is list/item/new/index.php
$db = new sql($root_folder_path."connection_details.php");
if($test){
$content = $_GET["i"];
$hash = $_GET["h"];
}else{
$content = $_POST["item"]["content"];
$hash = $_POST["list"]["hash"];
}
// insert into DB, use preformatted queries to prevent sqlinjection
echo $db->new($hash,$content) && $db->update_content_key($hash);
The worst thing about this is that I don't know enough of PHP to effectively debug this (I actually had it working at some point today but I did not commit right then...).
All comments and suggestions are welcome. I appreciate your time.
Got it.
I'm not sure what to call the error I was making (or what is actually going on behind the scenes) but it was the following:
on the POST request I was using
$url='list/item/new/index.php'
I used the whole url scheme:
$url = 'https://example.com/list/item/new/index.php';`
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'm retrieving a PHP file using file_get_content(), cURL() or fopen() all return PHP code itself. It's not retrieving just the HTML code itself that PHP is outputting. How can I overcome this please?
It's basically generating an HTML newsletter preview for my customer that is generated from their CMS. However I want them to be able to copy and paste the HTML it generates into Mailchimp or such like. It just fetches the entire PHP source code though as well as the HTML :(
Hope you can help.
Thanks in anticipation.
Pete
Trying to read a local PHP file will return its source code, since its a "local" file, and is not parsed by the server.
If you wish to read the result of the PHP file you must request it from the server.
Meaning instead of doing:
$data = file_get_contents('x.php');
You should be doing
$data = file_get_contents('http://mysite.com/path/x.php');
Which will be parsed in the server, and then returned to you.
Cheers! :)
Shai.
This will work in localhost. Try this one: $url = "http://localhost/box.php";
function isAllBoxContents($boxid,$pageNum)
{
$postdata = http_build_query( array('myBoxid' => "$boxid", 'isAllBoxContents' => "all",'pageNum' => "$pageNum",'innerReq' => true ));
$opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ));
$context = stream_context_create($opts);
$url = "http://localhost/box.php";
$result = file_get_contents( $url, false, $context);
$cacheFileName = "isAllBoxContents".$boxid.$pageNum;
cacheMe($cacheFileName,$result);
}