Adding an Array to a php script - php

I have a script that checks a website ($host) for an string of characters ($find). If the string exists the nothing happens, if the string is not found then an email is sent to a pre-set email address.
The problem I have is that I need to have an array of URL's and I believe a second array of text. The text in the array needs to match up to the URL's in the array.
Perhaps storing the URL's and text in a text file(s) might be a better solution.
Here is the script as it is right now, working on the single domain.
<?php
$host = 'www.my-domain.com';
$find = 'content on my page';
function check($host, $find) {
$fp = fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp) {
echo "$errstr ($errno)\n";
} else {
$header = "GET / HTTP/1.1\r\n";
$header .= "Host: $host\r\n";
$header .= "Connection: close\r\n\r\n";
fputs($fp, $header);
while (!feof($fp)) {
$str.= fgets($fp, 1024);
}
fclose($fp);
return (strpos($str, $find) !== false);
}
}
function alert($host) {
mail('mail#my-domain.com', 'Monitoring', $host.' down');
}
if (!check($host, $find)) alert($host);
?>
New code with array in place:
$hostMap = array(
'www.my-domain.com' => 'content on site',
'www.my-domain2.ca' => 'content on second site',
);
foreach ($hostMap as $host => $find)
{
function check($host, $find)
{
$fp = fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp)
{
echo "$errstr ($errno)\n";
} else {
$header = "GET / HTTP/1.1\r\n";
$header .= "Host: $host\r\n";
$header .= "Connection: close\r\n\r\n";
fputs($fp, $header);
while (!feof($fp)) {
$str.= fgets($fp, 1024);
}
fclose($fp);
return (strpos($str, $find) !== false);
}
}
function alert($host)
{
mail('my-email#my-domain.com', 'Website Monitoring', $host.' is down');
}
print $host;
print $find;
//if (!check($host, $find)) alert($host);
if( !check( $host, $find ) )
{
alert($host);
}
}
?>
Moved the functions outside of the foreach(
ini_set( 'display_errors', true );
$hostMap = array(
'www.my-domain.com' => 'content on site',
'www.my-domain2.ca' => 'content on second site',
);
function check($host, $find)
{
$fp = fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp)
{
echo "$errstr ($errno)\n";
} else {
$header = "GET / HTTP/1.1\r\n";
$header .= "Host: $host\r\n";
$header .= "Connection: close\r\n\r\n";
fputs($fp, $header);
while (!feof($fp)) {
$str.= fgets($fp, 1024);
}
fclose($fp);
return (strpos($str, $find) !== false);
}
}
function alert($host)
{
mail('my-email#my-domain.com', 'Website Monitoring', $host.' is down');
}
print $host;
print $find;
//if (!check($host, $find)) alert($host);
foreach ($hostMap as $host => $find)
{
if( !check( $host, $find ) )
{
alert($host);
}
}
?>
Here is the final code with a working Array in case anyone else wants a solution like this.
function check($host, $find)
{
$fp = fsockopen($host, 80, $errno, $errstr, 10);
if (!$fp)
{
echo "$errstr ($errno)\n";
} else {
$header = "GET / HTTP/1.1\r\n";
$header .= "Host: $host\r\n";
$header .= "Connection: close\r\n\r\n";
fputs($fp, $header);
while (!feof($fp)) {
$str.= fgets($fp, 1024);
}
fclose($fp);
return (strpos($str, $find) !== false);
}
}
function alert($host)
{
$headers = 'From: Set your from address here';
mail('my-email#my-domain.com', 'Website Monitoring', $host.' is down' $headers);
}
$hostMap = array(
'www.my-domain.com' => 'content on site',
'www.my-domain2.com' => 'content on second site',
);
//if (!check($host, $find)) alert($host);
foreach ($hostMap as $host => $find)
{
if( !check( $host, $find ) )
{
alert($host);
}
}
unset($host);
unset($find);
?>

