Edit: the session_start() was in the "entire code of initial page," but wasn't showing. I needed another newline.
Edit 2: Showing the output of the raw HTML rather than the displayed page.
I am working on a document conversion site. It takes a one or two page .docx file and converts it to simple html. (Basically replacing newlines with p tags, no html or head tags as it will be displayed in an existing page). For test purposes I'm converting a .docx file with a single word - "one" - in it.
I am storing the converted data as a string in the variable $_SESSSION['doc']. Because of the issues I've been having, I'm also storing a $_SESSION['test'] string.
I do a var_dump($_SESSION) on the initial page and I can see both variables with populated strings.
I do a var_dump($_SESSION) on the following screen, and the $_SESSION['test'] string comes through okay, but the $_SESSION['doc'] is now a 0 length string. I'm not certain what's truncating my 'doc' string.
The relevant variables are $_SESSION['doc'], $_SESSION['test'], and $outputData. I included the entire first page at the end of this post since I suspect $outputData is getting overwritten.
I believe this is the relevant code snippet for the initial page:
<?php $outputData = preg_replace("/.+/", "<p class='converted'>$0</p>", $outputData);
$outputData = preg_replace("/<\/p>\n\n/", "<br /><br /></p>", $outputData); ?>
<?php if(isset($outputData)){$_SESSION['doc'] = $outputData;}else{$_SESSION['doc']="JustATest";} $_SESSION['test'] = "<>()!';!SDFSDFG^%$"; echo "\n<div><br /><br />var_dump: " . var_dump($_SESSION) . "</div>"; ?>
Output:
array(2) {
["doc"]=>
string(32) "<p class='converted'>one</p>
"
["test"]=>
string(18) "<>()!';!SDFSDFG^%$"
Relevant code on the follow up page:
<?php if(session_id() == ''){session_start();}
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $woocommerce;
$woocommerce->show_messages();
?>
<div>session_id: <?php echo session_id(); ?><br />OUTPUT: <?php echo var_dump($_SESSION); ?></div>
<?php do_action( 'woocommerce_before_cart' ); ?>
<form action="<?php echo esc_url( $woocommerce->cart->get_cart_url() ); ?>" method="post">
Output of follow up page:
session_id: jl40cdmbdpd3h40qg3ogmghkp0
OUTPUT: array(2) { ["doc"]=> string(0) "" ["test"]=> string(18) "<>()!';!SDFSDFG^%$" }
EDIT: I wasn't viewing the raw HTML. /me shakes head.
IGNORE: One thing I found strange on the initial page is the single word "one" is showing up as a 32 char string. . . so there seems to be some extraneous white space after the document conversion. . . but it still outputs from the $_SESSION['doc'] variable on the initial screen.
Entire code for the initial page:
<?php if(session_id() == '' ){session_start();}
if(isset($_POST['added']))
{
add_basic_edit( $_POST['id'], $_POST['wc'] );
unset($_POST['added']);
header('Location: http://localhost/cart/');
exit;
}
/* Template Name: Upload Page */ get_header();
/**
* Test code to programmatically add a pricing calculator product to the cart, on
* every page load
*/
function add_basic_edit( $product_id, $num_words ) {
global $wc_measurement_price_calculator;
$product = get_product( $product_id ); // id of my 'word' product
$measurements = $wc_measurement_price_calculator->get_product_measurements( $product );
// get the one measurement
foreach ( $measurements as $measurement ) ;
$measurement->set_value( $num_words ); // the number of words
// add to cart
$wc_measurement_price_calculator->add_to_cart( $product->id, $measurement );
/var/www/html/websites/localhost/wordpress/wp-content/themes/Avada/upload.php}
if(isset($_POST['posted']))
{
require_once 'HTTP/Request2.php';
class DocumentConverterClient {
var $url = '';
function convert($inputFile, $outputType) {
$this->url="http://localhost:8080/jodconverter-sample-webapp-3.0-SNAPSHOT/converted/$inputFile.$outputType";
$request = new HTTP_Request2($this->url);
$request->setMethod(HTTP_Request2::METHOD_POST)
->setHeader('Content-Type', 'multipart/form-data')
->addPostParameter('outputFormat', $outputType)
->setBody($inputData);
$request->addUpload('inputDocument', $inputFile);
return $request->send()->getBody();
}
}
$documentConverter = new DocumentConverterClient();
$inputFile = $_FILES['inputDocument']['tmp_name'];
$outputType='txt';
$noext=current(explode(".", $_FILES["inputDocument"]["name"]));
$inputType=end(explode(".", $_FILES["inputDocument"]["name"]));
$outputFile = "data/$noext.$outputType";
$outputData = $documentConverter->convert($inputFile, $outputType);
//file_put_contents($outputFile, $outputData);
} ?>
<div class="column_group"><br /><br />
<div style="float:left;width:30%;" class="left_clumn">
<div style="float:left;width:35%">Wordcount:</div><div><?php $wc = str_word_count($outputData); echo $wc;?>
</div>
<div style="float:left;width:35%">Price Per Word:</div><div>$<?php $product_id=get_page_by_title('Basic Editing', 'OBJECT', 'Product' ); $product = get_product( $product_id->ID ); $ppw = $product->get_price(); echo $ppw;?>
</div>
<div style="float:left;width:35%">Total Price:</div><div>$<?php echo number_format(($wc * $ppw),2);?>
</div>
<div><br /><br />
<form name="add_to_cart" id="add_to_cart" action="../upload-page/" method="post">
<input type="hidden" name="added" value="added" />
<input type="hidden" name="id" value="<?php echo $product_id->ID; ?>" />
<input type="hidden" name="wc" value="<?php echo $wc; ?>" />
<?php $outputData = preg_replace("/.+/", "<p class='converted'>$0</p>", $outputData);
$outputData = preg_replace("/<\/p>\n\n/", "<br /><br /></p>", $outputData); ?>
<?php if(isset($outputData)){$_SESSION['doc'] = $outputData;}else{$_SESSION['doc']="JustATest";} $_SESSION['test'] = "<>()!';!SDFSDFG^%$"; echo "\n<div><br /><br />var_dump: " . var_dump($_SESSION) . "</div>"; ?>
<span class="BlueButton" onclick="document.getElementById('add_to_cart').submit()">Add to Cart</span>
</form>
</div>
</div>
</div>
<div style="float:right;width:70%;" class="right_column">
<div><?php echo $outputData; ?></div>
</div>
</div>
<div id="content" style="<?php echo $content_css; ?>">
</div>
<div id="sidebar" style="<?php echo $sidebar_css; ?>"><?php generated_dynamic_sidebar(); ?></div>
<?php get_footer(); unset($_POST['posted']); ?>
You must add session_start() to the top of all pages before anything is rendered as output to the page.
Source
This is a poor answer as I still don't know why $_SESSION['doc'] was getting overwritten, particularly since $_SESSION['test'] was retained. I think it has to do with my various if(isset()) statements for processing form data. I believe one of them was at some point overwritting $outputData. . . but I'm not certain where.
I changed the first such statement to grab outputData from the _POST variable:
if(isset($_POST['added']))
{
add_basic_edit( $_POST['id'], $_POST['wc'] );
unset($_POST['added']);
$_SESSION['doc'] = $_POST['outputData'];
header('Location: http://techleadnet.com/cart/');
exit;
}
I added a hidden input to the form, and a couple more regexes to get rid of single and double quotes:
$outputData = preg_replace("/\"/", """, $outputData);
$outputData = preg_replace("/\'/","’", $outputData);
<input type="hidden" name="outputData" value="<?php echo $outputData; ?>" />
If anybody can point out where I'm messing up either the $_SESSION['doc'] variable, or where $outputData is getting overwritten this would be a better answer.
I did try making session_start(), without an if statement, the first thing in both of these pages, but it didn't make a difference.
Related
I´m building a MVC style parser, and I NEEDto be able to process my custom tags (used with the {} separator, like {echo $myVar}) together with standard PHP code <?php doSomething ?> in the same file...
So, after running my parser (that deals with the {} scope), I get the following result:
if (is_Array($data) && sizeof($data)) extract($data);
$text = array();$text[] = "
<div class=\"row\">
<strong>Name: </strong>";$text[] = $name;$text[] = "<br />
<strong>Description:</strong>";$text[] = $description;$text[] = "
<br />
<strong>Status: </strong>
<?php if ($status == false) : ?>
<span class=\"label label-danger\">FAILURE</span>
<?php else : ?>
<span class=\"label label-success\">OK</span>
<?php endif; ?>
<br />
</div>
";return implode($text);
All fine. From that piece of code I create a function using:
function = create_function("\$data", $code);
$code is the resultset from above.
$data is an array containg variables and values like:
`$name` => jonas
`$description` => This is test.
`$status`=> false
Finally I run:
$ret = $function($data);
echo $ret;
At that point, I get a problem. All references to variables are removed, but the tags are not processed, resulting in a kind of wierd code like:
<div class="row">
<strong>Name: </strong>jonas"<br />
<strong>Description:</strong>This is test.<br />
<strong>Status: </strong>
<?php if ( == false) : ?> <<<<<========== WRONG CODE
<span class=\"label label-danger\">FAILURE</span>
<?php else : ?>
<span class=\"label label-success\">OK</span>
<?php endif; ?>
<br />
</div>
So, the variables are substituted, except for the code that is neither solved nor have the variables correctly replaced.
I wish I can get a solution for that problem... Thanks for helping.
You're probably going about this in an inefficient manner...but to purely fix the problem you are having with your current code, just take the conditionals out of the quotations.
if (is_Array($data) && sizeof($data)) extract($data);
$text = array();$text[] = "
<div class=\"row\">
<strong>Name: </strong>";$text[] = $name;$text[] = "<br />
<strong>Description:</strong>";$text[] = $description;$text[] = "
<br />
<strong>Status: </strong>";
if ($status == false) :
$text[] = "<span class=\"label label-danger\">FAILURE</span>";
else :
$text[] = "<span class=\"label label-success\">OK</span>";
endif;
$text[] = "<br />
</div>
";return implode($text);
You must ecape the variable declaration, as it will be parsed by php. Then process your php code stored in a string with eval().
I have created a homepage editor tool in a script I purchased. The function of this homepage editor is to allow me to create different sections and display them one on top of the other in the order they are created. Which in hopes will give me an effect of several blocks that stretch width of the screen.
All seems to work well except one piece. I input my html and php code into the field in the admin panel and it saves to the db as I wrote it. However, when I go to echo each section back to the homepage it just displays my php code as plain text and doesn't interpret it as php and do its function.
Here is code from the homepage.php that prints the results.
<?php
session_start();
require_once("inc/config.inc.php");
if (isset($_GET['ref']) && is_numeric($_GET['ref']))
{
$ref_id = (int)$_GET['ref'];
setReferal($ref_id);
header("Location: index.php");
exit();
}
/////////////// Page config ///////////////
function get_all_section($section_id='')
{
$sql="SELECT * FROM `cashbackengine_homepage` WHERE 1";
if($section_id!="")
{
$sql.=" AND section_id='".$section_id."'";
}
$sql.=" AND section_status=1";
$sql.=" ORDER BY section_order ASC";
//echo $sql;
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$section_array[]=array(
'section_id' =>$row['section_id'],
'section_name' =>$row['section_name'],
'section_desc' =>$row['section_desc'],
'section_order' =>$row['section_order'],
'section_status' =>$row['section_status'],
'last_updated' =>$row['last_updated'],
);
}
return $section_array;
}
$get_all_section=get_all_section('');
/*$get_all_section2=get_all_section('2');
$get_all_section3=get_all_section('3');
$get_all_section4=get_all_section('4');
$get_all_section5=get_all_section('5');*/
for($i=0; $i<count($get_all_section);$i++)
{
//echo htmlspecialchars_decode($get_all_section[$i]['section_desc']);
//echo htmlspecialchars_decode(stripslashes(str_replace(" ","",(str_replace("<br />","\n",$get_all_section[$i]['section_desc'])))));
echo $get_all_section[$i]['section_desc'];
}
?>
I am certain the problem has to do with the echo at the end. But I am unsure how to use htmlspecialchars to make it work with php if it even will. Or if I have to put something weird in my saved section.
Here is one of my sections. Any help is greatly appreciated. Thank you.
<div style="height:260px; width:100%; background-color:#000; margin:0px; color:white;">
<div id="header">
<div id="logo"><img src="<?php echo SITE_URL; ?>images/logo.png" alt="<?php echo SITE_TITLE; ?>" title="<?php echo SITE_TITLE; ?>" border="0" /></div>
<div class="start_saving">
<div id="links">
<?php if (MULTILINGUAL == 1 && count($languages) > 0) { ?>
<div id="languages">
<?php foreach ($languages AS $language_code => $language) { ?>
<img src="<?php echo SITE_URL; ?>images/flags/<?php echo $language_code; ?>.png" alt="<?php echo $language; ?>" border="0" />
<?php } ?>
</div>
<?php } ?>
<div id="welcome">
<?php if (isLoggedIn()) { ?>
<?php echo CBE_WELCOME; ?>, <span class="member"><?php echo $_SESSION['FirstName']; ?></span><!-- | <?php echo CBE_ACCOUNT ?>--> | <?php echo CBE_BALANCE; ?>: <span class="mbalance"><?php echo GetUserBalance($_SESSION['userid']); ?></span> | <?php echo CBE_REFERRALS; ?>: <span class="referrals"><?php echo GetReferralsTotal($_SESSION['userid']); ?></span>
<?php }else{ ?>
<a class="signup" href="<?php echo SITE_URL; ?>signup.php"><?php echo CBE_SIGNUP; ?></a> <a class="login" href="<?php echo SITE_URL; ?>login.php"><?php echo CBE_LOGIN; ?></a>
<?php } ?>
</div>
</div></div>
</div>
It looks like you're getting these section contents pieces out of your database, and not from a file stored on your web server. Is that correct?
Assuming that's true, then my next question would be, who populates this data? Is this taken in any way from user input? The reason why I ask is because of my next suggestion, which may or may not be received well.
The reason why your PHP code isn't executing, is because it's being retrieved from the database and output as a string, not as code. So how do you execute code that's stored in a string, you ask? Well, the answer to that question is to use eval() on the string. But this is where you have to be really careful!!!!!!! If any part of that string could have possibly come from an untrusted source, then malicious PHP code could be executed, which could potentially give evildoers a way into your server, where they can find all the information in your database, server, etc. Make sure you know where your code is coming from before executing it!
You make a good point that it's HTML mixed with PHP. So I see two possible solutions...
This post suggests that you could do eval(' ?>'. $section .' <?php'); This makes sense, you're breaking out of PHP before you eval your string, and so requiring the included string to open its own PHP tags to write PHP code.
Another way I can think of would be to throw the contents into a temporary file, and then include() that file:
// get contents, store in $contents
$filename = tempnam(sys_get_temp_dir(), 'section');
file_put_contents($filename, $section);
include($filename);
unlink($filename);
I am trying to make a website and it's almost completed but I want to add a view counter so when someone visit the page it count the view and save it into the database.
My script is working fine but the problem is that it continue view count even visitor is viewing anyother page
My pages url show like this
pictures.php?ID=13
I have added this PHP code in *count.php*
<?php
session_start();
if (isset($_SESSION['views'])){
$_SESSION['views']++;
} else {
$_SESSION['views'] =0;
}
//echo $_SESSION['views'];
?>
Page *views.php*
<?php
session_start();
if (isset($_SESSION['$post_id'])){
$_SESSION['$post_id']++;
} else {
$_SESSION['$post_id'] =0;
}
//echo $_SESSION['views'];
?>
<?php
echo "<hr><div align=\"center\">";
echo $_SESSION['$post_id'];
?>
<?php
$save = $_SESSION['$post_id'];
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE save_data SET Views='$save' WHERE ID='$page_id'");
mysqli_close($con);
?>
And added this line in Pictures.php where I want to show and count visits
<?php include("views.php"); ?>
Problem:
When someone visits page pictures.php?ID=8 it will show him page view 1 and save this view in database where ID=8, when he visit page pictures.php?ID=12 it will show him view 2 and save this 2 in database where ID=12. My point is that it is continuously counting instead of each page view.
Thanks in advance
Here is Pictures.php
<?php
include("connection.php");
if(isset($_GET['ID'])){
$page_id = $_GET['ID'];
$select_query = "select * from save_data where ID='$page_id'";
$run_query = mysql_query($select_query);
while($row=mysql_fetch_array($run_query)){
$post_id = $row['ID'];
$post_title = $row['Title'];
$post_image = $row['Name'];
?>
<h3>
<a href="pictures.php?ID=<?php echo $post_id; ?>">
<?php echo $post_title; ?>
</a>
</h3><center>
<form id="search-form" action="javascript:void(0);">
<input type="text" id="dimen" name="dimension" />
<input type="submit" value="Resize" Onclick ="splitString()"/></form>
<div id="sizet">
Type size like 200*300 in box
</div></center>
<div id="img"><img id="myImage" src="uploads/<?php echo $post_image; ?>" /></div>
<?php } }?>
<center>
<div id="postdetails">
<?php include("posted_by.php"); ?></center>
</div>
<?php include("views.php"); ?>
<html>
<link href="css/Pictures.css" rel="stylesheet" type="text/css">
<body>
<head>
<script type="text/javascript">
function splitString()
{
var myDimen=document.getElementById("dimen").value;
var splitDimen = myDimen.split("*");
document.getElementById("myImage").width=splitDimen[0];
document.getElementById("myImage").height=splitDimen[1];
}
</script>
</head>
</body>
Variables inside of single quotes are not evaluated, so regardless of whether $post_id is 8 or 12, $_SESSION['$post_id'] is setting the key named literally $post_id, rather than the key named 12 or 8. Variables are evaluated inside double quotes, so $_SESSION["$post_id"] would work, but the simplest and best way is to use $_SESSION[$post_id] instead.
Additionally, using $_SESSION here is probably not what you want to do. $_SESSION will be different for every user who visits the site, so when a new visitor comes to the site, it will start over with a count of 1. What you probably want to do is load the views value from the database, add one to it, and then save it back to the database. $_SESSION is for keeping data that is specific to a certain user.
Try to use structure like this
$_SESSION['view'][{resource_name}_{resource_id}]
E.g. for picture with id 8 it will be
$_SESSION['views']['picutures_8']++
My PHP is very rusty, it's been years since I did PHP and am having a bit of a brain fart. I am trying to create PHP code so a different link is displayed based on the page you are on (making it so a person is brought to a different Contact Us page based on what page they are on).
The file fieldgroup-simple-group_product_header.tpl does a similar thing by displaying different social media links based on what page you are on. Ideally I want to use the same variable that determines what social media links to display as I do in this PHP file. How do I call a variable from a different file? I tried using an include statement but when I tried to print the variable to make sure it was working nothing is displayed.
I was thinking I could call the variable that identifies page type in the file fieldgroup-simple-group_product_header.tpl and use it to determine what type of link to display.
Thanks,
Doug
Here are the two files:
fieldgroup-simple-group_product_header.tpl
<?php
// $Id: fieldgroup-simple.tpl.php,v 1.1.2.1 2009/02/28 23:56:17 yched Exp $
/**
* #file fieldgroup-simple.tpl.php
* Default theme implementation to display the a 'simple-styled' fieldgroup.
*
* Available variables:
* - $group_name - The group name
* - $group_name_css - The css-compatible group name.
* - $label - The group label
* - $description - The group description
* - $content - The group content
*
* #see template_preprocess_fieldgroup_simple()
*/
?><? //print_r( get_defined_vars()); die();?>
<?php
if ($content) :
$content_div_id = $group_name;
$holderId = $group_name . "_holder";
$show_div_class = "show_link_holder";
$hider_link_class = "group_hide_link";
$show_link_class = "group_show_link";
$show_link_id = $group_name ."_show_link";
$show_link_text = $label;
$href = "#" . $content_div_id;
//die( $show_link_text );
?>
<div class="fieldgroup <?php print $group_name_css; ?>" id="<?=$holderId ?>" title=" <?=$label ?>">
<div class="group_content" id="<?=$content_div_id ?>">
<?php print $content; ?>
<div class="clear"></div>
</div><!--close #<?=$content_div_id ?>-->
</div><!--close #<?=$holderId ?>-->
<?php endif; ?>
And the contact-us.php file code:
<?
//this is the location of the product header file that defines the variable that determines the content type
include '/sites/all/themes/tekzennew/fieldgroup-simple-group_product_header.tpl';
function build_info_form($node)
{
$node_url = $node->path;
$is_canine = strcasecmp($node_url, CANINE_STUDY_URL) == 0;
$img_src = $is_canine ? "/sites/default/files/case-study-orange.gif" : "/sites/default/files/info-orange.gif";
?>
<div class="request-info-holder system-sidebar-container">
<div id="request-info-header" class="system-sidebar-header">
<span class="request-form-title">Contact Us</span>
</div>
<div id="request-info-content" class="system-sidebar-content">
<span class="phone">800.248.3669 | 617.464.4500</span>
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} elseif ($d == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
<?php print $group_name; ?><br>
<img src="<?=$img_src ?>" />
<form action="" method="post" >
<input type="image" name="submit" value="Request Info" class="info-button" src="<?=$img_src ?>" />
<!-- product field -->
<input type="hidden" name="product" value="<?=$product_name ?>"/>
</form>
</div>
</div>
<?
In the he contact-us.php file line 41 you are trying to print $group_name. However you are not setting its value in either of these 2 files. Same issue for $content. It looks like you may be missing a file or a few here.
Hey iam making a slot machine and is almost done. The only thing i need is the credit's to stay so it just add points on the credit's. Like if i have 100 credits and then get 25 credits i want it to say 125 credits. Now i don't know how to get the credits from the round before.
This is what i got:
<?
$tal = rand (1,3 ); {
echo "<img src='css/billeder/enarmet$tal.gif' class=billed />";
$tal2 = rand (1,3 );
echo "<img src='css/billeder/enarmet$tal2.gif' class=billed />";
$tal3 = rand (1,3 );
echo "<img src='css/billeder/enarmet$tal3.gif' class=billed />"; }
?>
</div>
<div id="credits">
<h3 id="credits2">CREDITS</h3>
<h3 id="credits3"><?php
$credits=$_GET['credits'];
if ($tal . $tal2 . $tal3 == 111){
($credits=($credits+100));
}
if ($tal . $tal2 . $tal3 == 222){
($credits=($credits+50));
}
if ($tal . $tal2 . $tal3 == 333){
($credits=($credits+25));
}
echo $credits;
?></h3>
</div>
</div>
<form action="index.php" method="POST">
<input type="submit" value="SPIN" class="knap">
</form>
<form action="cashout.php" method="POST">
<input type="submit" value="CASH OUT" class="knap">
</form>
</div>
What about using sessions? Store and retrieve credits from session storage using
session_start();
$credits = $_SESSION['credits'];
at the top of your script and
$_SESSION['credits'] = $credits;
at the bottom.
This way credits will be preserved between page-loads.
You can remove the curly braces at the end of the following lines, its not need and try it.
<?
$tal = rand (1,3 ); { // remove the open brace
echo "<img src='css/billeder/enarmet$tal.gif' class=billed />";
...
echo "<img src='css/billeder/enarmet$tal3.gif' class=billed />"; } // remove the close brace
?>