Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
spacebard
Jan 1, 2007

Football~

Experto Crede posted:

When trying to use curl_setopt to get verbose info from a curl_exec, PHP will send the output to stderr, which is fine when you're using cli, but a problem when running it in a web environment.

I know you can just set the error_log using php.ini/ini_set which will save that output to a file, but ideally I'd like the stderr output to be usable someway (ie to save it to a variable, for example) when using code that runs in a browser.

Can this be done easily, or at all?

Can you not get what you need with curl_error() and curl_errno()?

If you use Guzzle, you can catch exceptions fairly easily.

Adbot
ADBOT LOVES YOU

jony neuemonic
Nov 13, 2009

We switched from the built-in curl functions to Guzzle for a few things at work, would definitely recommend switching to it if you can.

Peanut and the Gang
Aug 24, 2009

by exmarx
Does JSON_BIGINT_AS_STRING not work on a 64bit install?

code:
var_dump(json_encode(['a'=>974110684307885632], JSON_BIGINT_AS_STRING));

string(24) "{"a":974110684307885632}"
How can I dump this so JS can read it without converting the 64bit numbers to floats?

e: Or does it just not work on json_encode()?

Peanut and the Gang fucked around with this message at 01:01 on Jul 8, 2014

Peanut and the Gang
Aug 24, 2009

by exmarx
Apparently my problem is some dumb licensing thing. https://bugs.php.net/bug.php?id=63520
People wanted PHP to remove the json implementation they used because it included the text "The Software shall be used for Good, not Evil." and they're saying php can be used for evil. Lol. What a bunch of idiots. Guess I'll just push in a working copy of the json source and recompile.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Peanut and the Gang posted:

People wanted PHP to remove the json implementation they used because it included the text "The Software shall be used for Good, not Evil." and they're saying php can be used for evil.

Na, it's worse than that.

Not being allowed to be evil with software imposes an additional requirement on the source, which makes the JSON license incompatible with a wide variety of OSS licenses, including the GPL. Thus, Debian and Fedora and everyone else hypothetically liable for packaging together software with multiple licenses said "uh yeah no" and switched JSON libraries.

