How to replace in PHP? - php

Here's the code I'm currently working with:
try {
// Use '' al default
if(isset($_GET['url'])) {
$url = $_GET['url'];
unset($_GET['url']);
} else {
$url = '';
}
$proxy = new Proxy();
echo $proxy->run($url, $_GET, $_POST);
} catch(Exception $e) {
echo 'Error: '.$e->getMessage();
}
This is the part of the code I'm having issues with specifically:
echo $proxy->run($url, $_GET, $_POST);
This will echo a website after running it through a proxy. What I'm trying to do is replace <head> with the following text: <head> this is a test
So, I tried changing to code to this:
try {
// Use '' al default
if(isset($_GET['url'])) {
$url = $_GET['url'];
unset($_GET['url']);
} else {
$url = '';
}
$proxy = new Proxy();
$proxy_replace = str_replace('<head>','<head> this is a test',$proxy);
echo $proxy_replace->run($url, $_GET, $_POST);
} catch(Exception $e) {
echo 'Error: '.$e->getMessage();
}
But this is the error I'm getting:
Catchable fatal error: Object of class Proxy could not be converted to string in /home/username/public_html/testfolder/index.php on line 249
Any help with this would be greatly appreciated....

You need to perform the replacement on the downloaded HTML, not on the Proxy instance. Something like this should work:
try {
// Use '' al default
if(isset($_GET['url'])) {
$url = $_GET['url'];
unset($_GET['url']);
} else {
$url = '';
}
$proxy = new Proxy();
$html = $proxy->run($url, $_GET, $_POST);
$html_replace = str_replace('<head>','<head> this is a test',$html);
echo $html_replace;
} catch(Exception $e) {
echo 'Error: '.$e->getMessage();
}

Related

PLIVO v3 validation not able to verify signature using PLIVO SDK

I am trying to validate the request received from the plivo to my application server.
For this I am using the sample code provided by the plivo in the documentation.
<?php
require 'vendor/autoload.php';
use Plivo\Exceptions\PlivoValidationException;
use Plivo\Util\v3SignatureValidation;
use Plivo\XML\Response;
if (preg_match('/speak/', $_SERVER["REQUEST_URI"])) {
$auth_token = "<auth_token>";
$signature = #$_SERVER["X-Plivo-Signature-V3"] ?: 'signature';
$nonce = #$_SERVER["X-Plivo-Signature-V3-Nonce"] ?: 'nonce';
$url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$method = $_SERVER['REQUEST_METHOD'];
$SVUtil = new v3SignatureValidation();
if ($method == "GET") {
try {
$valid = $SVUtil->validateV3Signature($method, $url, $nonce, $auth_token, $signature);
} catch (PlivoValidationException $e) {
echo("error");
}
} else {
$body = file_get_contents("php://input");
$params = json_decode($body, true);
try {
$valid = $SVUtil->validateV3Signature($method, $url, $nonce, $auth_token, $signature, $params);
} catch (PlivoValidationException $e) {
echo("error");
}
}
echo $valid;
$body = 'Hi, Calling from Plivo';
$attributes = array(
'loop' => 3,
);
$r = new Response();
$r->addSpeak($body, $attributes);
echo($r->toXML());
} else {
echo "<p>Welcome to Plivo</p>";
}
But I am getting this error
Invalid argument supplied for foreach() in code/plivo/vendor/plivo/plivo-php/src/Plivo/Util/v3SignatureValidation.php on line 13
I am debugging, but not able to find the solution.
One thing I noticed that nothing is being received in json from the PLIVO server.
Can anyone help, as There is not enough documentation available for Plivo Request Validation.
Plivo's Developer Evangelist here. Please try the below code instead.
<?php
require 'vendor/autoload.php';
use Plivo\Exceptions\PlivoValidationException;
use Plivo\Util\v3SignatureValidation;
use Plivo\XML\Response;
if (preg_match('/speak/', $_SERVER["REQUEST_URI"]))
{
$auth_token = "<auth_token>";
$signature = #$_SERVER["HTTP_X_PLIVO_SIGNATURE_V3"] ? : 'signature';
$nonce = #$_SERVER["HTTP_X_PLIVO_SIGNATURE_V3_NONCE"] ? : 'nonce';
$url = $_SERVER['HTTP_REFERER'];
$method = $_SERVER['REQUEST_METHOD'];
$SVUtil = new v3SignatureValidation();
if ($method == "GET")
{
try
{
$valid = $SVUtil->validateV3Signature($method, $url, $nonce, $auth_token, $signature);
}
catch(PlivoValidationException $e)
{
echo ("error");
}
}
else
{
$body = file_get_contents("php://input", true);
parse_str($body, $get_array);
try
{
$valid = $SVUtil->validateV3Signature($method, $url, $nonce, $auth_token, $signature, $get_array);
}
catch(PlivoValidationException $e)
{
echo ("error");
}
}
error_log(print_r($valid, true));
$body = 'Hi, Calling from Plivo';
$attributes = array(
'loop' => 3,
);
$r = new Response();
$r->addSpeak($body, $attributes);
echo ($r->toXML());
}
else
{
echo "<p>Welcome to Plivo</p>";
}
And run the below command
php -S localhost:5000
In case if you still face any issues, please free to contact our support team
src: https://www.plivo.com/docs/voice/concepts/signature-validation#code

