PHP cURL and Simple HTML Dom - php

I'm sorry, but I speak a little English only.
I use this:
<?php
function file_get_contents_curl ( $url ) {
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_AUTOREFERER, TRUE );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, TRUE );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); //
curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 ); //
curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; rv:71.0) Gecko/20100101 Firefox/71.0' ); // spoof
$data = curl_exec ( $ch );
curl_close ( $ch );
return $data;
}
include ( __DIR__ . '/simplehtmldom_1_9_1/simple_html_dom.php' );
// 1. OK: $url = 'https://www.p***hub.com/model/ashley-porner';
// 2. OK: $url = 'https://www.p***hub.com/model/ashley-diamond-and-diamond-king';
// 3. NOT OK: $url = 'https://www.p***hub.com/model/ambercashh';
// 4. NOT OK: $url = 'https://www.p***hub.com/model/autumn-raine';
$html = file_get_contents_curl ( $url );
$html = str_get_html ( $html );
var_dump ( $html ); // boolean(false) if NOT OK
?>
The 1-2. URL is ok, but the 3-4. URL is not ok. Not show, no view. The return is false.
I try change from 600000 to 6000000 (~/simplehtmldom_1_9_1/simple_html_dom.php), but the new value is more loading time and than crashed my website:
// OLD: defined('MAX_FILE_SIZE') || define('MAX_FILE_SIZE', 600000);
defined('MAX_FILE_SIZE') || define('MAX_FILE_SIZE', 6000000); // NEW
What is the problem?
Thanks.

As test you can run the following - obviously the urls will need editing but it shows reasonable performance - why you were running out of memory must therefore lie in code not included
<?php
function file_get_contents_curl ( $url ) {
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_AUTOREFERER, TRUE );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, TRUE );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; rv:71.0) Gecko/20100101 Firefox/71.0' ); // spoof
$data = curl_exec ( $ch );
curl_close ( $ch );
return $data;
}
$start=time();
$memstart=memory_get_usage();
$baseurl='https://www.*******.com/model/';
$models=['ashley-porner','ashley-diamond-and-diamond-king','ambercashh','autumn-raine'];
libxml_use_internal_errors( true );
$dom=new DOMDocument;
$dom->validateOnParse=false;
$dom->recover=true;
$dom->strictErrorChecking=false;
/* do some expensive DOM operations to test performance */
$query='//section[ #class="topProfileHeader" ]/div/div/div[ #class="content-columns" ]/div[ #class="infoPiece" ]';
foreach( $models as $model ){
$url = $baseurl . $model;
$res = file_get_contents_curl( $url );
$dom->loadHTML( $res );
$xp=new DOMXPath( $dom );
libxml_clear_errors();
$col=$xp->query( $query );
if( $col->length > 0 ){
foreach( $col as $node ) {
echo str_repeat( '.', strlen( $node->nodeValue ) ) . '<br />';
}
}
}
$memory=memory_get_usage() - $memstart;
printf(
'<div style="padding:1rem; border:1px solid red;">Script took approx: %ss - consumed: %sMb, Peak memory consumption: %sMb</div>',
( time() - $start ),
round( $memory / pow(1024,2), 2 ),
round( memory_get_peak_usage() / pow(1024,2), 2 )
);
?>

Related

Securepay is not working

I have implemented Secure pay payment gateway in my website. It was working fine but from yesterday it is not working. I did not get any response from secure server. Also I am getting an error.
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: libraries/securepay.php
Line Number: 479
In securepay.php 479 number line is
($this->_TranslateServerCode($this->ResponseTree->Status->statusCode) == SECUREPAY_STATUS_OK);
and full function is below
function TestConnection() {
$this->RequestXml = $this->_ComposeEcho();
$this->ResponseXml = $this->_Dispatch($this->RequestXml);
$this->ResponseTree = simplexml_load_string($this->ResponseXml);
return ($this->_TranslateServerCode($this->ResponseTree->Status->statusCode) == SECUREPAY_STATUS_OK);
}
Below is my sample code:
include('securepay.php');
$sp = new SecurePay('ABC0001','abc123', TRUE);
$sp->TestMode();
$sp->TestConnection();
$sp->Cc = 4111111111111111;
$sp->ExpiryDate = '07/20';
$sp->ChargeAmount = 1500;
$sp->ChargeCurrency = 'AUD';
$sp->Cvv = 321;
$sp->OrderId = 'ORD34234';
if ($sp->Valid()) {
$response = $sp->Process();
if ($response == SECUREPAY_STATUS_APPROVED) {
echo "Transaction was a success\n";
} else {
echo "Transaction failed with the error code: $response\n";
echo "XML Dump: " . print_r($sp->ResponseXml,1) . "\n";
}
} else {
die("Your data is invalid\n");
}
Please help me how to solve it.
You can use the following curl REST API code:
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, 'https://test.api.securepay.com.au/xmlapi/payment' );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, false );
curl_setopt ( $ch, CURLOPT_MAXREDIRS, 1 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array (
'Content-Type: application/json'
) );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $jsonRequest );
curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 30 );
$result = curl_exec ( $ch );
Here $jsonRequest will consist of request data like "credit card payment". You can use the following link to find the JSON request data and test it.
SecurePay Sandbox Testing Environment