$hostMap = array(
'www.my-domain.com' => 'content on my page',
/* etc. */
);
foreach( $hostMap as $host => $find )
{
if( !check( $host, $find ) )
{
alert($host);
}
}
However, be aware that -- depending on the amount of domains you are checking -- sequentially mailing large amounts of mails with PHP's native mail() is not very efficient. You may wanna look in to more specialized mail libraries for that, such as SwiftMailer.
On the other hand -- seeing you are mailing one and the same e-mail address -- you could also simply save the failing domains in an array, and mail them all in one e-mail after you're done checking of course.

You can just store everything in a multidimensional array and put an iterator around the entire working section of code.
$list_of_sites[0]["url"] = blah;
$list_of_sites[0]["text"] = blah;
$list_of_sites[1]["url"] = blah;
$list_of_sites[1]["text"] = blah;
foreach($list_of_sites as $site){
$url = $site["url"];
$text = $site["text"];
check($url, $text);
}

Related

How to print the last string from socket

I'm trying to print the last string from server respone. I'm write the following:
$fp = fsockopen("smtp.mail.ru", 25);
// There is fputs functions
echo fgets($fp);// This is print the first string
But I want to print the last string of the server's response. Is it possible to do?
You can put the strings into array of stings, then print the last string:
<?php
$cntr = 0;
$strarray = [];
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp)
{
echo "$errstr ($errno)<br />\n";
}
else
{
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.example.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp))
{
$strarray[$cntr] = fgets($fp);
$cntr = $cntr + 1;
}
fclose($fp);
}
//Now, print the last string in the array:
echo end($strarray);
?>

Paypal IPN listener always returns INVALID, yet transaction is successful in live paypal