Convert procedural code into class for Blobs

So I have the following code that I built out that grabs some images from an Azure storage library:
$accountName = 'teststorageaccount';
$accountKey = '**';
$containerName = 'users';
$connectionString = "DefaultEndpointsProtocol=http;AccountName={$accountName};AccountKey={$accountKey}";
$blobClient = ServicesBuilder::getInstance()->createBlobService($connectionString);
try {
$blob_list = $blobClient->listBlobs($containerName);
$blobs = $blob_list->getBlobs();
// Grab all the blob links
foreach ($blobs as $blob) {
echo $blob->getUrl() . "</br>";
}
} catch(ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
Then I'm getting the following results back:
http://teststorageaccount.blob.core.windows.net/users/ABREUG.jpg
http://teststorageaccount.blob.core.windows.net/users/ABUKHADA.jpg
http://teststorageaccount.blob.core.windows.net/users/ACHANT.jpg
http://teststorageaccount.blob.core.windows.net/users/ACQUISTE.jpg
Now this is where I would need some help .. I'm practicing on building out everything in a class, and this is how far I've come:
class AzureStorage
{
private $accountName;
private $accountKey;
private $containerName;
public static function init()
{
return new AzureStorage([
'accountName' => 'teststorageaccount',
'accountKey' => '***',
'containerName' => 'users',
]);
}
/**************************************************************************/
public function __construct(array $data = [])
{
if (count($data) === 0) {
return;
}
$this->load($data);
}
public function load(array $data) : void
{
if (isset($data['accountName'])) {
$this->accountName = $data['accountName'];
}
if (isset($data['accountKey'])) {
$this->accountKey = $data['accountKey'];
}
if (isset($data['containerName'])) {
$this->containerName = $data['containerName'];
}
}
public function connect()
{
$connectionString = "DefaultEndpointsProtocol=https;AccountName={$this->accountName};AccountKey={$this->accountKey}";
$blobClient = ServicesBuilder::getInstance()->createBlobService($connectionString);
return $blobClient;
}
public function getContainers() : array
{
$containers = $this->connect()->listContainers();
return $containers->getContainers();
}
public function getBlobURLs()
{
try {
$blob_list = $this->connect()->listBlobs($this->containerName);
$blobs = $blob_list->getBlobs();
// Grab all the blob links
foreach ($blobs as $blob) {
echo $blob->getUrl() . "</br>";
}
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
}
}
The problem: How would I be able to use the try and catch inside the getBlobURLs method and then output the results? I'm unable to get results when calling it outside the class.
Here is what I'm doing:
$test2 = new \AzureStorage\AzureStorage([
'accountName' => 'teststorageaccount',
'accountKey' => '***',
'containerName' => 'users',
]);
Now if I call the following (I get an array of containers, which works perfectly):
$containers = $test2->getContainers();
//var_dump($containers);
But if I do the following (I get no results outputted back):
$blobs = $test2->getBlobURLs();
var_dump($blobs);
Does anyone know why I might not be getting the URLs back?
You do have a return statement in getContainers function but not in getBlobURLs.
public function getBlobURLs(){
try {
$blob_list = $this->connect()->listBlobs($this->containerName);
$blobs = $blob_list->getBlobs();
$blobUrls = [];
// Grab all the blob links
foreach ($blobs as $blob) {
$blobUrls[] = $blob->getUrl();
}
return $blobUrls;
} catch (ServiceException $e) {
return false;
}
}
Now if you want to display blob url list then
$blobs = $test2->getBlobURLs();
if($blobs === false){
echo 'Error while getting blob urls.';
}
else{
foreach($blobs as $blobUrl){
echo $blobUrl . "</br>";
}
}

Facebook API - Required param "state" missing from persistent data

I know that this question is a duplicate of another, however after searching Google and Stack Overflow, I have still yet to find a solution.
I have some code which calls the Facebook API for a login URL. However, I am doing it in a somewhat indirect way. Basically here is the server flow:
Client chooses to login to app with FB
Client website (A) sends HTTP GET request to intermediate website (B)
Website B returns login URL on website B which includes 2 callbacks: a login URL to FB generated with fb->getLoginUrl() and a callback to website A.
Website A redirects to login page on Website B which redirects to login page on FB
User logs in and grants permissions to app on FB website
FB redirects to callback on website B which gets the access code.
Website B redirects to Website A callback passing the access code as a $_GET variable
Website A uses the access token as it wishes
So very complicated and I only include the flow to possibly make answering this question and understanding the code in PHP easier.
PHP
Website A Code:
if (!isset($_GET['code'])) {
$callback = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$request_url = "http://embocorp.com/factory/api.php/facebook/login?callback=".$callback;
header("Location: ".implode(json_decode(callAPI("GET", $request_url), true)['body']['data']));
} else {
echo $_GET['code'];
}
Website B Code:
api.php
if (!session_id()) {
session_start();
}
require_once("vendor/autoload.php");
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = $_SERVER['PATH_INFO'];
$table = array_shift($request);
$key = array_shift($request);
parse_str($_SERVER['QUERY_STRING'], $query_array);
$callback = "http://embocorp.com/factory/api.php/facebook/callback?call=";
function returnData($data, $options = "") {
$response = [
"data"=>$data
];
return json_encode($response, $options);
}
function getFacebookConnection($appid, $appsecret) {
return new Facebook\Facebook(['app_id' => $appid,'app_secret' => $appsecret,'default_graph_version' => 'v2.5', 'persistent_data_handler'=>'session']);
}
function facebookHandleRequest($request, $connection, $details = null) {
switch($request) {
case "login":
$callback_url = $GLOBALS["callback"].$GLOBALS['query_array']['callback'];
echo returnData("http://embocorp.com/factory/login.php?fb=".getFacebookLoginURL($connection, $callback_url), JSON_UNESCAPED_SLASHES);
break;
case "callback":
if (!empty($GLOBALS["query_array"])) {
foreach ($_COOKIE as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
$_SESSION[$k]=$v;
}
}
$access = getFacebookAccessCode($connection);
$called = $GLOBALS['query_array']['called'];
header("location: ".$called."?code=".$access);
} else {
echo returnError(400, "Bad Request, missing authorization");
}
break;
case "me":
if (!empty($GLOBALS["query_array"]) && array_key_exists("accessToken", $GLOBALS["query_array"]) == true) {
$response = $connection->sendRequest('GET', '/me', [], $GLOBALS["query_array"]["accessToken"], 'eTag', 'v2.2');
$user = $response->getGraphUser();
echo returnData($user);
} else {
echo returnError(400, "Bad Request, missing authorization");
}
break;
default:
echo returnError(404, "Request URI Not Found");
break;
}
}
function getFacebookLoginURL($connection, $callback_url) {
$helper = $connection->getRedirectLoginHelper();
$permissions = ['manage_pages', 'publish_pages', 'read_insights'];
$loginUrl = $helper->getLoginUrl($callback_url, $permissions);
foreach ($_SESSION as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
if(setcookie($k, $v)) {
$_COOKIE[$k]=$v;
}
}
}
return $loginUrl;
}
function getFacebookAccessCode($fb){
if (!session_id()) {
$accessToken = $_SESSION['facebook_access_token'];
return $accessToken;
} else {
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
$_SESSION['facebook_access_token'] = (string) $accessToken;
return (string) $accessToken;
} else {
return false;
}
}
}
switch ($table) {
case "facebook":
$fb = getFacebookConnection($appid, $appsecret);
facebookHandleRequest($key, $fb);
break;
case "twitter":
echo "no";
break;
default:
exit();
break;
}
session_write_close();
?>
login.php
if (!session_id()) {
session_start();
}
if (isset($_GET['fb'])) {
$redirect = str_replace("fb=", "", $_SERVER['QUERY_STRING']);
header("Location: ".$redirect);
} else {
echo "ni";
}
Again, thank you for any help, this has been driving me crazy for 72 hours now.
Just add,
if (!session_id()) {
session_start();
}
in start both file.

