Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 11 months ago.
Improve this question
I have a php script that creates an xml sitemap. At the end, I use
shell_exec('ping -c1 www.google.com/webmasters/tools/ping?sitemap=sitemapurl');
to submit the updated sitemap to Google Webmaster tools.
Having read the Google documentation, I'm unsure whether I need to do this each time or not. Entering the link in the code manually, results in a success page from google, but using the ping command I receive no confirmation. I would also like to know if there is any way of checking if the command has actually worked.
Here is a script to automatically submit your site map to google, bing/msn and ask:
/*
* Sitemap Submitter
* Use this script to submit your site maps automatically to Google, Bing.MSN and Ask
* Trigger this script on a schedule of your choosing or after your site map gets updated.
*/
//Set this to be your site map URL
$sitemapUrl = "http://www.example.com/sitemap.xml";
// cUrl handler to ping the Sitemap submission URLs for Search Engines…
function myCurl($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode;
}
//Google
$url = "http://www.google.com/webmasters/sitemaps/ping?sitemap=".$sitemapUrl;
$returnCode = myCurl($url);
echo "<p>Google Sitemaps has been pinged (return code: $returnCode).</p>";
//Bing / MSN
$url = " https://www.bing.com/webmaster/ping.aspx?siteMap=".$sitemapUrl;
$returnCode = myCurl($url);
echo "<p>Bing / MSN Sitemaps has been pinged (return code: $returnCode).</p>";
//ASK
$url = "http://submissions.ask.com/ping?sitemap=".$sitemapUrl;
$returnCode = myCurl($url);
echo "<p>ASK.com Sitemaps has been pinged (return code: $returnCode).</p>";
you can also send yourself an email if the submission fails:
function return_code_check($pingedURL, $returnedCode) {
$to = "webmaster#yoursite.com";
$subject = "Sitemap ping fail: ".$pingedURL;
$message = "Error code ".$returnedCode.". Go check it out!";
$headers = "From: hello#yoursite.com";
if($returnedCode != "200") {
mail($to, $subject, $message, $headers);
}
}
Hope that helps
Since commands like shell_exec(), exec(), passthru() etc. are blocked by many hosters, you should use curl and check for a response code of 200.
You could also use fsockopen if curl is not available. I'm going to check for the code snippet and update the answer when I found it.
UPDATE:
Found it. I knew I used it somewhere. The funny coincedence: It was in my Sitemap class xD
You can find it here on github: https://github.com/func0der/Sitemap. It is in the Sitemap\SitemapOrg class.
There is a also an example for the curl call implemented.
Either way, here is the code for stand alone implementation.
/**
* Call url with fsockopen and return the response status.
*
* #param string $url
* The url to call.
*
* #return mixed(boolean|int)
* The http status code of the response. FALSE if something went wrong.
*/
function _callWithFSockOpen($url) {
$result = FALSE;
// Parse url.
$url = parse_url($url);
// Append query to path.
$url['path'] .= '?'.$url['query'];
// Setup fsockopen.
$port = 80;
$timeout = 10;
$fso = fsockopen($url['host'], $port, $errno, $errstr, $timeout);
// Proceed if connection was successfully opened.
if ($fso) {
// Create headers.
$headers = 'GET ' . $url['path'] . 'HTTP/1.0' . "\r\n";
$headers .= 'Host: ' . $url['host'] . "\r\n";
$headers .= 'Connection: closed' . "\r\n";
$headers .= "\r\n";
// Write headers to socket.
fwrite($fso, $headers);
// Set timeout for stream read/write.
stream_set_timeout($fso, $timeout);
// Use a loop in case something unexpected happens.
// I do not know what, but that why it is unexpected.
while (!feof($fso)){
// 128 bytes is getting the header with the http response code in it.
$buffer = fread($fso, 128);
// Filter only the http status line (first line) and break loop on success.
if(!empty($buffer) && ($buffer = substr($buffer, 0, strpos($buffer, "\r\n")))){
break;
}
}
// Match status.
preg_match('/^HTTP.+\s(\d{3})/', $buffer, $match);
// Extract status.
list(, $status) = $match;
$result = $status;
}
else {
// #XXX: Throw exception here??
}
return (int) $result;
}
If you guys find any harm or improvement in this code, do not hesitate to open up a ticket/pull request on GitHub, please. ;)
Simplest solution: file_get_contents("https://www.google.com/webmasters/tools/ping?sitemap={$sitemap}");
That will work on every major hosting provider. If you want optional error reporting, here's a start:
$data = file_get_contents("https://www.google.com/webmasters/tools/ping?sitemap={$sitemap}");
$status = ( strpos($data,"Sitemap Notification Received") !== false ) ? "OK" : "ERROR";
echo "Submitting Google Sitemap: {$status}\n";
As for how often you should do it, as long as your site can handle the extra traffic from Google's bots without slowing down, you should do this every time a change has been made.
Related
I am writing a php script to interact with a CouchDb server. The script reads an SQL database and creates documents and PUTs them on the server. Each script runs every 5 minutes and puts about 2000 documents (creates and updates).
Running sync, this takes about 3 minutes to PUT all the docs. In a test I did using node and promises, I found CouchDb can handle 100 asnyc puts at the same time and respond back in only slightly more time than it took to do a single document. I want to utilize this feature in PHP instead.
I have available, php 5.3 and php 7.0.10 on a Windows server.
How do I do this asnyc?
My first thought was using the pclose(popen()) trick, but that spawns a new process each time, and even if I restrict this to 100 docs at a time (my tests show up to 700 at a time is doable), that would still results in 6 scripts creating and recreating total of 600 new processes every 100/2000 docs every 5 minutes, or a total of 12,000 processes created and run every 5 minutes. I don't think Windows can handle that.
My second idea was to set up a basic node script to handle it, with PHP creating and formatting the data, writing to a file, and passing the file to a node script to process async and report back to PHP using exec. But I am hoping to find a pure PHP solution.
I currently send requests to couch like this
private function sendJSONRequest($method, $url, $post_data = NULL)
{
// Open socket
$s = fsockopen($this->db_host, $this->db_port, $errno, $errstr);
if (!$s) {
throw new Exception("fsockopen: $errno: $errstr");
}
// Prepare request
$request = "$method $url HTTP/1.0\r\n" .
($this->db_auth === false ? "" : "Authorization: $this->db_auth\r\n") .
"User-Agent: couchdb-php/1.0\r\n" .
"Host: $this->db_host:$this->db_port\r\n" .
"Accept: application/json\r\n" .
"Connection: close\r\n";
if ($method == "POST" || $method == "PUT") {
$json_data = json_encode($post_data);
$request .= "Content-Type: application/json\r\n" .
"Content-Length: " . strlen($json_data) . "\r\n\r\n" .
$json_data;
} else {
$request .= "\r\n";
}
// Send request
fwrite($s, $request);
$response = "";
// Receive response
while (!feof($s)) {
$response .= fgets($s);
}
$headers = array();
$body = '';
$reason = '';
if (!empty($response)) {
// Split header & body
list($header, $body) = explode("\r\n\r\n", $response);
// Parse header
$first = true;
foreach (explode("\r\n", $header) as $line) {
if ($first) {
$status = intval(substr($line, 9, 3));
$reason = substr($line, 13);
$first = false;
} else {
$p = strpos($line, ":");
$headers[strtolower(substr($line, 0, $p))] = substr($line, $p + 2);
}
}
} else {
$status = 200;
}
// Return results
return array($status, $reason, $headers, json_decode($body));
}
My PHP knowledge is only basic, so examples to learn from would be greatly appreciated.
Thank you
Guzzle is a PHP library that helps send HTTP requests and can do so asynchronously. The documentation for the async function can be found here.
It's a litte bit ago since i have researched in this topic, but simply what you are looking for is a queue runner system. At my old employee i have worked with a custom built queue runner in php.
That mean, you have e.g. 4 queue runners. Thats are php processes which are watching a control table maybe "queue". Each time a queue process is inserted in maybe status "new" a runner lock this entry and start the process with a fork job.
PHP forking: http://php.net/manual/de/function.pcntl-fork.php
so... this 4 queue runners can maybe let's say fork 10 processes, than you have 40 parallel working processes.
To seperate them what each do is in best way another control tables from which each job selects a amount of data with LIMIT and OFFSET Queries. Lets say job 1 selects the first 0-20 rows, job 2 the 21-40 rows.
Edit:
After a little research this looks nearly similar to on what i've worked: https://github.com/CoderKungfu/php-queue
While I'm trying to send a GET request to an address with php I receive HTTP 400 BAD REQUEST message and I can't figure out why.
Here's my code:
function redirect($url)
{
error_reporting(E_ERROR | E_PARSE);
$components = parse_url($url);
$port = $components["port"];
$ip = $components["host"];
$path = $components["path"];
//create and connect socket with the parameters entered by the user
//$sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
echo "Establishing connection to the given adress...\n";
//Connection timeout limit is set to 10 seconds...
if(!isset($port))
{
$port = 80;
}
$sock = fsockopen($ip, $port,$errno, $errstr, 10) or die("Unable to connect...");
$request = "GET $path HTTP/1.1" . "\r\n\r\n";
fwrite($sock, $request);
while ($header = stream_get_line($sock, 1024, "\r\n")) {
$response.= $header . "\n";
}
echo $response;
$loc = "";
if (preg_match("/Location:\'(.*)\\n/", $response, $results))
$loc = $results[1];
echo $loc;
}
Any suggestions?
A GET request also contains a header wich include things like the useragent oder the encoding, you should have a look at what you need to send and what's optional
For this specific problem I've found a solution. If you want to get the headers from the request that I sent in the question above, you can use php's get_headers($url) method. It retrieves the headers that I was looking for. I'm really new to protocols and web-services and also to php (1 or 1.5 weeks), therefore I may have asked a silly question and not have been specific enough. Anyways thank you very much for your answers.
Have a nice day!
I'm looking for a PHP script that can be run as a cron job on my web host. It needs to run through a list of websites and check to make sure that each returns the Http response 200 OK. If a site doesn't return that response, or isn't available, it needs to send off an email to the website admin.
I've since refined this script to check to see if your website/webserver is still up and running. I've improved the error handling slightly and added a comfort email to let you know that the script is running successfully.
The comfort email relies on another file called healthcheck.txt to store some values until the script is run the next time. If it doesn't get automatically created, just create a 0 bytes text file, upload it and set the correct file permissions on it (read/write).
<?php
// set email server parameters
ini_set('sendmail_from', 'server.status#host.example.com' );
ini_set('SMTP', '127.0.0.1' );
ini_set('smtp_port', '25' );
ini_set('allow_url_fopen', true); //enable fopen
// define list of webservers to check
$webservers = array('www.example.com', 'www.example2.com');
function sendemail($subject,$message) // email function using standard php mail
{
$wrapmessage = wordwrap($message,70,"\n",true); // mail function can't support a message more than 70 characters per line
$to = 'you#example.com'; // who to send the emails to
// Headers ensure a properly formatted email
$headers = 'From: server.status#host.example.com' . "\r\n" .
'Reply-To: server.status#host.example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
return mail($to, $subject, $wrapmessage, $headers); //send the email
}
function getresponse($url) //queries a url and provides the header returned and header response
{
$ch = curl_init(); // create cURL handle (ch)
if (!$ch) { // send an email if curl can't initialise
$subject = "Web Server Checking Script Error";
$message = "The web server checking script issued an error when it tried to process ".$url.". Curl did not initialise correctly and issued the error - ".curl_error($ch)." The script has died and not completed any more tasks.";
sendemail($subject,$message);
die();
}
// set some cURL options
$ret = curl_setopt($ch, CURLOPT_URL, "http://".$url."/");
$ret = curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
$ret = curl_setopt($ch, CURLOPT_HEADER, true);
$ret = curl_setopt($ch, CURLOPT_NOBODY, true);
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// execute
$ret = curl_exec($ch);
if (empty($ret)) {
// some kind of an error happened
$subject = "Web Server Checking Script Error";
$message = "The web server checking script issued an error when it tried to process ".$url.". Curl was trying to execute and issued the error - ".curl_error($ch)." Further URLs will be tried.";
sendemail($subject,$message);
curl_close($ch); // close cURL handler
} else {
$info = curl_getinfo($ch); //get header info - output is an array
curl_close($ch); // close cURL handler
if (empty($info['http_code'])) {
$subject = "Web Server Checking Script Error";
$message = "The web server checking script issued an error when it tried to process ".$url."\r\nNo HTTP code was returned";
sendemail($subject,$message);
} else {
// load the HTTP code descriptions
$http_codes = parse_ini_file("/server/path/to/http-response-codes.ini");
// results - code number and description
$result = $info['http_code'] . " " . $http_codes[$info['http_code']];
return $result; // $result contained a code, so return it
}
return None; //$info was empty so return nothing
}
return None; // $ret was empty so return nothing
}
// this bit of code initiates the checking of the web server
foreach ($webservers as $webserver) { //loop through the array of webservers
$status = getresponse($webserver); //get the status of the webserver
if (empty($status)) {
// nothing happens here because if $status is empty, the function returned nothing and an email was already sent.
} else {
if (strstr($status, "200")) { //search for the error code that means everything is ok
// If found, don't do anything, just process the next one
} else {
$timestamp = date("m/d/Y H:i:s a", time()); //get the current date and time
$error = $webserver." - ".$status." status error detected"; //set error message with server and response code
$message = "At - ".$timestamp." - a http response error was detected on ".$webserver.".\r\nInstead of a 200 OK response, the server returned ".$status."\r\nThis requires immediate attention!"; //At what time was an error detected on which server and what was the error message
sendemail($error,$message); //trigger the sendemail function
}
}
}
// Health Check. Comfort email twice a day to show script is actually running.
$healthfile = "/server/path/to/healthcheck.txt"; // path with the name of the file to store array data
$hfsize = filesize($healthfile); // filesize of healthcheck file
$notify = "16:00"; // specify the earliest time in the day to send the email - cron job settings dictate how close you'll get to this
$datenow = date("d-m-Y"); //what is current date as of now
if (file_exists($healthfile) && $hfsize !== 0) { //read contents of array from file if it exists and has data, otherwise create array with some defaults
$valuestor = unserialize(file_get_contents($healthfile));
} else { // file doesn't exist so we'll create an array with some defaults
$valuestor = array("email_sent"=>0, "sent_date"=>$datenow, "iterations"=>0);
}
$i = $valuestor['iterations']; //get the iterations number from the valuestor array
$curdate = strtotime($datenow); //convert current date to seconds for comparison
$stordate = strtotime($valuestor['sent_date']); //convert stored date to seconds
if ($valuestor['email_sent'] == 1) { // has the email already been sent today
if ($curdate == $stordate) { // if it has, is the current date equal to the stored date
$i++; // yes it is, just increment the iterations
} else { // it's a new day, reset the array
$timestamp = date("m/d/Y H:i:s a", time()); //get the current date and time
$subject = "Web Server Checking Script Health Status"; //set email subject line
$message = "Message created: ".$timestamp."\r\nThe Web Server Checking script ran successfully for ".$i." time(s) on the ".$valuestor['sent_date']; //email message
sendemail($subject,$message); //trigger the sendemail function
$valuestor['email_sent'] = 0; // set email sent to false
$valuestor['sent_date'] = $datenow; // set email send date to today
$i = 1; // this is the first time the script has run today, so reset i to 1. It gets written to the array later.
// echo $message;
}
} else { // email has not been sent today
$checktime = strtotime($notify); //convert $notify time (for current date) into seconds since the epoch
if (time() >= $checktime) { // are we at or have we gone past checktime
$i++; // increase the number of script iterations by 1
$timestamp = date("m/d/Y H:i:s a", time()); //get the current date and time
$subject = "Web Server Checking Script Health Status"; //set email subject line
$message = "Message created: ".$timestamp."\r\nThe Web Server Checking script has successfully run and completed ".$i." time(s) today."; //email message
sendemail($subject,$message); //trigger the sendemail function
$valuestor['email_sent'] = 1; // set array to show that email has gone
// echo $message;
} else { // we haven't reached the check time yet
$i++; // just increment the iterations
}
}
$valuestor['iterations'] = $i; // update the array with the iterations number
// save the array to the file again
$fp = fopen($healthfile, 'w+'); // open or create the file, clear its contents and write to it
if (!$fp) { // handle the error with an email if the file won't open
$subject = "Web Server Checking Script Error";
$message = "The web server checking script issued an error when trying to open or create the file ".$healthfile." The script was ended without any new information being stored.";
sendemail($subject,$message);
} else {
fwrite($fp, serialize($valuestor)); // write to the file and serialise the array valuestor
fclose($fp); // close the file connection
}
die(); // make sure that script dies and cron job terminates
?>
I found it took me a while to research a good answer to this question. So for the benefit of the community, here's what I came up with after research on Stackoverflow and other forums.
You need two files for this to work. The PHP script that you execute via cron and a ini file that contains detailed descriptions of what the http response codes mean.
I hope this is of use to others.
server-check.php
<?php
// set email server parameters
ini_set('sendmail_from', 'server.status#host.example.com' );
ini_set('SMTP', '127.0.0.1' );
ini_set('smtp_port', '25' );
// define list of webservers to check
$webservers = array('www.example.com', 'www.example2.com');
function sendemail($subject,$message) // email function using standard php mail
{
$wrapmessage = wordwrap($message,70,"\n",true); // mail function can't support a message more than 70 characters per line
$to = 'you#example.com'; // who to send the emails to
// Headers ensure a properly formatted email
$headers = 'From: server.status#host.example.com' . "\r\n" .
'Reply-To: server.status#host.example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
return mail($to, $subject, $wrapmessage, $headers); //send the email
}
function getresponse($url) //queries a url and provides the header returned and header response
{
$ch = curl_init(); // create cURL handle (ch)
if (!$ch) {
$subject = "Web Server Checking Script Error";
$message = "The web server checking script issued an error when it tried to process ".$url."\r\nCouldn't initialize a cURL handle";
sendemail($subject,$message);
die();
}
// set some cURL options
$ret = curl_setopt($ch, CURLOPT_URL, "http://".$url."/");
$ret = curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
$ret = curl_setopt($ch, CURLOPT_HEADER, true);
$ret = curl_setopt($ch, CURLOPT_NOBODY, true);
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// execute
$ret = curl_exec($ch);
if (empty($ret)) {
// some kind of an error happened
$subject = "Web Server Checking Script Error";
$message = "The web server checking script issued an error when it tried to process ".$url."\r\ncurl_error ".$ch;
sendemail($subject,$message);
curl_close($ch); // close cURL handler
die();
} else {
$info = curl_getinfo($ch);
curl_close($ch); // close cURL handler
if (empty($info['http_code'])) {
$subject = "Web Server Checking Script Error";
$message = "The web server checking script issued an error when it tried to process ".$url."\r\nNo HTTP code was returned";
sendemail($subject,$message);
die();
} else {
// load the HTTP codes
$http_codes = parse_ini_file("/server/path/to/http-response-codes.ini");
// results
$result = $info['http_code'] . " " . $http_codes[$info['http_code']];
}
}
return $result;
}
foreach ($webservers as $webserver) { //loop through the array of webservers
$status = getresponse($webserver); //get the status of the webserver
if (strstr($status, "200")) { //search for the error code that means everythings ok
return None; // Don't do anything, just process the next one
} else {
$timestamp = date("m/d/Y H:i:s a", time()); //get the current date and time
$error = $webserver." - ".$status." status error detected"; //set error message with server and response code
$message = "At - ".$timestamp." - a http response error was detected on ".$webserver.".\r\nInstead of a 200 OK response, the server returned ".$status."\r\nThis requires immediate attention!"; //At what time was an error detected on which server and what was the error message
sendemail($error,$message); //trigger the sendemail function
}
}
?>
http-response-codes.ini
[Informational 1xx]
100="Continue"
101="Switching Protocols"
[Successful 2xx]
200="OK"
201="Created"
202="Accepted"
203="Non-Authoritative Information"
204="No Content"
205="Reset Content"
206="Partial Content"
[Redirection 3xx]
300="Multiple Choices"
301="Moved Permanently"
302="Found"
303="See Other"
304="Not Modified"
305="Use Proxy"
306="(Unused)"
307="Temporary Redirect"
[Client Error 4xx]
400="Bad Request"
401="Unauthorized"
402="Payment Required"
403="Forbidden"
404="Not Found"
405="Method Not Allowed"
406="Not Acceptable"
407="Proxy Authentication Required"
408="Request Timeout"
409="Conflict"
410="Gone"
411="Length Required"
412="Precondition Failed"
413="Request Entity Too Large"
414="Request-URI Too Long"
415="Unsupported Media Type"
416="Requested Range Not Satisfiable"
417="Expectation Failed"
[Server Error 5xx]
500="Internal Server Error"
501="Not Implemented"
502="Bad Gateway"
503="Service Unavailable"
504="Gateway Timeout"
505="HTTP Version Not Supported"
how to find the total no.of inbound and outbound links of a website using php?
To count outbound links
parse html for webpage
parse all links using regex
filter links which starts with your domain or "/"
To inbound link
Grab google results page
http://www.google.ca/search?sourceid=chrome&ie=UTF-8&q=site:
parse similarly
For outbound links, you will have to parse the HTML code of the website as some here have suggested.
For inbound links, I suggest using the Google Custom Search API, sending a direct request to google can get your ip banned. You can view the search api here. Here is a function I use in my code for this api:
function doGoogleSearch($searchTerm)
{
$referer = 'http://your-site.com';
$args['q'] = $searchTerm;
$endpoint = 'web';
$url = "http://ajax.googleapis.com/ajax/services/search/".$endpoint;
$args['v'] = '1.0';
$key= 'your-api-key';
$url .= '?'.http_build_query($args, '', '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $referer);
$body = curl_exec($ch);
curl_close($ch);
//decode and return the response
return json_decode($body);
}
After calling this function as: $result = doGoogleSearch('link:site.com'), the variable $result->cursor->estimatedResultCount will have the number of results returned.
PHP can't determine the inbound links of a page through some trivial action. You either have to monitor all incoming visitors and check what their referrer is, or parse the entire internet for links that point to that site. The first method will miss links not getting used, and the second method is best left to Google.
On the other hand, the outbound links from a site is doable. You can read in a page and analyze the text for links with a regular expression, counting up the total.
function getGoogleLinks($host)
{
$request = "http://www.google.com/search?q=" . urlencode("link:" . $host) ."&hl=en";
$data = getPageData($request);
preg_match('/<div id=resultStats>(About )?([\d,]+) result/si', $data, $l);
$value = ($l[2]) ? $l[2] : "n/a";
$string = "" . $value . "";
return $string;
}
//$host means the domain name
I am kinda new to PHP however I used JSP a lot before (I have quite information) and everything was easier with Java classes.
So, now, I want to perform a POST request on a HTTPS page (not HTTP) and need to get returned cookies and past it to another GET request and return the final result. Aim is to make a heavy page for mobile phones more compatible to view in a mobile browser by bypassing the login page and directly taking to the pages which are also served in an ajax user interface.
I am stuck, my code does not work, it says it is Bad Request.
Bad Request
Your browser sent a request that this
server could not understand. Reason:
You're speaking plain HTTP to an
SSL-enabled server port. Instead use
the HTTPS scheme to access this URL,
please.
<?php
$content = '';
$flag = false;
$post_query = 'SOME QUERY'; // name-value pairs
$post_query = urlencode($post_query) . "\r\n";
$host = 'HOST';
$path = 'PATH';
$fp = fsockopen($host, '443');
if ($fp) {
fputs($fp, "POST $path HTTP/1.0\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-length: ". strlen($post_query) ."\r\n\r\n");
fputs($fp, $post_query);
while (!feof($fp)) {
$line = fgets($fp, 10240);
if ($flag) {
$content .= $line;
} else {
$headers .= $line;
if (strlen(trim($line)) == 0) {
$flag = true;
}
}
}
fclose($fp);
}
echo $headers;
echo $content;
?>
From past experience, I've never used PHP's internal functions like fsocketopen() for external data posting. The best way to do these actions are using CURL, which gives much more ease and is massively more powerful for developers to leverage.
for example, look at these functions
http://php.net/curl_setopt
and look at the one with URL, POST, POSTDATA, and COOKIESFILES which is for .JAR, which you get then retrieve and that you can use file_get_contents() to send the data using GET.