I'm working with the paypal adaptive payments and my IPN listener worked fine in the sandbox, but now that we're testing live transactions, it always returns "INVALID", but the actual money has been transferred.
Any help on why I always receive "INVALD" is appreciated.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Paypal_ipn extends CI_Controller {
public function index() {
log_message('error', '');
log_message('error', '');
log_message('error', '##################');
log_message('error', '##################');
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate&'.file_get_contents("php://input");
$header = null;
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Host: www.sandbox.paypal.com\r\n"; // this line is needed for sandbox, but may not be needed for prod.
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
$raw_post = file_get_contents("php://input");
$post_array = $this->decodePayPalIPN($raw_post);
log_message('error', "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
$log1 = var_export($post_array, true);
log_message('error', $log1);
log_message('error', "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
log_message('error', "sender_email = ".$post_array['sender_email']);
if(isset($post_array['sender_email'])) {
$sender_email = $post_array['sender_email'];
}
if(isset($post_array['status'])) {
$status = $post_array['status'];
}
if(isset($post_array['payment_request_date'])) {
$payment_request_date = $post_array['payment_request_date'];
}
if(isset($post_array['transaction'][0]['receiver'])) {
$receiver0 = $post_array['transaction'][0]['receiver'];
}
if(isset($post_array['transaction'][1]['receiver'])) {
$receiver1 = $post_array['transaction'][1]['receiver'];
}
if(isset($post_array['transaction'][0]['id'])) {
$id0 = $post_array['transaction'][0]['id'];
}
if(isset($post_array['transaction'][1]['id'])) {
$id1 = $post_array['transaction'][1]['id'];
}
if(isset($post_array['transaction'][0]['invoiceId'])) {
$invoiceId0 = $post_array['transaction'][0]['invoiceId'];
}
if(isset($post_array['transaction'][1]['invoiceId'])) {
$invoiceId1 = $post_array['transaction'][1]['invoiceId'];
}
if(isset($post_array['transaction'][0]['amount'])) {
$amount0 = $post_array['transaction'][0]['amount'];
}
if(isset($post_array['transaction'][1]['amount'])) {
$amount1 = $post_array['transaction'][1]['amount'];
}
if(isset($post_array['transaction'][0]['status'])) {
$status0 = $post_array['transaction'][0]['status'];
}
if(isset($post_array['transaction'][1]['status'])) {
$status1 = $post_array['transaction'][1]['status'];
}
if(isset($post_array['transaction'][0]['id_for_sender_txn'])) {
$id_for_sender_txn0 = $post_array['transaction'][0]['id_for_sender_txn'];
}
if(isset($post_array['transaction'][1]['id_for_sender_txn'])) {
$id_for_sender_txn1 = $post_array['transaction'][1]['id_for_sender_txn'];
}
if(isset($post_array['transaction'][0]['status_for_sender_txn'])) {
$status_for_sender_txn0 = $post_array['transaction'][0]['status_for_sender_txn'];
}
if(isset($post_array['transaction'][1]['status_for_sender_txn'])) {
$status_for_sender_txn1 = $post_array['transaction'][1]['status_for_sender_txn'];
}
if(isset($post_array['transaction'][1]['pending_reason'])) {
$pending_reason0 = $post_array['transaction'][1]['pending_reason'];
}
if(isset($post_array['transaction'][1]['pending_reason'])) {
$pending_reason1 = $post_array['transaction'][1]['pending_reason'];
}
if (!$fp) {
log_message('error', 'Problem with !$fp');
// HTTP ERROR
} else {
$counter = 0;
fputs ($fp, $header . $req);
$res = '';
while (!feof($fp)) {
$res .= fgets ($fp, 1024);
log_message('error', "res = $res");
if (strcmp ($res, "VERIFIED") == 0) {
log_message('error', 'we verified');
if($status0 == "Completed") {
log_message('error', 'we completed');
$this->load->model('customer_model');
$results = $this->customer_model->get_invoice_info($invoiceId0);
if($results != false) {
log_message('error', 'results is NOT false');
foreach($results as $row) {
if($row->amount_verified != 1) {
log_message('error', 'row->amount_verified is NOT equal to 1');
log_message('error', "row->amount = ".$row->amount);
if($row->amount == $amount0) {
//log_message('error', 'row->amount is equal to amount0');
if($this->customer_model->verify_amount($invoiceId0)) {
$subject = 'Successful transaction';
$message = 'There was a successful transaction. View the log for details /public_html/application/logs';
$this->_send_email($subject, $message);
}
} else {
//log_message('error', 'we in the else');
//log_message('error', 'invoiceId0 = '.$invoiceId0);
if($this->customer_model->update_amount_and_verify($invoiceId0, $row->amount)) {
//log_message('error', 'we inside update_amount_and_verify');
$subject = 'Successful transaction';
$message = 'There was a successful transaction. View the log for details /public_html/application/logs';
$this->_send_email($subject, $message);
}
}
}
}
} else {
$subject = 'Results Equal False';
$message = 'View the log for details /public_html/application/logs';
$this->_send_email($subject, $message);
}
} else {
$subject = 'Status NOT Complete!';
$message = 'View the log for details /public_html/application/logs';
$this->_send_email($subject, $message);
}
log_message('error', "sender_email = $sender_email");
log_message('error', "payment_request_date = $payment_request_date");
log_message('error', "status = $status");
log_message('error', "receiver0 = $receiver0");
log_message('error', "receiver1 = $receiver1");
log_message('error', "id0 = $id0");
log_message('error', "id1 = $id1");
log_message('error', "invoiceId0 = $invoiceId0");
log_message('error', "invoiceId1 = $invoiceId1");
log_message('error', "amount0 = $amount0");
log_message('error', "amount1 = $amount1");
log_message('error', "status0 = $status0");
log_message('error', "status1 = $status1");
log_message('error', "id_for_sender_txn0 = $id_for_sender_txn0");
log_message('error', "id_for_sender_txn1 = $id_for_sender_txn1");
log_message('error', "status_for_sender_txn0 = $status_for_sender_txn0");
log_message('error', "status_for_sender_txn1 = $status_for_sender_txn1");
log_message('error', "pending_reason0 = $pending_reason0");
log_message('error', "pending_reason1 = $pending_reason1");
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
$counter++;
}
else if (strcmp ($res, "INVALID") == 0) {
log_message('error', 'WE INVALIDDDDDDDDDDDDDDDDDD');
$test = var_export($res, true);
$test = str_replace(array("\r","\n"), '', $test);
log_message('error', $test);
log_message('error', "Problem with IPN. res = $test");
}
}
fclose ($fp);
}
}
function decodePayPalIPN($raw_post)
{
//log_message('error', "testing");
if (empty($raw_post)) {
return array();
} # else:
$post = array();
$pairs = explode('&', $raw_post);
foreach ($pairs as $pair) {
list($key, $value) = explode('=', $pair, 2);
$key = urldecode($key);
$value = urldecode($value);
# This is look for a key as simple as 'return_url' or as complex as 'somekey[x].property'
preg_match('/(\w+)(?:\[(\d+)\])?(?:\.(\w+))?/', $key, $key_parts);
switch (count($key_parts)) {
case 4:
# Original key format: somekey[x].property
# Converting to $post[somekey][x][property]
if (!isset($post[$key_parts[1]])) {
$post[$key_parts[1]] = array($key_parts[2] => array($key_parts[3] => $value));
} else if (!isset($post[$key_parts[1]][$key_parts[2]])) {
$post[$key_parts[1]][$key_parts[2]] = array($key_parts[3] => $value);
} else {
$post[$key_parts[1]][$key_parts[2]][$key_parts[3]] = $value;
}
break;
case 3:
# Original key format: somekey[x]
# Converting to $post[somkey][x]
if (!isset($post[$key_parts[1]])) {
$post[$key_parts[1]] = array();
}
$post[$key_parts[1]][$key_parts[2]] = $value;
break;
default:
# No special format
$post[$key] = $value;
break;
}#switch
}#foreach
return $post;
}#decodePayPalIPN()
private function _send_email($subject, $message) {
//log_message('error', 'we in send_email');
$this->load->library('email');
$this->email->from('do-not-reply#mysite.com', 'Title');
$this->email->to('myemail#gmail.com');
$this->email->subject($subject);
$this->email->message($message);
$this->email->send();
//log_message('error', 'email error = '.$this->email->print_debugger());
}
}
If you are now testing live transactions your code is still showing for sandbox -
$header .= "Host: www.sandbox.paypal.com\r\n"; // this line is needed for sandbox, but may not be needed for prod.
...
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
Make sure that you change to -
// $header .= "Host: www.sandbox.paypal.com\r\n"; line removed, not needed
...
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
did not had a chance to try your code but can you try the code sample we have here on X.com https://www.x.com/developers/PayPal/documentation-tools/code-sample/216623 ? We actually recommend using curl than socket io.

How Do I use curl_post_async() to Run PHP Script in the Background?

I expected the followingcode would create a file, test.txt, in the same directory of the loading script when the page is accessed. But it doesn't. Nothing happens. Could somebody tell what is wrong with this code? Does it work fine in your environment?
<?php
if (isset($_POST['cache']) && $_POST['cache'] === true) {
$file = dirname(__FILE__) . '/test.txt';
$current = time() . ": John Smith\r\n";
file_put_contents($file, $current,FILE_APPEND);
return;
}
curl_post_async(selfurl(), array('cache' => true));
echo 'writing a log in the background.<br />';
return;
function curl_post_async($url, $params) {
//http://stackoverflow.com/questions/124462/asynchronous-php-calls
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
if (isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
function selfurl() {
// http://www.weberdev.com/get_example.php3?ExampleID=4291
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
function strleft($s1, $s2) {
return substr($s1, 0, strpos($s1, $s2));
}
?>
Problem
The error in your script is in the following
if (isset($_POST['cache']) && $_POST['cache'] === true) {
$file = dirname(__FILE__) . '/test.txt';
$current = time() . ": John Smith\r\n";
file_put_contents($file, $current,FILE_APPEND);
return;
}
$_POST['cache'] === true would try to validated of cache with same type as boolean but $_POST['cache'] would actually output 1 when posted over http using current method
Solution
if (isset($_POST['cache'])) {
if ($_POST['cache'] == true) {
$file = dirname(__FILE__) . '/test.txt';
$current = time() . ": John Smith\r\n";
file_put_contents($file, $current, FILE_APPEND);
}
return ;
}

Stay connected to download images with fsockopen?

I've made a basic script to get the html page and images. But I would like to continue to stay connected while I am retrieve pictures.
- What I did with the test script was kept on asking for addresses on the web server. But It did not work. So how do I do it or what have I done wrong?
Basic script:
function fetch( $server, $url, $port = 80, &$resp_head )
{
if ( !$con = #fsockopen($server, $port, $error_number, $error_string, 30) ) return False;
stream_set_timeout( $con, 8600 );
// Reguest
$qry_header = 'GET '.$url." HTTP/1.1\r\n";
$qry_header .= 'Host: '.$server."\r\n";
$qry_header .= 'User-Agent: Mihtyom; (+http://'.$_SERVER['HTTP_HOST']."/)\r\n";
$qry_header .= "Accept: */*\r\n"; //google check the 3 "Accept"
$qry_header .= "Accept-Language: *\r\n";
$qry_header .= "Accept-Encoding: *\r\n";
$qry_header .= "Connection: Close\r\n\r\n";
fwrite( $con, $qry_header );
$inheader = True;
$data = '';
while (!feof( $con ))
{
$line = fgets( $con );
if (!$inheader)
{
$data .= $line;
continue;
}
if ($line == "\n" || $line == "\r\n")
{
$inheader = False;
continue;
}
$resp_head[] = trim($line);
}
fclose( $con );
return $data;
}
Test script:
function fetch( $server, $urls, $port = 80, &$resp_head )
{
if ( !$con = #fsockopen($server, $port, $error_number, $error_string, 30) ) return False;
stream_set_timeout( $con, 8600 );
$resp_head = array();
$data = array();
foreach ($urls as $key => $url)
{
$inheader = True;
$data[$key] = '';
// Reguest
$qry_header = 'GET '.$url." HTTP/1.1\r\n";
$qry_header .= 'Host: '.$server."\r\n";
$qry_header .= 'User-Agent: Mihtyom; (+http://'.$_SERVER['HTTP_HOST']."/)\r\n";
$qry_header .= "Accept: */*\r\n"; //google check the 3 "Accept"
$qry_header .= "Accept-Language: *\r\n";
$qry_header .= "Accept-Encoding: *\r\n";
$qry_header .= "Connection: Close\r\n\r\n";
fwrite( $con, $qry_header );
while (!feof( $con ))
{
$line = fgets( $con );
if (!$inheader)
{
$data[$key] .= $line;
continue;
}
if ($line == "\n" || $line == "\r\n")
{
$inheader = False;
continue;
}
$resp_head[$key][] = trim($line);
}
}
fclose( $con );
return $data;
}
New script (21-07-12 12:34):
function fetch( $server, $urls, $port = 80, &$resp_head )
{
if ( !$con = #pfsockopen($server, $port, $error_number, $error_string, 30) ) return False;
stream_set_timeout( $con, 8600 );
$resp_head = array();
$data = '';
$i = count($urls);
foreach ($urls as $key => $url )
{
$i--;
// Reguest
$qry_header = 'GET '.$url." HTTP/1.1\r\n";
$qry_header .= 'Host: '.$server."\r\n";
$qry_header .= 'User-Agent: Mihtyom; (+http://'.$_SERVER['HTTP_HOST']."/)\r\n";
$qry_header .= "Accept: */*\r\n";
$qry_header .= "Accept-Language: *\r\n";
$qry_header .= "Connection: ".($i == 0 ? 'Close' : 'keep-alive')."\r\n\r\n";
fwrite( $con, $qry_header );
}
while (!feof( $con ))
{
$line = fgets( $con );
if ($line == "\r\n\r\n" || $line == "\n\n") break;
$data .= $line;
}
fclose( $con );
return $data;
}
You specify Connection: Close in the HTTP header, which basically tells the server: "give me this one file and then close the connection immediately". You are actually forcing the connection to close yourself.
Instead, you can specify Connection: Keep-Alive, which tells the server (explicitly) to not close the TCP session so you can reuse it for another request.
However, the server must not accept this in any case - it may ignore your request and answer with Connection: Close. Also, each side of the connection may at any time close the connection and/or tell the other side to do so in the (next) header, via Connection: Close.
For a correct implementation, you should specify Connection: Close when your loop processes the last URL.
Find more details about persistent connections in HTTP 1.1 / RFC 2068 Section 14.10, HTTP 1.1 / RFC 2616 Section 19.6.2.

PHP Infine Loop Problem

function httpGet( $url, $followRedirects=true ) {
global $final_url;
$url_parsed = parse_url($url);
if ( empty($url_parsed['scheme']) ) {
$url_parsed = parse_url('http://'.$url);
}
$final_url = $url_parsed;
$port = $url_parsed["port"];
if ( !$port ) {
$port = 80;
}
$rtn['url']['port'] = $port;
$path = $url_parsed["path"];
if ( empty($path) ) {
$path="/";
}
if ( !empty($url_parsed["query"]) ) {
$path .= "?".$url_parsed["query"];
}
$rtn['url']['path'] = $path;
$host = $url_parsed["host"];
$foundBody = false;
$out = "GET $path HTTP/1.0\r\n";
$out .= "Host: $host\r\n";
$out .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0\r\n";
$out .= "Connection: Close\r\n\r\n";
if ( !$fp = #fsockopen($host, $port, $errno, $errstr, 30) ) {
$rtn['errornumber'] = $errno;
$rtn['errorstring'] = $errstr;
}
fwrite($fp, $out);
while (!#feof($fp)) {
$s = #fgets($fp, 128);
if ( $s == "\r\n" ) {
$foundBody = true;
continue;
}
if ( $foundBody ) {
$body .= $s;
} else {
if ( ($followRedirects) && (stristr($s, "location:") != false) ) {
$redirect = preg_replace("/location:/i", "", $s);
return httpGet( trim($redirect) );
}
$header .= $s;
}
}
fclose($fp);
return(trim($body));
}
This code sometimes go infinite loop. What's wrong here?
There is a big, red warning box in the feof() documentation:
Warning
If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example:
Example #1 Handling timeouts with feof()
<?php
function safe_feof($fp, &start = NULL) {
$start = microtime(true);
return feof($fp);
}
/* Assuming $fp is previously opened by fsockopen() */
$start = NULL;
$timeout = ini_get('default_socket_timeout');
while(!safe_feof($fp, $start) && (microtime(true) - $start) < $timeout)
{
/* Handle */
}
?>
Also you should only write to or read from the file pointer, if it is valid (what you are not doing, you just set an error message):
This leads to the second big red warning box:
Warning
If the passed file pointer is not valid you may get an infinite loop, because feof() fails to return TRUE.
Better would be:
$result = '';
if ( !$fp = #fsockopen($host, $port, $errno, $errstr, 30) ) {
$rtn['errornumber'] = $errno;
$rtn['errorstring'] = $errstr;
}
else {
fwrite($fp, $out);
while (!#feof($fp)) {
//...
}
fclose($fp);
$result = trim(body);
}
return $result;
A last remark: If you follow a redirect with
if ( ($followRedirects) && (stristr($s, "location:") != false) ) {
$redirect = preg_replace("/location:/i", "", $s);
return httpGet( trim($redirect) );
}
you never close the file pointer. I think better is:
if ( ($followRedirects) && (stristr($s, "location:") != false) ) {
$redirect = preg_replace("/location:/i", "", $s);
$result = httpGet( trim($redirect) );
break;
}
// ...
return $result;
feof will return false if the connection is still open in a tcp/ip stream.
function httpGet( $url, $followRedirects=true ) {
[...]
return httpGet( trim($redirect) );
}
Nothing prevents you from fetching the same URL again and again.

Categories