(There's also a running joke that the canonical JSON library was sublicensed to IBM without the evil clause.)

Loving Africa Chaps
Dec 3, 2007


We had not left it yet, but when I would wake in the night, I would lie, listening, homesick for it already.

I'm trying to sanitise a field in a set of RSS feeds i want to archive in a database but having a little trouble.

I'm after the description fields mostly but it seems that because the text lies within a tag <![CDATA]]> like so:

code:
<description>
<![CDATA[
New RCT on intraoperative ventilation strategies is out: PROVHILO. Low tidal volume ventilation (LTVV) has been settled as the way to go, but what about PEEP and recruitment maneuvers? Wouldn&#8217;t high PEEP and regular lung recruitment make sense in patients &#8230; <a href="http://www.scancrit.com/2014/07/01/individual/">Continue reading <span class="meta-nav">&#8594;</span></a>
]]>
</description>
from: http://www.scancrit.com/feed/

all the text gets deleted when i try to sanitize it.

code:
function cleanInput($input) {
 
  $search = array(
    '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
    '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
    '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
    '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
  );
 
    $output = preg_replace($search, '', $input);
    return $output;
  }
  function sanitize($input) {
    if (is_array($input)) {
        foreach($input as $var=>$val) {
            $output[$var] = sanitize($val);
        }
    }
    else {
        if (get_magic_quotes_gpc()) {
            $input = stripslashes($input);
        }
        $input  = cleanInput($input);
        $output = mysql_real_escape_string($input);
    }
    return $output;
}
is the example code i'm using

code:
function clean($text)
{
	$text = strip_tags($text);
	$text = htmlspecialchars($text, ENT_QUOTES);
	
    return ($text); //output clean text
}
works a little better in that the text is there although no special characters but i'm not sure how secure that is

cowboy beepboop
Feb 24, 2001

http://www.php.net/manual/en/filter.filters.sanitize.php

This might help. Alternatively, use this DOM parser http://www.php.net/manual/en/domdocument.loadhtml.php and just grab the parts you want from the DOM. Most importantly, ensure you're using prepared statements to insert any untrusted data into your database.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
You're inappropriately mixing removing bad HTML, removing junk input (magic quotes) and database escaping. Don't do that. Validation, sanitization, input escaping and output escaping are four entirely different things that you should be doing in different areas of your code.

Please go the suggested DOM route to extract the data from the XML, then use an HTMLPurifier-based whitelist to squish the resulting HTML into sanity. Escape when inserting into the database, not before.

McGlockenshire fucked around with this message at 17:42 on Jul 8, 2014

Impotence
Nov 8, 2010
Lipstick Apathy
get_magic_quotes_gpc() will always return false because magic quotes does not exist in PHP..

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Biowarfare posted:

get_magic_quotes_gpc() will always return false because magic quotes does not exist in PHP..

This is only true in recent versions. Given the code in question also still uses ext/mysql, chances are that the code targets older versions where magic quotes are still a threat.

Loving Africa Chaps
Dec 3, 2007


We had not left it yet, but when I would wake in the night, I would lie, listening, homesick for it already.

McGlockenshire posted:

You're inappropriately mixing removing bad HTML, removing junk input (magic quotes) and database escaping. Don't do that. Validation, sanitization, input escaping and output escaping are four entirely different things that you should be doing in different areas of your code.

Please go the suggested DOM route to extract the data from the XML, then use an HTMLPurifier-based whitelist to squish the resulting HTML into sanity. Escape when inserting into the database, not before.

This is great thanks.

Ghostlight
Sep 25, 2009

maybe for one second you can pause; try to step into another person's perspective, and understand that a watermelon is cursing me



I'm getting some weird behaviour using empty() to filter simplexml loaded objects, I'm hoping you guys can give me a pointer as to why.
I'm currently loading English and Chinese articles from xml files, and they share an xml structure but are otherwise separated by folder structure. There's increasing 'bleed' between them, so I'm looking to flatten it and serve the same article from the same xml file with different language fields.

The key trigger is contained in <text> and added <ctext> fields. This code works to filter down to only the articles with Chinese versions:
code:
foreach($globbedarticles as $newsbit) {
$details = simplexml_load_file("$newsbit");
   if(strpos($details->articletype,"News") !== false && !empty($details->ctext)) {	
      if(strpos($details->date,"2014")) { $reel2014[] = objectsIntoArray($details); }
}}
But if I change it to !empty($details->text) it returns absolutely no results. empty($details->text) returns every article, so I assume that ->text is doing a partial string match. What's a good way to resolve this without going through everything and every article and changing ->text references to ->etext ?

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.
You might have to explicitly cast the SimpleXMLElement objects to a string:

(string)$details->ctext;

If you var_dump($details->ctext); vs var_dump((string)$details->ctext); you should see the difference.

LP0 ON FIRE
Jan 25, 2006

beep boop
Is there anything synonymous to shorthand writing a php object array with properties like the javascript below?

code:
var keyTimesAndText = [
		{time:4.773309,  text:"&nbsp;Arctic"},
		{time:11.102234, text:"&nbsp;achievement"},
		{time:21.022100, text:"&nbsp;intelligence"},
		{time:22.960357, text:"&nbsp;perseverance"},
		];
I then have to convert the php array to a javascript one and have it turn out like one here. I hope json_encode will work.

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
php:
<?
$keyTimesAndText = [
        ['time' => 4.773309,  'text' => "&nbsp;Arctic"],
        ['time' => 11.102234, 'text' => "&nbsp;achievement"],
        ['time' => 21.022100, 'text' => "&nbsp;intelligence"],
        ['time' => 22.960357, 'text' => "&nbsp;perseverance"],
        ];
?>
If you don't have php5.5 installed, it's a bit more unruly:


php:
<?
$keyTimesAndText = array(
        array('time' => 4.773309,  'text' => "&nbsp;Arctic"),
        array('time' => 11.102234, 'text' => "&nbsp;achievement"),
        array('time' => 21.022100, 'text' => "&nbsp;intelligence"),
        array('time' => 22.960357, 'text' => "&nbsp;perseverance"),
        );
?>

LP0 ON FIRE
Jan 25, 2006

beep boop

KARMA! posted:

php:
<?
$keyTimesAndText = [
        ['time' => 4.773309,  'text' => "&nbsp;Arctic"],
        ['time' => 11.102234, 'text' => "&nbsp;achievement"],
        ['time' => 21.022100, 'text' => "&nbsp;intelligence"],
        ['time' => 22.960357, 'text' => "&nbsp;perseverance"],
        ];
?>
If you don't have php5.5 installed, it's a bit more unruly:


php:
<?
$keyTimesAndText = array(
        array('time' => 4.773309,  'text' => "&nbsp;Arctic"),
        array('time' => 11.102234, 'text' => "&nbsp;achievement"),
        array('time' => 21.022100, 'text' => "&nbsp;intelligence"),
        array('time' => 22.960357, 'text' => "&nbsp;perseverance"),
        );
?>

The second one worked great! Especially since it worked with json_encode. Thank you!

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.

KARMA! posted:


If you don't have php5.5 installed, it's a bit more unruly:


Slight nit-pick but the Javascript array style came in 5.4 :)

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker

musclecoder posted:

Slight nit-pick but the Javascript array style came in 5.4 :)

Ah, that's what I get for trusting stack overflow. :shobon:

revmoo
May 25, 2006

#basta
Is there a way to specify outgoing ip address with php SCP?

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

revmoo posted:

Is there a way to specify outgoing ip address with php SCP?

I believe you would do that with the ssh2_connect method, and I can't find any way in the docs to use the -b switch. You might have to get all fancy with routing.

Aniki
Mar 21, 2001

Wouldn't fit...
I am working with the DataTables jQuery plugin and since they don't have great support for SQL Server, I am writing my own code to handle table generation, pagination, and ordering. I know what to do on that front, but I am having issues accessing some of the data that is sent via AJAX to the table generation file.

The data appears to be sent as JSON:

code:
// Some data was omitted for the sake of readability
{"sEcho":0,
"iTotalRecords":44198,
"iTotalDisplayRecords":44198,
"order":[{"column":"1","dir":"asc"}],
"start":"0",
"length":"10",
"search":{"value":"","regex":"false"},
"_":"1407713341313"},
"sSearch":null,
"limit":10,
"sTable":"sourceCodes",
"sWhere":"",
"sIndexColumn":"sourceCodeId",
"sOrder":"",
"column":null,
"direction":null}
I can access some variables like iTotalRecords or sSearch by simply using $_GET (e.g. $_GET['iTotalRecords'], $_GET['sSearch']), but some variables like order contain an object or array and I haven't had luck being able to access the data stored in them. I have tried using json_decode to access them as both an object and an array:

php:
<?PHP
// Object
$obj json_decode($_GET['order']);
 
echo $obj->{'column'}; // Outputs null
echo $obj->{'dir'}; // Outputs null
 
// Associative array
$arr json_decode($_GET['order'],true);
echo $arr['column']; // Outputs null
echo $arr['dir']; // Outputs null
?>

And I even tried exploding $_GET['order'], just in case the data was being stored as a string:

php:
<?PHP
// Explodes $_GET['order'] into an array
$arrExplode explode(":",$_GET['order']);
 
echo $arrExplode[0]; // Outputs null
echo $arrExplode[1]; // Outputs null
?>

