PHP Using a Session cookie ID set by 3rd party server/URL - php

I am building a WordPress shopping cart plugin that will tie into our server through a URL that will produce an XML page, which I will then have to parse the info to the WordPress page.
The server contains a session id (ShoppingCart.SessionID) that I need to get and use to help store which button was clicked and then pull the product info and add it to the cart. Each button is given a product id via shortcode (product_id="some#") from the page owner and that ID is pulled from the server to display the product's info.
How the buttons are set up:
In the shortcode file, I am using a function and have the button set up as
<?php
add_shortcode('add_cart_button', 'add_cart_button_handler');
function add_cart_button_handler($atts) {
extract(shortcode_atts(array(
'product_id' => '',
), $atts));
return print_add_cart_button_for_product($product_id, $atts);
}
In the main plugin file:
This file handles the printing of the button and the function to display the cart
<?php
session_id();
session_start();
// This function prints the button with its assigned $product_id
function print_add_cart_button_for_product($product_id, $atts = array()) {
$replacement .= '<form method="POST" class="cart-button-form" style="display:inline" action="">';
$replacement .= '<input type="hidden" name="bmt_cart_product" value="' . $product_id . '" />';
$replacement .= '</form>';
$replacement .= '</div>';
return $replacement;
}
Here is the function for what is supposed to be displaying the cart/product info:
function show_shopping_cart_handler($atts) {
$output = "";
$form = '';
$output .= '<table style="width: 100%;">';
$output .= '<tr class="cart_item_row">
<th class="cart_item_name_th">' . (__("Item Name", "wordpress-simple-paypal-shopping-cart")) . '</th><th class="cart_price_th">' . (__("Price", "wordpress-simple-paypal-shopping-cart")) . '</th><th></th>
</tr>';
# For now, I am using this to print the headers that display the
# ShoppingCart.SessionID="somevalue", but on every button click it changes the value of the session id.
if (isset($_POST['add_cart_submit'])) {
// The server reads the ID from "&PRODUCTID=product#"
$id = "&PRODUCTID=" . $_POST['cart_product'];
$url = "https://secure.bmtmicro.com/cart?CID=2/WP" . $id;
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'GET',
'content' => http_build_query($data)
)
);
//$context = stream_context_create($options);
$context = stream_context_set_default($options);
$output .= file_get_contents($url, false, $context);
}
print_r(get_headers($url));
$output .= '</table>';
return $output;
}
What the XML page looks like with an example product
Not sure if this is needed, but the more info provided, the better (right?). The product ID that is sent will populate these fields and keep adding a new row and then I will parse the necessary fields to the WordPress page.
<shoppingcart sessionid="88582813">
<producttable>
<row number="0">
<productid>22804</productid>
<productname>XFree86 CD</productname>
<quantity>1</quantity>
<productprice>$15.00</productprice>
<discount>$0.00</discount>
<rowtotal>$15.00</rowtotal>
</row>
</producttable>
</shoppingcart>
I am pretty new to PHP and learning as I go (reading/research), but have not been able to find the solution or steps to tackle my issue. Essentially, I believe my question should be (in short):
How can I grab the ShoppingCart.SessionID from the 3rd party server and use it to populate the cart without refreshing the Session so more than one product will display when more than one button is clicked? Also, is there a better/more productive way to accomplish what I am trying to do?
Thanks in advance and let me know if there's any info I need to add to the question!