What is going wrong with this API?

I am coding a website for my friend whom plays Habbo Hotel which is a virtual game. He linked me to some API.
http://habboemotion.com/guide/habinfo & http://habboemotion.com/guide/habboapi
I have been using this code to show the data from the api.
<?php
$info = habbo( "Tyler", "com" );
if( $info ) {
foreach( $info->user AS $name ) {
echo $name->motto;
}
} else {
echo "Habbo not found";
}
?>
Why is nothing appearing? It just appears to be a blank screen.
As the previous person said, make sure to include your habbo() function.
I changed the habbo() function to remove gzip compression and gzinflate(). That seemed to fix the blank page issue. However it seems to take a few seconds to load the page and is on the slow side.
It would also appear that $user->motto isn't allowed. As such, I've replaced it with $friends->motto.
Hope this helps! I am still very new to APIs.
<?php
error_reporting(E_ALL); // Debugging
ini_set('display_errors', 1); // Debugging
function habbo( $name, $hotel ) {
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "https://www.habbo." . $hotel . "/api/public/users" );
curl_setopt( $ch, CURLOPT_HEADER, false );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Accept-Encoding: identity' ) ); // Changed to "identity"
curl_setopt( $ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
$response = curl_exec( $ch ); // Added
//$get = gzinflate( substr( curl_exec( $ch ), 10, -8 ) );
//preg_match( "/setCookie\((.*)\);/", $get, $get );
//$get = explode( ",", str_replace( array( "'", " " ), "", $get[1] ) );
//curl_setopt( $ch, CURLOPT_HTTPHEADER, array( "Cookie:" . $get[0] . "=" . $get[1] ) );
curl_setopt( $ch, CURLOPT_URL, "http://www.habbo." . $hotel . "/api/public/users?name=" . $name );
$id = json_decode( curl_exec( $ch ) );
if( isset( $id ) && $id->profileVisible == 1 ) {
curl_setopt( $ch, CURLOPT_URL, "http://www.habbo." . $hotel . "/api/public/users/" . $id->uniqueId . "/profile" );
$info = json_decode( curl_exec( $ch ) );
} else
$info = false;
curl_close( $ch );
return $info;
}
Here is the function call:
$info = habbo( "Tyler", "com" );
if( $info ) {
foreach( $info->friends AS $friend ) {
echo $friend->motto . "<br />";
}
} else {
echo "habbo not found or homepage hidden";
}
?>

Select HTML content using PHP