Any thoughts on what I could do differently, so that I can access the column and dir elements stored in the order object/array? I am running PHP 5.4.0 if that makes a difference.

Aniki fucked around with this message at 00:43 on Aug 11, 2014

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

I would expect that data to come in via POST, not GET.

Aniki
Mar 21, 2001

Wouldn't fit...

Subjunctive posted:

I would expect that data to come in via POST, not GET.

I went ahead and changed it to send data via POST, but it does send data via GET by default:

code:
$(document).ready(function() {
	$( '#example' ).dataTable({
		"processing":	true,
		"serverSide":	true,
		"ajax":			{
			"url":	"AJAX/ajaxSourceCodes4.php",
			"type": "POST"
		}
	});
});
Here I tried accessing them as an object, as an array, and even just directly through POST:

php:
<?PHP
$obj json_decode($_POST['order']);
$arr json_decode($_POST['order'],true);
 
$output = array(
    "sEcho" => intval($_POST['sEcho']),
    "iTotalRecords" => $iTotal,
    "iTotalDisplayRecords" => $iFilteredTotal,
    "limit" => $limit,
    "Order" => $_POST['order'],
    "objColumn" => $obj->{'column'},
    "objDirection" => $obj->{'dir'},
    "arrColumn" => $arr['column'],
    "arrDir" => $arr['dir']
        "postColumn" => $_POST['order']['column'],
        "postDir" => $_POST['order']['dir']
);

echo json_encode$output );
?>

And when I inspect the element and look at the response in the network tab, this is what I get back:

code:
{
"sEcho":0,
"iTotalRecords":44198,
"iTotalDisplayRecords":44198,
"sSearch":null,
"limit":10,
"Order":[{"column":"1","dir":"asc"}],
"objColumn":null,
"objDirection":null,
"arrColumn":null,
"arrDir":null,
"postColumn":null,
"postDir":null
}
I feel like I am missing something really obvious.

Edit: This issue has been resolved now.

Aniki fucked around with this message at 01:37 on Aug 11, 2014

Aniki
Mar 21, 2001

Wouldn't fit...
Ok, I figured it out by doing a var_dump on $_POST['order']. In order to directly access the variables that I needed, I need to call them like:

php:
<?PHP
echo $_POST['order'][0]['column']; // Outputs 2
echo $_POST['order'][0]['dir']; // Outputs asc
?>

I just got caught down a rabbit hole of bad thinking, but at least I can access the data that I need now.

Thanks for your help, just changing things slightly from GET to POST made me think about the problem differently.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

Subjunctive posted:

I would expect that data to come in via POST, not GET.

Why? It's retrieving data from the server, not submitting it to the server. Maybe I've not understood properly though.

Eight Is Legend
Jan 2, 2008
Is there anyone that could help me out with setting this up: http://welcometocreature.com/cheapstaprint/

It's for the annual summer party at my work place and my PHP skills are pretty rusty/almost non-existent at this point :/

v1nce
Sep 19, 2004

Plant your brassicas in may and cover them in mulch.
1. Set up server. Consider using EasyPHP if you don't know what you're doing.
2. Download Cheapstaprint code from github.
3. Extract it so index.php from the code can be run by EasyPHP via the browser.
4. Edit index.php and change $clientId="INSERT YOUR INSTAGRAM CLIENTID"; to be your instagram Client Id. See this article on fetching your instagram Client ID.
5. Browse to the index.php and type in the location you want to search for.

I literally only glanced at the code, but give that a go and let us know if/where you get stuck.

nexus6
Sep 2, 2011

If only you could see what I've seen with your eyes
Does anyone have experience generating secure Paypal Add To Cart buttons with PHP? They have a tool for generating the HTML but it's just a form that anybody could edit with Firebug to change item values. I can't find any examples of creating this button form securely with PHP. I mean, they have an API reference but I've no idea how you actually use that with PHP.