PHP - Define file include in class for all methods to use

Is there a way on including a file at the beginning of a class for all methods to use. The example below is a simplified version of what I am trying to achieve. Currently I have to include the file within every method.
Example Logic (not working)
class Myclass
{
protected require_once 'folerd1/folder2/pear/HTTP/Request2.php'; // this does not work
public function aMethod()
{
$request = new HTTP_Request2('http://example1.com/', HTTP_Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
public function aMethod1()
{
$request = new HTTP_Request2('http://example2.com/', HTTP_Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
// more methods
}
2 solution
1) require_once taken outside from class
require_once 'folerd1/folder2/pear/HTTP/Request2.php';
class Myclass
{
2) Include in the construct
public function __construct() {
require_once 'folerd1/folder2/pear/HTTP/Request2.php';
}
But it is better first option
The best way is to look at autoloading standard http://www.php-fig.org/psr/psr-0/
Have you tried this? I don't know what's your Request2.php file content. So my code is only a PoC!
require 'folerd1/folder2/pear/HTTP/Request2.php';
class Myclass
{
public function aMethod()
{
$request = new Request2('http://example1.com/', Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
public function aMethod1()
{
$request = new Request2('http://example2.com/', Request2::METHOD_GET);
try {
$response = $request->send();
if (200 == $response->getStatus()) {
echo $response->getBody();
} else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
} catch (Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
}
}
As I commented out, just require the file in the constructor of the PHP class:
class Myclass{
function Myclass(){
require_once('folerd1/folder2/pear/HTTP/Request2.php');
}
I have not checked this, but it MIGHT be possible that what you're just doing is including it not only for all the class to see, but the entire script. Please, check that out if it is a problem for you. If not, the other 2 solutions might end up doing the same.
Cheers

Fatal error: cannot use stdClass as array

I've inherited some code from an ex-colleague and as it has recently been put into production it is causing us some issues. I'm not a php developer so apologies if this appears vague but it has fallen to me (don't ask!).
We are calling a function getLoan() to pre-populate an application form from an existing application. This should return an array, but I am receiving the stdClass error.
$result = getLoan(); //this is the line that is erroring
if (isset($result->GetResult->Debtor->Addresses->Address[0])) $current_address = clone $result->GetResult->Debtor->Addresses->Address[0];
else $current_address = clone $result->GetResult->Debtor->Addresses->Address;
if ($result === false)
{
echo("No LID given");
die;
}
$attr = 'selected';
and the function:
function getLoan() {
//globals
/*
global $client;
global $test;
global $result;
*/
global $thisurl;
if (isset($_GET['LID']))
$pLoanID = $_GET['LID'];
else
return false;
$test = array(
"pLoanID" => $pLoanID,
);
//print_r($Address); //print address object as a test
//send to gateway starts**********
$url = "https://www.blahblah.asmx?WSDL";
$client = new SoapClient($url, array("trace" => 1, "exception" => 0));
try {
$result = $client->Get($test);
}
catch(Exception $e) {
//header("Location: http://" . $_SERVER['REMOTE_ADDR'] . "/application-form-new");
print_r($e);
exit;
}
$thisurl = "continue-app?LID=" . $pLoanID;
if (isset($result)) return $result;
else return false;
}
How can I assign the returned value from the function to $result as an array?
Many thanks
array = json_decode(json_encode(object),true);

Categories