I want to get the paragraphs under this tag:
I tried to:
<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("https://sabq.org/xMQjz2");
$elements = $doc->getElementsByTagName('p');
if (!is_null($elements)) {
foreach ($elements as $element) {
$nodes = $element->childNodes;
foreach ($nodes as $node) {
echo $node->textContent. "\n";
}
}
}
?>
And I got the paragraphs I wanted along with unwanted ones, and they were duplicated.
EDIT:
I changed the URL, hope it works
The link that you have provided throws an error when accessing it so what I did, I found a function that could get the contents of the webpage using curl instead of the DOMDocument class which you were using.
I used preg_match and regex to extract the specific element that you were looking for.
Here's the code:
<?php
//opened url
$content = get_fcontent("https://sabq.org/%D8%B4%D8%A7%D9%87%D8%AF-%D8%A3%D9%84%D9%81-%D8%B5%D9%81%D8%AD%D8%A9-%D8%AA%D8%B1%D9%88%D9%8A-%D9%82%D8%B5%D8%B5-%D8%A7%D9%84%D8%AD%D8%B1%D9%85%D9%8A%D9%86-%D9%85%D9%86%D8%B0-%D8%A7%D9%86%D8%B7%D9%84%D8%A7%D9%82-%D8%A7%D9%84%D8%B9%D9%87%D8%AF-%D8%A7%D9%84%D8%B3%D8%B9%D9%88%D8%AF%D9%8A");
//extract specific html tag and its innerHTML
preg_match('/<p .*? ng\-bind\-html\=\"getContent\(material\.content\)\" .*?>.*?<\/p>/m', $content[0], $matches);
//display the wanted element
echo $matches[0];
//getting contents using curl because threw error: failed to open stream
function get_fcontent( $url, $javascript_loop = 0, $timeout = 5 ) {
$url = str_replace( "&", "&", urldecode(trim($url)) );
$cookie = tempnam ("/tmp", "CURLCOOKIE");
$ch = curl_init();
curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_ENCODING, "" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
$content = curl_exec( $ch );
$response = curl_getinfo( $ch );
curl_close ( $ch );
if ($response['http_code'] == 301 || $response['http_code'] == 302) {
ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");
if ( $headers = get_headers($response['url']) ) {
foreach( $headers as $value ) {
if ( substr( strtolower($value), 0, 9 ) == "location:" )
return get_url( trim( substr( $value, 9, strlen($value) ) ) );
}
}
}
if ( ( preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value) ) && $javascript_loop < 5) {
return get_url( $value[1], $javascript_loop+1 );
} else {
return array( $content, $response );
}
}
?>
For testing, I created a local file called test.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>This should not be showing.</p>
<p ng-bind-html="getContent(material.content)" id="dev-content" class="details-text">This is a test.</p>
</body>
</html>
I used the local url http://localhost/example/test.html instead of the link you provided for testing purposes.
And from the local file I created for testing, I got the following result:
<p ng-bind-html="getContent(material.content)" id="dev-content" class="details-text">This is a test.</p>
Here's the result that I got from the original url:
<p ng-bind-html="getContent(material.content)" id="dev-content" class="details-text"></p>
I hope this helps!

Transfer array from one page to another using CURL

Im trying to transfer an array of data between two files.
The sender.php code (the file sending the array using POST method)
$url = 'http://localhost/receiver.php';
$myvars = array("one","two","three")
$post_elements = array('myvars'=>$myvars);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_elements);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
echo "$response";
The receiver.php code (The file receiving the array from sender.php file and then take each element of the array and echo it and also put it in a document saved.txt.
echo $_POST($myvars); // To test the output of the received data.
foreach($myvars as $item) {
if (!empty($item)) {
echo $item."<br>";
$myfile = file_put_contents('Saved.txt', (" Name: ". ($_POST["$item"])) . PHP_EOL , FILE_APPEND);
}
}
The array isn't being transferred to the receiver.php or I am not catching it. In the document output I have only in the place of the variable $item instead of each element of the array.
Edit:
Added the following code in the receiving file in order to get the array elements from inside but all I get is array printed out:
foreach( $_POST as $stuff ) {
if( is_array( $stuff ) ) {
foreach( $stuff as $thing ) {
echo $thing;
}
} else {
echo $stuff;
}
}
By adding on the receiving file the following:
echo "<pre>";
print_r($_POST);
echo "</pre>";
I get the following:
Array
(
[myvars] => Array
)
OK, the bottom line of the discussion in the comments above leads to this result:
The sending part:
<?php
$url = 'http://localhost/out.php';
$myvars = array("one","two","three");
$post_elements = array('myvars'=>$myvars);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($post_elements));
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
print_r($response);
The receiving part:
<?php
print_r($_POST);
The output on the sending side is:
Array ( [myvars] => Array ( [0] => one [1] => two [2] => three ) )
which basically says that you can simply use $_POST['myvars'] on the receiving side which will exactly hold the scalar array you want to transfer.
try to serialize the array because it always helps me :
$url = 'http://localhost/receiver.php';
$myvars = array("one","two","three");
$myvars_post=join(" ",$myvars);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, "array=".urldecode($myvars_post));
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
echo "$response";
and in the receiver.php use :
print_r($_POST);

PHP curl run times

I used curl to get a page online, but can't get full content because the page loading a few times .
If I open that page with browser, maybe wait 20 seconds or more ,the full content show.
I tried use params for curl function ,but it's no use.
The code like below:
$curl = curl_i
$curl=curl_init ();
curl_setopt ( $curl, CURLOPT_URL, $url );
curl_setopt ( $curl, CURLOPT_REFERER, $url );
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $curl, CURLOPT_TIMEOUT, 60 * 3 );
$result = curl_exec ( $curl );
curl_close ( $curl );
Util::dump ( addcslashes ( $result, '/' ) );
How can I do?

Categories