Also, I've had a look at their SDK stuff on github but we don't have composer installed so I'm not clear on how I use any of that stuff.

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING
I have no experience with paypal or that specific API but don't forget that absolutely anything coming from the client is to be considered untrustworthy. I think you're trying to explain that in your post but you're saying things like generating the form securely from PHP which needs to be clarified.

You'd generate the form and validate however you want client-side (i.e. ensuring certain patterns of values are met, doubles in the price column, etc) but that's just as a courtesy to the client and to save complaints. Every single bit of data received by the client is, as you said, inherently suspect, and must be confirmed against your database.

That's when your PHP script take the data and confirms properly that the item IDs are correct, that the prices match, that there is enough stock of those items, etc etc. Then once you've confirmed it's a valid order request, your PHP sends it off to the paypal API to confirm that the purchase is valid (i.e. that they have enough funds or a valid account etc etc).

So you'd have at minimum 3 steps:

1. Client-side form validation as a courtesy for the client to help prevent typos or mistaken prices etc.
2. Actual form validation on the PHP end, which treats every single point of input as actively hostile, rejects any invalid formats, and checks that everything is okay according to the state of your database. (Don't forget your database can have hostile content as well but I won't go into that now)
3. Check with the paypal API to ensure that your token is valid (supplied via your PHP script, not the client-submitted form), their payment details are valid, etc.

Then Paypal will validate everything from there on out and presumably hand you back some token to confirm the successful transaction, and redirect the user back to your site.

Like I said I haven't used the paypal API before but just remember that it doesn't matter if the user mucks around with the HTML on their end, every bit of data sent to you (including form elements, names, data, etc) must be considered hostile by your script and handled accordingly. Just generate a form that holds the user's hand as a courtesy; there's no security client-side whatsoever.

nexus6
Sep 2, 2011

If only you could see what I've seen with your eyes
I get that, but from the generated code it looks like the form is processed on Paypal's end directly. I hoping for something specific: I've not been able to find any PHP examples and the ones I have found have been ~2 years old.

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.

nexus6 posted:

I get that, but from the generated code it looks like the form is processed on Paypal's end directly. I hoping for something specific: I've not been able to find any PHP examples and the ones I have found have been ~2 years old.

PayPal has thought of this and taken care of it, especially if you have an account with them.

After signing into your PayPal account, go here: https://www.paypal.com/us/cgi-bin/webscr?cmd=_singleitem-intro-outside

From there, you can generate a button. I just made a sample one for a single product of $35.00. The resulting HTML looks like this:

code:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
    <input type="hidden" name="cmd" value="_s-xclick">
    <input type="hidden" name="hosted_button_id" value="S279KN37E73QC">
    <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
    <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
As you can see, the entirety of the button contents are stored in a single ID "S279KN37E73QC" which is stored server side on PayPal's servers. Thus, if someone mucks with your form, the only thing they can really change is that value, and if they do, there's nothing they can change it to.

This is a basic PayPal button integration, they click the button, go to PayPal, pay, and then go back to your site. If you need more complex integration than that, you'll have to use the PayPal APIs which are documented quite well here: https://developer.paypal.com/docs/api/

Finally, if you're just selling a few items (and are based in the US), use Gumroad, so much better than PayPal.

Eight Is Legend
Jan 2, 2008

v1nce posted:

1. Set up server. Consider using EasyPHP if you don't know what you're doing.
2. Download Cheapstaprint code from github.
3. Extract it so index.php from the code can be run by EasyPHP via the browser.
4. Edit index.php and change $clientId="INSERT YOUR INSTAGRAM CLIENTID"; to be your instagram Client Id. See this article on fetching your instagram Client ID.
5. Browse to the index.php and type in the location you want to search for.

I literally only glanced at the code, but give that a go and let us know if/where you get stuck.

Hah, that is still a bit too advanced for me. If you could spell it out a little more, I would be really grateful :)

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING

