I need to make multiple API calls to the uClassify Sentiment classifier to get the sentiment for a number of tweets. Since I have a lot of tweets to index, simply using cURL is not enough (it takes nearly 2 minutes to fully index around 228 tweets).
Without sentiment analysis, indexing is almost instantaneous so the problem is definitely due to the high number of API calls.
I have instead considered to use the curl_multi_init. Whenever an API call is made, curl_init() is called and rather than processing the call, the handle is added to curl_multi. Once all the handles are added, I use the curl_multi_exec() function to process all the handles.
Here is a simplified version of my application to only show the sentiment part:
$mh = curl_multi_init ();
foreach ($tweets as $tweet){
getSentiment ( $tweet, $mh );
}
executeHandles($mh);
function getSentiment($tweet, $mh) {
$tweet = str_replace ( ' ', '+', $tweet );
$prefix = 'http://uclassify.com/browse/uClassify/Sentiment/ClassifyText?';
$key = 'readkey=' . CLASSIFY_KEY . '&';
$text = 'text=' . $tweet . '&';
$version = 'version=1.01';
$url = $prefix . $key . $text . $version;
// $xml = getXML($url, $mh);
addHandle ( $url, $mh );
// $xml = file_get_contents($url, false, $context); ---- TOO SLOWh
// $mood = parseSentiment($xml);
// return $mood;
}
function addHandle($url, $mh) {
$ch = curl_init ();
$timeout = 5;
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_multi_add_handle ( $mh, $ch );
// $xml = curl_exec($ch);
curl_close ( $ch );
// return $xml;
}
function executeHandles($mh) {
if (! empty ( $mh )) {
$active = null;
// execute the handles
do {
$mrc = curl_multi_exec ( $mh, $active );
} while ( $mrc == CURLM_CALL_MULTI_PERFORM );
while ( $active && $mrc == CURLM_OK ) {
if (curl_multi_select ( $mh ) == - 1) {
usleep ( 100 );
}
do {
$mrc = curl_multi_exec ( $mh, $active );
} while ( $mrc == CURLM_CALL_MULTI_PERFORM );
}
}
}
This is returning
curl_multi_exec(): 12 is not a valid cURL handle resource in C:\xampp\htdocs\Twitter\twitteroauth-master\index.php on line 299
This is referring to this line of code:
$mrc = curl_multi_exec ( $mh, $active );
Now this is just my first time using cURL so I am not sure if I am missing some important detail. I cannot understand why this error is happening, I do not have any curl statements that are happening after curl_close() etc.
Any help would be greatly appreciated, thank you!
so if you need those handles, why did you close them?
function addHandle($url, $mh) {
$ch = curl_init ();
$timeout = 5;
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_multi_add_handle ( $mh, $ch );
}
Related
Here's the code i'm trying to use to connect to the C F E website. Can someone help me with this. I can't find whats wrong with the code.
Even if i changed the codes , i get a (object move to here)
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
$url =
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$fields = array(
'ctl00$PHContenidoPag$UCLogin2$LoginUsuario$UserName' => 'xxxxxxxxxxxx',
'ctl00$PHContenidoPag$UCLogin2$LoginUsuario$Password' => 'xxxxxxxxxxxx',
);
$fields_string = '';
foreach($fields as $key=>$value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output = curl_exec($ch);
$url =
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
echo $output;
you're doing several things wrong. first thing, your $fields_string is incorrectly encoded. in application/x-www-urlencoded, as you're trying to encode, $ must be encoded as %24, but you just send the $ directly. but if you stop to think about it, it should be obvious that your encoding method is wrong, because, what do you think would happen if the username or password contains & ? if there is an & in the username or password, it must be encoded as %26, spaces must be encoded as %20, and so on, use urlencode() to encode them, correcting the encoding loop, it looks like:
foreach($fields as $key=>$value) {
$fields_string .= urlencode($key) . '=' . urlencode($value) . '&';
}
rtrim($fields_string, '&');
but luckily, php has a dedicated function for encoding to application/x-www-urlencoded called http_build_query, that entire loop & trim can (and should be) replaced by this single line:
$fields_string=http_build_query($fields);
second, you make a curl handle, set the CURLOPT_COOKIEJAR, and fetch the login page, i guess you do this to get a cookie session for your login request, which you indeed need to do, but you don't close the first curl handle before you create a brand new curl handle to do the login request. CURLOPT_COOKIEJAR is first flushed when the curl handle is closed, meaning that your first curl handle has not saved the cookies yet becuase you didn't do curl_close, so your second curl handle has no way of loading the first handle's cookies, meaning that it tries to login without a cookie session, which is required to login here.
third, your code completely ignores any setopt errors. curl_setopt returns bool(false) if there was a problem setting your option, which should not be ignored. to make sure there's no problems setting your curl options, i suggest you use this function instead:
function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
$ret=curl_setopt($ch,$option,$value);
if($ret!==true){
//option should be obvious by stack trace
throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' . curl_errno ($ch) .' curl_error: '.curl_error($ch) );
}
return true;
}
fourth, this page appears to employ a CSRF-token-like scheme called __VIEWSTATE and __EVENTVALIDATION , given in the html of the login page load, which is required when logging in, your code completely ignores them, you must parse them out of the html and add them to your login request. i highly recommend DOMDocument/DOMXPath for this (... but the most common (and flawed) method of doing this is regexes...)
fifth, this line is nonsensical, and works by mistake: curl_setopt($ch, CURLOPT_POST, count($fields)); it's supposed to be bool true, not the number of post fields (luckily it works anyway because any int above zero is true-ish, aka close enough, but its still weird and suggest the author don't know what he's doing)
lastly, protip, you can reuse the same curl session as many times as you'd like, there's no reason for you to create 2 curl sessions in this php code. also, when debugging curl code, enable CURLOPT_VERBOSE, it prints lots of useful debugging info.
here's an example code, using hhb_curl as a curl wrapper (taking care of error detection and reporting, cookie handling, etc), doing none of your mistakes, which i think would work with a correct username & password on line 3 and 4:
<?php
declare(strict_types = 1);
const USERNAME = '???';
const PASSWORD = '???';
header ( "content-type: text/plain;charset=utf8" );
require_once ('hhb_.inc.php');
$hc = new hhb_curl ( '', true );
$html = $hc->exec ( 'https://app.cfe.gob.mx/Aplicaciones/CCFE/Recibos/Consulta/login.aspx' )->getStdOut ();
$domd = #DOMDocument::loadHTML ( $html );
$inputsRaw = getDOMDocumentFormInputs ( $domd, true ) ['aspnetForm'];
$inputs = array ();
foreach ( $inputsRaw as $tmp ) {
$inputs [$tmp->getAttribute ( "name" )] = $tmp->getAttribute ( "value" );
}
assert ( isset ( $inputs ['__VIEWSTATE'], $inputs ['__EVENTVALIDATION'] ) );
$inputs ['ctl00$PHContenidoPag$UCLogin2$LoginUsuario$UserName'] = USERNAME;
$inputs ['ctl00$PHContenidoPag$UCLogin2$LoginUsuario$Password'] = PASSWORD;
hhb_var_dump ( $inputs );
$html = $hc->setopt_array ( array (
CURLOPT_URL => 'https://app.cfe.gob.mx/Aplicaciones/CCFE/Recibos/Consulta/login.aspx',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query ( $inputs )
) )->exec ()->getStdOut ();
// hhb_var_dump($html) & die();
$domd = #DOMDocument::loadHTML ( $html );
$xp = new DOMXPath ( $domd );
$loginErrors = $xp->query ( '//*[(contains(#style,"color:Red") or contains(#color,"Red")) and not(contains(#style,"hidden"))]' );
foreach ( $loginErrors as $tmp ) {
echo "login error!! ";
var_dump ( $tmp->textContent );
}
if (0 === $loginErrors->length) {
echo "login success!";
}
function getDOMDocumentFormInputs(\DOMDocument $domd, bool $getOnlyFirstMatches = false): array {
// :DOMNodeList?
$forms = $domd->getElementsByTagName ( 'form' );
$parsedForms = array ();
$isDescendantOf = function (\DOMNode $decendant, \DOMNode $ele): bool {
$parent = $decendant;
while ( NULL !== ($parent = $parent->parentNode) ) {
if ($parent === $ele) {
return true;
}
}
return false;
};
// i can't use array_merge on DOMNodeLists :(
$merged = function () use (&$domd): array {
$ret = array ();
foreach ( $domd->getElementsByTagName ( "input" ) as $input ) {
$ret [] = $input;
}
foreach ( $domd->getElementsByTagName ( "textarea" ) as $textarea ) {
$ret [] = $textarea;
}
foreach ( $domd->getElementsByTagName ( "button" ) as $button ) {
$ret [] = $button;
}
return $ret;
};
$merged = $merged ();
foreach ( $forms as $form ) {
$inputs = function () use (&$domd, &$form, &$isDescendantOf, &$merged): array {
$ret = array ();
foreach ( $merged as $input ) {
// hhb_var_dump ( $input->getAttribute ( "name" ), $input->getAttribute ( "id" ) );
if ($input->hasAttribute ( "disabled" )) {
// ignore disabled elements?
continue;
}
$name = $input->getAttribute ( "name" );
if ($name === '') {
// echo "inputs with no name are ignored when submitted by mainstream browsers (presumably because of specs)... follow suite?", PHP_EOL;
continue;
}
if (! $isDescendantOf ( $input, $form ) && $form->getAttribute ( "id" ) !== '' && $input->getAttribute ( "form" ) !== $form->getAttribute ( "id" )) {
// echo "this input does not belong to this form.", PHP_EOL;
continue;
}
if (! array_key_exists ( $name, $ret )) {
$ret [$name] = array (
$input
);
} else {
$ret [$name] [] = $input;
}
}
return $ret;
};
$inputs = $inputs (); // sorry about that, Eclipse gets unstable on IIFE syntax.
$hasName = true;
$name = $form->getAttribute ( "id" );
if ($name === '') {
$name = $form->getAttribute ( "name" );
if ($name === '') {
$hasName = false;
}
}
if (! $hasName) {
$parsedForms [] = array (
$inputs
);
} else {
if (! array_key_exists ( $name, $parsedForms )) {
$parsedForms [$name] = array (
$inputs
);
} else {
$parsedForms [$name] [] = $tmp;
}
}
}
unset ( $form, $tmp, $hasName, $name, $i, $input );
if ($getOnlyFirstMatches) {
foreach ( $parsedForms as $key => $val ) {
$parsedForms [$key] = $val [0];
}
unset ( $key, $val );
foreach ( $parsedForms as $key1 => $val1 ) {
foreach ( $val1 as $key2 => $val2 ) {
$parsedForms [$key1] [$key2] = $val2 [0];
}
}
}
return $parsedForms;
}
it currently outputs:
login error!! string(35) "Usuario No Existente en Aplicacion."
saying that ??? is not a valid username.
This is what I get when I follow your recommendations. At least I don't get the 'object move to here'. I'm able to get the login page, but that's it. It's not logging in. Try the code and at least you will see what it does. Thanks everyone for your help with this.
<?php
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$fields = array(
'ctl00$PHContenidoPag$UCLogin2$LoginUsuario$UserName' => 'xxx',
'ctl00$PHContenidoPag$UCLogin2$LoginUsuario$Password' => 'xxx',
);
$fields_string = http_build_query($fields);
foreach($fields as $key=>$value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count(1));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$url =
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$output = curl_exec($ch);
echo $output;
?>
Say we have this array
$args = array('responseType' => 'Xml',
'serverName' => 'vl18278.dinaserver.com',
'command' => 'Vps_GetUsedSpace',
) ;
This array composes an URL to send through cURL. I need to replace vl18278.dinaserver.com with a variable $vps, but when I replace it, the URL show a %5B0%5D just before the = sign of the attribute serverName:
responseType=Xml&serverName%5B0%5D=vl18278.dinaserver.com&command=Vps_GetUsedSpace
If I dont replace the vl18278.dinaserver.com, the URL is correct.
What is wrong with my code? Why are those %5B0%5D getting into my URL? :(
Thanks in advance.
Complete code:
<?php
$listavps = simplexml_load_file('servers.xml');
foreach ($listavps->servers->server as $vps) {
$urlApi = 'url.php';
$username = 'user';
$password = 'pass';
$args = array('responseType' => 'Xml',
'serverName' => 'vl18278.dinaserver.com',
'command' => 'Vps_GetUsedSpace',
) ;
$args = ( is_array ( $args ) ? http_build_query ( $args, '', '&' ) : $args );
$headers = array();
$handle = curl_init($urlApi);
if( $handle === false ) // error starting curl
{
$error = '0 - Couldn\'t start curl';
}
else
{
curl_setopt ( $handle, CURLOPT_FOLLOWLOCATION, true );
curl_setopt ( $handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $handle, CURLOPT_URL, $urlApi );
curl_setopt( $handle, CURLOPT_USERPWD, $username.':'.$password );
curl_setopt( $handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt( $handle, CURLOPT_TIMEOUT, 60 );
curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, 4); // set higher if you get a "28 - SSL connection timeout" error
curl_setopt ( $handle, CURLOPT_HEADER, true );
curl_setopt ( $handle, CURLOPT_HTTPHEADER, $headers );
$curlversion = curl_version();
curl_setopt ( $handle, CURLOPT_USERAGENT, 'PHP '.phpversion().' + Curl '.$curlversion['version'] );
curl_setopt ( $handle, CURLOPT_REFERER, null );
curl_setopt ( $handle, CURLOPT_SSL_VERIFYPEER, false ); // set false if you get a "60 - SSL certificate problem" error
curl_setopt ( $handle, CURLOPT_POSTFIELDS, $args );
curl_setopt ( $handle, CURLOPT_POST, true );
$response = curl_exec ( $handle );
echo $args;
if ($response)
{
$response = substr( $response, strpos( $response, "\r\n\r\n" ) + 4 ); // remove http headers
// parse response
$responseSimpleXml = simplexml_load_string($response);
if( $responseSimpleXml === false )
{
// invalid xml response
}
else
{
// parse response
$errorCode = $responseSimpleXml->response->responseCode ;
echo $errorCode;
if( $errorCode == 1000 ) // success
{
$usado = $responseSimpleXml->response->data->total_space;
$capacidad = $responseSimpleXml->response->data->space_limit;
echo 'Usado: '.$usado.'</br>Total: '.$capacidad.'.';
}
else // normal errors
{
$errors = $responseSimpleXml->response->errors;
foreach( $errors->error as $error )
{
// process error
}
}
}
}
else // http response code != 200
{
$error = curl_errno ( $handle ) . ' - ' . curl_error ( $handle );
}
curl_close($handle);
}
}
?>
Your variable $server must be an array, because, once decoded, %5B0%5D is [0].
My guess is to use $server[0] instead of $server wherever you replace the value. Without the replacement code, it is hard to determine.
I solved this using rawurlencode in the $listavps variable before using it.
<?php
$listavps = simplexml_load_file('servers.xml');
foreach ($listavps->servers->server as $key => $tag) {
$vps = rawurlencode ($tag);
$urlApi = 'url.php';
$username = 'user';
$password = 'pass';
$args = array('responseType' => 'Xml',
'serverName' => $vps,
'command' => 'Vps_GetUsedSpace',
) ;
I have some code similar to Jason Lattimer's below that used to work however now fails. I can find the "Identifier" in the wsdl anymore. Can anyone provide assistance on this?
function GetADFS($url) {
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url . "XrmServices/2011/Organization.svc?wsdl=wsdl0" );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
$response = curl_exec ( $ch );
curl_close ( $ch );
$responsedom = new DomDocument ();
$responsedom->loadXML ( $response );
// **************************************************
// **************************************************
// Can no longer find this Identifier
// **************************************************
// **************************************************
$identifiers = $responsedom->getElementsbyTagName ( "Identifier" );
$identifier = $identifiers->item ( 0 )->textContent;
return str_replace ( "http://", "https://", $identifier );
}
It's in namespace 'ms-xrm' so replace
$identifiers = $responsedom->getElementsbyTagName ( "Identifier" );
with
$identifiers = $responsedom->getElementsbyTagNameNS ( "ms-xrm","Identifier" );
and check. Next thing is to check in actual WSDL if you see this node if not then there may be a problem with configuration of your CRM because that node is only available when you are using ADFS.
This file is supposed to redirect to the URl specified in the header but displays blank page.
It displays expected values if you un-comment some of the results.
<?php
sendReceiveOrder($Amnt);
function sendReceiveOrder($Amnt) {
//$ch = curl_init ();
$description = $_POST['gtpay_tranx_memo'];
$receivedXML = "";
$receivedXML .= "<?xml version='1.0' encoding='UTF-8'?>";
$receivedXML .= "<TKKPG>";
$receivedXML .= "<Request>";
$receivedXML .= "</Request>";
$receivedXML .= "</TKKPG>";
// Define POST URL and also payload
//
define ( 'XML_POST_URL', 'http://127.0.0.1:5555/Exec' );
// Initialize handle and set options
$ch = curl_init ();
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch,CURLOPT_MAXREDIRS,50);
if(substr($url,0,8)=='https://'){
// The following ensures SSL always works. A little detail:
// SSL does two things at once:
// 1. it encrypts communication
// 2. it ensures the target party is who it claims to be.
// In short, if the following code is allowed, CURL won't check if the
// certificate is known and valid, however, it still encrypts communication.
curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_ANY);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
}
curl_setopt ( $ch, CURLOPT_URL, XML_POST_URL );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 500 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $receivedXML );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array ('Connection: close' ) );
//---Additional stuff
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/tdpayment/cert/ETECHNOL.pem");
//----------
/**
* Execute the request and also time the transaction
*/
$start = array_sum ( explode ( ' ', microtime () ) );
$result = curl_exec ( $ch );
$stop = array_sum ( explode ( ' ', microtime () ) );
$totalTime = $stop - $start;
/**
* Check for errors
*/
if (curl_errno ( $ch )) {
$result = 'cURL ERROR -> ' . curl_errno ( $ch ) . ': ' . curl_error ( $ch );
} else {
$returnCode = ( int ) curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
switch ($returnCode) {
case 200 :
break;
default :
$result = 'HTTP ERROR -> ' . $returnCode;
break;
}
}
/**
* Close the handle
*/
curl_close ( $ch );
/**
* Output the results and time
*/
//echo 'Total time for request: ' . $totalTime . "\n";
//echo $_SESSION ['Amt'];
//echo $result ;
//echo "<br>";
$_SESSION['store_result'] = $result;
//echo $Amnt;
//echo $description;
//return $result;
/**
* Exit the script
*/
$result2 = <<<XML
<?xml version='1.0' standalone='yes'?>
$result
XML;
$TKKPG = new SimpleXMLElement($result2);
$orderid = $TKKPG->Response->{'Order'}->OrderID;
$sessionid = $TKKPG->Response->{'Order'}->SessionID;
$url = $TKKPG->Response->{'Order'}->URL;
$_SESSION['ordersessionid'] = $orderid.$sessionid;
$header = $url."?sessionid=".$sessionid."&orderid=".$orderid;
header ("Location: ".$header);
exit ( 0 );
}
?>
I use this code to get a response/result from the other server and I want to know how can I check if the site is alive?
$ch = curl_init('http://domain.com/curl.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if (!$result)
// it will execute some codes if there is no result echoed from curl.php
All you really have to do is a HEAD request to see if you get a 200 OK message after redirects. You do not need to do a full body request for this. In fact, you simply shouldn't.
function check_alive($url, $timeout = 10) {
$ch = curl_init($url);
// Set request options
curl_setopt_array($ch, array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_NOBODY => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_USERAGENT => "page-check/1.0"
));
// Execute request
curl_exec($ch);
// Check if an error occurred
if(curl_errno($ch)) {
curl_close($ch);
return false;
}
// Get HTTP response code
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Page is alive if 200 OK is received
return $code === 200;
}
here is the simpler one
<?php
$yourUR="http://sitez.com";
$handles = curl_init($yourUR);
curl_setopt($handles, CURLOPT_NOBODY, true);
curl_exec($handles);
$resultat = curl_getinfo($handles, CURLINFO_HTTP_CODE);
echo $resultat;
?>
Check a web url status by PHP/cURL function :
Condition is , If HTTP status is not 200 or 302, or the requests takes longer than 10 seconds, so the website is unreachable...
<?php
/**
*
* #param string $url URL that must be checked
*/
function url_test( $url ) {
$timeout = 10;
$ch = curl_init();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_TIMEOUT, $timeout );
$http_respond = curl_exec($ch);
$http_respond = trim( strip_tags( $http_respond ) );
$http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
if ( ( $http_code == 200 ) || ( $http_code == 302 ) ) {
return true;
} else {
// you can return $http_code here if necessary or wanted
return false;
}
curl_close( $ch );
}
// simple usage:
$website = "www.example.com";
if( !url_test( $website ) ) {
echo $website ." is down!";
} else {
echo $website ." functions correctly.";
}
?>
You can try with cURL:
curl -I "<URL>" 2>&1 | awk '/HTTP\// {print $2}'
It will return 200 when it's alive
Keep it short and simple...
$string = #file_get_contents('http://domain.com/curl.php');
If $string is null or empty the page is probably unreachable (or actually doesnt output anything).