In case anyone comes across this with a similar issue:
My way around this was to send the button data to an <iframe> and then set the <iframe> to width="0" height="0".
Example code:
<form method="POST" action="URL" target="the_iframe">
// add some <input> fields data
</form>
<iframe type="hidden" name="the_iframe" width="0" height="0"></iframe>
Not sure if this is THE BEST way to do it, but it works and I was able to add some JQuery to manipulate things even further (I tried using AJAX before this, but the server was set to "same origin", so the data wouldn't send from another URL).

Related

Sum the values for a particular column on a WordPress site based on user form input

I am using WordPress a lot recently and I encountered a following problem. I downloaded a theme from the web(https://organicthemes.com/theme/retro-theme/) and based on the theme I created a Wordpress website like so:
On that website I created a few sub-pages that allow the user to:
Enter user input, using a Contact Form 7 form Wordpress plugin, like this:
Display the input using CF7 Form Views Wordpress plugin like so:
My goal would be display the input in a table so that the values for the last column are summed and the overall score is displayed at the very bottom of the page in a new row.
This means that if we have three rows as the the output, and for those three rows we are taking into account the last column. For that column we want to sum the cells so that we get a new row with the overall score for that particular column.
I asked my colleague at work how to do this and he gave me a hint to customize the Wordpress plugin CF7 Views. So I downloaded the plugin from the web(https://wordpress.org/plugins/cf7-views/) and experimented with the PHP code for that plugin. After downloading my plugin I opened the folder for the plugin(cf7-views) and went into the inc folder to modify the shortcode(class-cf7-views-shortcode.php).
I know the solution has something to do with get_table_content function
function get_table_content( $section_type, $view_settings, $submissions ) {
$content = '';
$section_rows = $view_settings->sections->{$section_type}->rows;
$content = ' <div class="cf7-views-cont cf7-views-'.$this->view_id.'-cont"> <table class="cf7-views-table cf7-view-' . $this->view_id . '-table pure-table pure-table-bordered">';
$content .= '<thead>';
foreach ( $submissions as $sub ) {
$content .= '<tr>';
foreach ( $section_rows as $row_id ) {
$content .= $this->get_table_row_html( $row_id, $view_settings, $sub );
$this->seq_no++;
}
$content .= '</tr>';
}
$content .= '</tbody></table></div>';
return $content;
}
but I do not know how to alter the code to accomplish my goal. Any help is welcome!

Updating URL for parsing XML in PHP

I am trying to figure out how to update an URL that I am using to parse the XML (using simplexml_load_file()).
There is a button that has a $productid that is assigned to it by the user when they add their shortcode [show_cart_button productid=#].
//code for the button input that gets called
function print_add_cart_button($productid, $atts = array()) {
//some other form code for the button
$replacement .= '<input type="hidden" name"cart_product" value"' . $productid . '"/>';
return $replacement;
}
This is the function I am using to display and call the product information:
function show_shopping_cart_handler($atts) {
if (isset($_POST['cart_product'])) {
$id = "&PRODUCTID=" . $_POST['cart_product'];
// uses the input name from the button
}
$url = "https://secure.bmtmicro.com/cart?CID=2/WP" . $id;
$xml = simplexml_load_file($url) or die("error.");
foreach ($xml->producttable->row as $product) {
$output .= '<span>' . $product->productname . '</span>';
}
return $output;
}
The way the URL will work properly is to have a &PRODUCTID=(product#) added to the end of the URL. For example, if you click two different buttons, the URL should look like this: https://secure.bmtmicro.com/cart?CID=2/WP&PRODUCTID=1&PRODUCTID=2 (obviously 1 and 2 will need to display the buttons $productid number).
As you should be able to see from my code above, every time a button gets clicked, it just rewrites the URL and displays that one product, instead of adding a new one to the list. I tried to set the simplexml_load_file() into a foreach(), but that would not display any products when the button was clicked. Does anyone know a way I could get that URL to update/work properly?
Everytime
if (isset($_POST['cart_product'])) {
$id = "&PRODUCTID=" . $_POST['cart_product'];
// uses the input name from the button
}
Is called, it's overwriting $id. You need to get any existing values for the url.
You'll have to get all of the current values ($_GET['cart_productions']), throw them into an array, grab the new post, add it to the array and add all of them to them the url using http_build_query().

Selectize.js doesn't read HTML entities correctly

I'm working with Selectize.js currently and am stuck on a problem relating to HTML entities not displaying correctly in Selectize fields, and therefore failing checks after submission. We use PHP on the backend and run every Selectize option through htmlspecialchars($option);. We then export the PHP array to a JSON array in preparation for adding it to the Selectize script/field.
//Array of options
$options = getOptions();
$optionsArray = array();
foreach($options as $item) {
$optionsArray[] = array('text' => htmlspecialchars($item), 'value' => htmlspecialchars($item));
}
//Create html script to run selectize initialization
$htmlcode = "<script>";
...
$htmlcode .= "var optionList = " . json_encode($"optionsArray") . ";";
$htmlcode .= "$('#selector').selectize({ options: optionList });";
...
$htmlcode .= "</script>";
The point here is to protect against malicious entries by encoding. This typically wouldn't be a problem, as browsers will detect the entities and convert them automatically (ie. will detect & and display as &. However, that is NOT happening inside the selectize. As you can see in the image below, outputting an option with an ampersand displays correctly on the page, but it doesn't display accurately in the Selectize field.
Example:
The problem then becomes larger, as we are comparing the selected item against the database after submission, to ensure that the selected entry actually exists. If the entry testOption&stuff actually exists, the form submission will check testOption&stuff against it, and will obviously fail the check.
//For simplicity, checking against static option
var $selectedOption = $_POST["options"];
if ($selectedOption == "testOption&stuff") {
//Do success
} else {
//Do failure
}
How can I resolve this and make it so that the Selectize field will store and display the correct entry (ie. &)?
Thanks!

Removing article with ID from URL

Im building this blogg site and finally got everything considering uploading multiple pictures to one news article done.
Now my second step is to remove an article with following pictures to it.
Everything is set in the database so all i need is an ID from the news article.
When i press remove button on a article it shows the ID up in the URL... Im wondering how to get the specifik ID int from the URL and IF there is an smarter approach. It must be OOP and objectoriented apporach.
Code looks like this:
This is the looping out each article and notice $current_id that i put into a button to show in the url when its pressed
public function doOutputArticles($newsList, $pictureList)
{
$result = '';
foreach($newsList as $news)
{
$result .= '<ul>';
$current_id = $news->dbNewsID;
$result .= '<li class="bloggNewsHeader">'.$news->dbHeader.'</li>';
$result .= '<li class="bloggNews">'.$news->dbNews.'</li>';
$result .= '<li class="bloggNewsDate">'.$news->dbNewsDate.'</li>';
foreach($pictureList as $pic)
{
if($pic->dbNewsID == $current_id)
{
$result .= '<li class="bloggNewsPicID">'.$pic->dbPictureID.'</li>';
$result .= '<img class="bloggNewsPic" src="./images/'.$pic->dbPicture.'"alt="some_text">';
}
}
$result .= "
<form id='' method='get'>
<input type='hidden' name='$current_id'/>
<input type='submit' name='removeArticle' value='Ta bort inlägg' />
</form>";
$result .= '</ul>';
}
return "<div id='filesLoaded'>". $result ."</div>";
}
`
After this is done, i press a button to remove specific article and then the ID shows in the URL, now this method is meant to GET the specific INT/NUMBER ID in the URL but HOW?
public function GetSelectedID()
{
$ID = $_GET[self::$articleId];
echo $ID;
if(is_null($ID) || empty($ID))
{
return null;
}
else
{
echo $ID;
return $ID;
}
}
`
Kind regards /Haris
You don't really need a form, a simple link would do and be clearer. You should be using a different endpoint for deletion rather than looking for "removeArticle". This would be more OO since it would pave the path towards creating a specific Action Controller for each function rather than having one sprawling endpoint full of conditionals. Then you can have a consistent parameter (ideally within the URL path) of something like "articleId" that you are extracting from the URL. You'd also ideally want to redirect to the listing page upon completion to keep functionality focused in each method and also as a practice to avoid double posting issues (though this example is idempotent so it wouldn't be overly important).

Adding JS To Codeigniter Links - Simple OnClick

I am trying to write a simple Javascript snippet into a Codeigniter link. I am using the link to delete posts where required in my dashboard. I dont know anything about JS although am trying to learn it.
Code
$js = 'onClick = "alert("Are you sure")"';
$this->table->set_heading('Date', 'Title', 'Delete', 'Update');
foreach($records as $row){
$row->title = ucwords($row->title);
$this->table->add_row($row->date,
$row->title = ucwords($row->title),
anchor("main/delete/$row->id", $row->id, $js), //this is the link in question
anchor("main/fill_form/$row->id", $row->id)
);
}
$table = $this->table->generate();
echo $table;
My question is how to write the JS for the link ($js). I would like to use a confirm statement, (yes or no). I am totally lost with JS to prevent accidental deletions
Thank you
Here's how you might do it with the CodeIgniter anchor function :
echo anchor('delete/something', 'Delete', array('onClick' => "return confirm('Are you sure you want to delete?')"));
This displays a confirmation box when the link is clicked. If the user confirms then the link is followed. If the user cancels then no action is taken.

Categories