Eight Is Legend posted:

Hah, that is still a bit too advanced for me. If you could spell it out a little more, I would be really grateful :)

Which part in particular are you having issues with? You have to meet him halfway here.

Aniki
Mar 21, 2001

Wouldn't fit...
It is nice to see there is already a PayPal discussion going on. I am working on integrating the PayPal REST API into our system and have run into some issues with namespacing (e.g. use PayPal\Api\Amount;). I am using composer and the code in the sample directory runs fine, but when I move that same code inside of a class*, then it stops working. I have noticed that the errors are different if I include the namespacing inside or outside of the class, but either way the code won't run properly.

Here is an example of a simplified class where the namespacing is declared outside of the class:

php:
<?PHP
// # CreatePaymentSample
//
// This sample code demonstrate how you can process
// a direct credit card payment. Please note that direct 
// credit card payment and related features using the 
// REST API is restricted in some countries.
// API used: /v1/payments/payment

require __DIR__ '/../bootstrap.php';
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\CreditCard;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\FundingInstrument;
use PayPal\Api\Transaction;

class processSale {
    public function directSale() {
        $this->payPalSale();
    }

    //    Processes a sale request using the PayPal REST API
    public function payPalSale() {
        // GET AUTHORIZATION TOKEN
        
        // ### CreditCard
        // A resource representing a credit card that can be
        // used to fund a payment.
        $card    = new CreditCard();
        $card->setType("visa")
            ->setNumber("4417119669820331")
            ->setExpireMonth("11")
            ->setExpireYear("2019")
            ->setCvv2("012")
            ->setFirstName("Joe")
            ->setLastName("Shopper");
                
        // ### FundingInstrument
        // A resource representing a Payer's funding instrument.
        // For direct credit card payments, set the CreditCard
        // field on this object.
        $fi= new FundingInstrument();
        $fi->setCreditCard($card);

        // ### Payer
        // A resource representing a Payer that funds a payment
        // For direct credit card payments, set payment method
        // to 'credit_card' and add an array of funding instruments.
        $payer = new Payer();
        $payer->setPaymentMethod("credit_card")
            ->setFundingInstruments(array($fi));

        // ### Additional payment details
        // Use this optional field to set additional
        // payment information such as tax, shipping
        // charges etc.
        $details = new Details();
        $details->setShipping('1.20')
            ->setTax('1.30')
            ->setSubtotal('17.50');
            
        // ### Amount
        // Lets you specify a payment amount.
        // You can also specify additional details
        // such as shipping, tax.
        $amount = new Amount();
        $amount->setCurrency("USD")
            ->setTotal("20.00")
            ->setDetails($details);

        // ### Transaction
        // A transaction defines the contract of a
        // payment - what is the payment for and who
        // is fulfilling it. 
        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setDescription("Payment description");

        // ### Payment
        // A Payment Resource; create one using
        // the above types and intent set to sale 'sale'
        $payment = new Payment();
        $payment->setIntent("sale")
            ->setPayer($payer)
            ->setTransactions(array($transaction));

        // ### Create Payment
        // Create a payment by calling the payment->create() method
        // with a valid ApiContext (See bootstrap.php for more on `ApiContext`)
        // The return object contains the state.
        try {
            $payment->create($apiContext);
            echo $payment->getId() . "<br />";
            echo $payment->getIntent() . "<br />";
            echo $payment->getState() . "<br />";
        } catch (PayPal\Exception\PPConnectionException $ex) {
            echo "Exception: " $ex->getMessage() . PHP_EOL;
            //"<Pre>" . var_dump($ex->getData()) . "</Pre>";
            $arrException json_decode($ex->getData(), true);
            echo $arrException['name'] . "<br />";
            echo $arrException['details'][0]['issue'] . "<br />";
            echo $arrException['debug_id'] . "<br />";
            exit(1);
        }        
    }
}

