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 );
}
?>
Related
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 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 );
}
I am trying to copy a file from localhost to Dropbox account , i'm using curl to generate the token once i get the token i'm using it to upload the file but i'm getting error saying either Token Expired or Does not exist.
Here is my code:
## step1.php ##
<?php
session_start();
require_once('config.php');
$step_2_url = rawurlencode("http://nuftp.com/sanjeev/step-2.php");
$ch = curl_init();
$headers = array( 'Authorization: OAuth oauth_version="1.0",
oauth_signature_method="PLAINTEXT", oauth_consumer_key="' . $app_key . '",
oauth_signature="' . $app_secret . '&"' );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_URL,
"https://api.dropbox.com/1/oauth/request_token" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );
$request_token_response = curl_exec( $ch );
error_log(var_export($request_token_response,true));
parse_str( $request_token_response, $parsed_request_token );
$json_access = json_decode( $request_token_response );
if ( isset( $json_access->error ) ) {
echo '<br><br>FATAL ERROR: ' . $json_access->error . '<br><br>';
die();
}
$_SESSION['myapp'] = array();
$_SESSION['myapp']['oauth_request_token'] =
$parsed_request_token['oauth_token'];
$_SESSION['myapp']['oauth_request_token_secret'] =
$parsed_request_token['oauth_token_secret'];
header( 'Location: https://www.dropbox.com/1/oauth/authorize?oauth_token='
. $parsed_request_token['oauth_token'] . '&oauth_callback=' . $step_2_url );
## step2.php ##
<?php
session_start();
require_once('config.php');
include 'dropbox-sdk-php-1.1.4/lib/Dropbox/autoload.php';
use \Dropbox as dbx;
$step_3_url = "step-3.php";
if ( isset( $_GET['oauth_token'] ) && isset( $_GET['uid'] ) && isset(
$_SESSION['myapp'] ) ) {
$ch = curl_init();
$headers = array( 'Authorization: OAuth oauth_version="1.0",
oauth_signature_method="PLAINTEXT", oauth_consumer_key="' . $app_key .
'", oauth_token="' .$_GET['oauth_token'] . '", oauth_signature="' .
$app_secret . '&' . $_SESSION['myapp']['oauth_request_token_secret'] . '"'
);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_URL,
"https://api.dropbox.com/1/oauth/access_token" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );
$access_token_response = curl_exec( $ch );
error_log(var_export($request_token_response,true));
parse_str( $access_token_response, $parsed_access_token );
error_log( $access_token_response );
$json_access = json_decode( $access_token_response );
if ( isset( $json_access->error ) ) {
echo '<br><br>FATAL ERROR: ' . $json_access->error . '<br><br>';
die();
}
$_SESSION['myapp']['uid'] = $parsed_access_token['uid'];
$_SESSION['myapp']['oauth_access_token'] =
$parsed_access_token['oauth_token'];
$_SESSION['myapp']['oauth_access_token_secret'] =
$parsed_access_token['oauth_token_secret'];
$dbxClient = new dbx\Client($_GET['oauth_token'], "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();
print_r($accountInfo);
$f = fopen("working-draft.txt", "rb");
$result = $dbxClient->uploadFile("/working-draft.txt",
dbx\WriteMode::add(), $f);
fclose($f);
print_r($result);
$folderMetadata = $dbxClient->getMetadataWithChildren("/");
print_r($folderMetadata);
$f = fopen("working-draft.txt", "w+b");
$fileMetadata = $dbxClient->getFile("/working-draft.txt", $f);
fclose($f);
print_r($fileMetadata);
}
Somebody please suggest me what to do and where am i going wrong.
I managed to get another working code and it works absolutely fine. It performs upload and download of files on dropbox. you can get the working code from the link below, however in the code i'm manually changing the names of the files to upload instead of holding it in a variable or giving an option to choose the file from directory.
In case there is any query , comment here and also revert me back on sanjeevks101#gmail.com
Also go through the instructions page first before actually testing the code.
http://www.filehosting.org/file/details/471563/AccessDropboxUsingPHP-master.rar
I have a script where I read a file using:
file_get_contents(urlencode($url));
I get this error:
failed to open stream: HTTP request failed! HTTP/1.0 400 Bad request
I tried this, but I still get the error.
I've tried this:
ini_set('default_socket_timeout', 120);
This:
$opts = array('http'=>array('timeout' => 120));
$context = stream_context_create($opts);
$resul = file_get_contents($url,0,$context);
And this:
$opts = array('http'=>array('timeout' => 120,'header'=>'Connection : close'));
$context = stream_context_create($opts);
$resul = file_get_contents($url,false,$context);
Can you help me figure out why I get the error?
You need encode only "querystring", extract query and enconding this, after append enconded query you "url".
Note: file_get_contents requires allow_url_fopen=On in "php.ini", try use curl
Example (read my comments in code)
Note: This example get error in connection and http errors
<?php
//Set your page example
$uri = 'http://localhost/path/webservice.php?callback=&id=153&provenance=153&ret=a:1:{s:5:"infos";a:8:{s:8:"civilite";s:3:"Mme";s:5:"lname";s:0:"";s:5:"fname";s:8:"Nathalie";s:5:"email";s:17:"tometnata#free.fr";s:3:"tel";s:0:"";s:7:"adresse";s:0:"";s:6:"date_n";s:14:"10:"01/06/1969";s:2:"cp";s:0:"";}}';
//extract url
$parsed_url = parse_url($uri);
//Create fixed url
$fixed_url = $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'];
//If exists query
if (isset($parsed_url['query'])) {
$output = array();
$result = array();
//Extract querystring
parse_str($parsed_url['query'], $output);
//Encode values in querystring
forEach($output as $k => $v) {
$result[] = $k . '=' . rawurlencode($v);
}
//Append encoded querystring
$fixed_url .= '?' . implode('&', $result);
}
echo 'GET url: ', $fixed_url, '<br>';
//Get result in page
$ch = curl_init();
$timeout = 30; //set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, $fixed_url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
$errornum = curl_errno($ch);
$info = curl_getinfo($ch);
$status = (int) $info['http_code'];
if ($errornum !== 0) {
echo 'Error: ', curl_error($ch);
$file_contents = NULL;
} else if ($status !== 200) {
echo 'http_error: ', $status;
$file_contents = NULL;
} else {
echo 'Result:<hr>';
echo $file_contents;
}
curl_close($ch);
?>
Enable curl
Windows (Xampp): https://stackoverflow.com/a/1347340/1518921
Linux (like debian): https://stackoverflow.com/a/11724633/1518921
Mac OSX (probably outdated): https://stackoverflow.com/a/11354731/1518921
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).