$saleRequest = new processSale;
$saleRequest->directSale();
?>

And it yields the following error:

quote:

Notice: Undefined variable: apiContext in C:\xampp\htdocs\PaymentTest\rest-api-sdk-php-master\sample\payments\paymentClassTest.php on line 97

Fatal error: Uncaught exception 'PayPal\Exception\PPConfigurationException' with message 'Config file C:\xampp\htdocs\PaymentTest\rest-api-sdk-php-master\sample\vendor\paypal\sdk-core-php\lib\PayPal\Core\..\config\sdk_config.ini not found' in C:\xampp\htdocs\PaymentTest\rest-api-sdk-php-master\sample\vendor\paypal\sdk-core-php\lib\PayPal\Core\PPConfigManager.php:50 Stack trace: #0 C:\xampp\htdocs\PaymentTest\rest-api-sdk-php-master\sample\vendor\paypal\sdk-core-php\lib\PayPal\Core\PPConfigManager.php(33): PayPal\Core\PPConfigManager->load('C:\\xampp\\htdocs...') #1 C:\xampp\htdocs\PaymentTest\rest-api-sdk-php-master\sample\vendor\paypal\sdk-core-php\lib\PayPal\Core\PPConfigManager.php(40): PayPal\Core\PPConfigManager->__construct() #2 C:\xampp\htdocs\PaymentTest\rest-api-sdk-php-master\sample\vendor\paypal\sdk-core-php\lib\PayPal\Common\PPApiContext.php(23): PayPal\Core\PPConfigManager::getInstance() #3 C:\xampp\htdocs\PaymentTest\rest-api-sdk-php-master\sample\vendor\paypal\sdk-core-php\lib\PayPal\Transport\PPRestCall.ph in C:\xampp\htdocs\PaymentTest\rest-api-sdk-php-master\sample\vendor\paypal\sdk-core-php\lib\PayPal\Core\PPConfigManager.php on line 50

Line 97 is where I run, "$payment->create($apiContext);" and I am assuming that it is not running due to a scope issue with the class and namespacing. With that in mind, I had tried moving the namespace calls inside of the class (moved into public function payPalSale()) to see if that made a difference and received the following error:

quote:

Parse error: syntax error, unexpected 'use' (T_USE) in C:\xampp\htdocs\PaymentTest\rest-api-sdk-php-master\sample\payments\paymentClassTest.php on line 19

So moving the namespace code inside of the class and function did not help things. I am sure that I am missing something basic about scope here, so any help would be appreciated.

*We use multiple payment gateways, so I wrote a class that allows us to use generic calls that route to the proper gateway and then return a consistent set of results.

Edit: I am using PHP Version 5.5.15 in XAMPP for testing purposes.

Aniki fucked around with this message at 18:56 on Sep 4, 2014

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.
Doesn't look like a class issue, the variable $apiContext has never been defined anywhere. And if it's defined in bootstrap.php you either need to use the global keyword to use it in the payPalSale() function (yuck, don't do this) or pass it into the object (do this instead).

Also, use the full path to the PayPal exception in the catch: catch (\PayPal\Exception\PPConnectionException $ex) to actually catch it.

Aniki
Mar 21, 2001

Wouldn't fit...

musclecoder posted:

Doesn't look like a class issue, the variable $apiContext has never been defined anywhere. And if it's defined in bootstrap.php you either need to use the global keyword to use it in the payPalSale() function (yuck, don't do this) or pass it into the object (do this instead).

Also, use the full path to the PayPal exception in the catch: catch (\PayPal\Exception\PPConnectionException $ex) to actually catch it.

Thank you very much for your help, it looks like $apiContext is defined in bootstrap.php and when the code was outside of the class, it could access that value, but inside of the class it could not access that variable, so it was a scope issue but as you said the scope issue was with $apiContext and not the namespacing. To get around that I can make $apiContext a global variable in bootstrap.php ($GLOBALS['apiContenxt']), I can call the getApiContext() function inside of the class, or I can pass it to object.

What would you suggest instead of payPalSale()? Is it a naming convention issue or is there an issue with how it is structured? I included a very simplified version of the code, but here is a little more of it. We currently use three different payment gateways, so the code is meant to normalize calling payment requests and handling their responses.

php:
<?
class processSale {
    public $orderId, $amount, $ccCvv, $paymentProfileId, $paymentGatewayId;
    
    public function directSale($orderId, $amount, $ccCvv, $paymentProfileId, $paymentGatewayId) {
        $this->orderId = $orderId;
        $this->amount = $amount;
        $this->ccCvv = $ccCvv;
        $this->paymentProfileId = $paymentProfileId;
        $this->paymentGatewayId = $paymentGatewayId;    
                
        switch ($paymentGatewayId) :
            case 1
                return $this->payPalSale();
                break;
            case 2:
                return $this->gateway2NameRemovedSale();    
            case 3:    
                return $this->gateway3NameRemovedSale();
                break;
            default:
                // Handle orders without a valid paymentGatewayId
                break;    
        endswitch;
    }

    public function payPalSale() {
        //    Gets the password information for the gateway being used for this transaction.
        $arrPaymentGatewayInfo = getPaymentGatewayInfo($this->paymentGatewayId);    
        $arrOrderInfo = getOrderInfo($this->orderId, $this->paymentProfileId);

                // Sends request and handles the response

                return $arrTransactionData;
       }
}

$saleRequest = new processSale;
$arrTransactionData = $saleRequest->directSale(1,1.00,'999',12,1);
?>

Aniki fucked around with this message at 20:51 on Sep 4, 2014

musclecoder
Oct 23, 2006

I'm all about meeting girls. I'm all about meeting guys.
I don't care what you name your method, I meant don't make it a global variable (you did exactly this). Instead, pass it into your object or method:

php:
<?
public function __construct($apiContext)
{
   $this->apiContext = $apiContext;
}

public function processSale()
{
    // do stuff
    $whatever->stuff($this->apiContext);
    // do more stuff
}
?>
Making it part of $GLOBALS or calling "global $apiContext" is generally frowned upon because global variables are a mess.

Aniki
Mar 21, 2001

Wouldn't fit...

musclecoder posted:

I don't care what you name your method, I meant don't make it a global variable (you did exactly this). Instead, pass it into your object or method:

php:
<?
public function __construct($apiContext)
{
   $this->apiContext = $apiContext;
}

public function processSale()
{
    // do stuff
    $whatever->stuff($this->apiContext);
    // do more stuff
}
?>
Making it part of $GLOBALS or calling "global $apiContext" is generally frowned upon because global variables are a mess.

I get what you are saying. Thanks again for your help with this.

stoops
Jun 11, 2001
I'm using Simple HTML DOM to scrape some content.

The problem I'm having is I need to scrape the href from a particular linked image.

This is the html:
code:
<a href="picture.jpg"><img id="image" src="image"></a>
There are other links in the html, but the particular one I need is the one that links to the image with the id of #image.

Anyone know the best way to approach this?

I thought I could do this sorta, but I'm not sure how to get the href.

code:
foreach($html->find('#image') as $e){
                myImageURL = $e->outertext;
}
Any help is appreciated.

Adbot
ADBOT LOVES YOU

Sulla Faex
May 14, 2010

No man ever did me so much good, or enemy so much harm, but I repaid him with ENDLESS SHITPOSTING
I haven't used it before but I just took a quick look at the documentation and why not use $e->parent() and then get the ->href of that?

e: So:

code:
foreach($html->find('#image') as $e){
		$parent = $e->parent();
                $myImageURL = $parent->href;
}

Sulla Faex fucked around with this message at 19:18 on Sep 5, 2014

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply