How do you put a session like this into an array - php

I have the follow two files and I would like to transmit information between the two files using a session, but I am not getting the right results. Here are the files
index.php:
<?php
session_start();
for ($i=0; $i<=2; $i++) {
echo ("<p><a href='getpage.php?row=$item_title' target='_blank'>" . $item_title . "</a>");
echo ("<br>");
echo ($item_desc . "</p>");
$_SESSION['item_link'] = $item_link;
$_SESSION['item_title'] = $item_title;
}
and the getpage.php has the following
<?php
session_start();
if (isset($_SESSION['item_link']) && isset($_SESSION['item_title'])) {
$item_link = $_SESSION['item_link'];
$item_title = $_SESSION['item_title'];
header( "Location: $item_link" );
}
But I keep getting the last item_link when I click the link and run the getpage.php file by clicking the link from the index file. How do I put the session into an array so that I am not only getting the last value in session after you click the link?

This is a quick drive-by attempt at an answer, but you might try
$_SESSION['item_link'][] = $item_link;
$_SESSION['item_title'][] = $item_title;
Then your session variables will themselves be arrays.

I suspect your code is based on a misunderstanding on the underlying mechanics. Files are nothing but static assets, nothing but a bunch of zeroes and ones that do nothing but use disk space until you do something with them.
Just printing the name of a file:
echo ("<p><a href='getpage.php?row=$item_title' target='_blank'>" . $item_title . "</a>");
... will neither execute the file nor load it in memory or assign any resource of variable to it. It's just text. Variables defined in the for-each-file loop will not transmit to the files. The source code in the file will eventually run when the user clicks on the link.
Secondly, that's not how PHP sessions work anyway. Session data is not attached to a specific file, it's session-wide information.
You appear to be partially aware of URL parameters. That's the proper way to transmit information as long as it isn't sensitive or too long. If you pass $item_title in the URL:
echo ("<p><a href='getpage.php?row=$item_title' target='_blank'>"
... it'll be available right at $_GET['row']. There's no need to fiddle with sessions:
$_SESSION['item_link'] = $item_link; // What for?
Last but not least, when you inject text into a string that's aimed to be consumed by a computer (such as a URL or an HTML document) you need to ensure you don't break the data format. PHP provides the following built-in tools:
For URLs: rawurlencode()
For HTML: htmlspecialchars()
So your echo should look like this:
echo ("<p><a href='getpage.php?row=" . htmlspecialchars(rawurlencode($item_title)) . "' target='_blank'>"

Related

What is wrong with my 'Save File' php code?

The question is simple but i will give some background information to hopefully make answering it easier.
So, I am working with the ELGG framework and taking information from a form and the text boxes in it in hopes to print that data to a simple text file.
Unfortunately, for some reason this has been giving me lots of trouble and I cannot seem to figure out why no matter where I look.
Code is as followed
<?php
error_reporting(E_ALL);
//Get the page
$title = get_input('title');
$body = get_input('body');
$date = date("l jS F Y h:i A");
//remove any possible bad text characters
$FileName = $title . ' ' . $date;
//print to file
//get filename and location to save
$folderName = '/Reports/' . $FileName . '.txt';
$ReportContent = "| " . $body . " |";
//write to the file
file_put_contents($folderName, $ReportContent, 0);
//error check to see if the file now exists
if (file_put_contents($folderName, $ReportContent)) {
system_message("Report Created (" . basename($folderName) . ")");
forward(REFERER);
} else {
register_error("Report (" . basename($folderName) . ") was not saved!");
forward(REFERER);
}
So what above SHOULD do is grab the text from the title and body box (which i can confirm it does from the title at least) and then save it under the /reports/ folder (full path for the plugin is Automated_script_view/reports/ if needed). Yet I will always get the register error, and I cannot seem to find why.
I believe it has to do with the declaration of the folder (/reports/), as if I take that part away, it passes and submits, although it doesn't seem to actually save anywhere.
Any and all advice would be very much appreciated!
The Function file_put_contents(file,data,mode,context) returns the number of character written into the file on success, or FALSE on failure. Note the following corrections and your script will work just fine:
1 Your File name has an 'illegal' character ":" coming from the $date part of the string you concatenate to form the filename.
2 Remove file_put_contents($folderName, $ReportContent, 0); Since the function returns an integer, simple use:
if( file_put_contents($folderName, $ReportContent) > 0 ){
//true
}else{
//false
}

Get array details PHP

I have a google map on this page, all markers were generated by submit postcodes. So I have the array below, loop info of each marker,
imploded as ("array", "array") format, I am trying to click on a infoWindow and display the according marker details on details.php.
The problem is everything is on the button onclick event, only a simple get on the second page.
This is working, but it is a very bad way. Because the limit to URL length and security reasons;
I would like to be able to get an array info from details.php page,
and the button onclick event trigger url looks like: details.php?marker=id
I don't know what is the best way to go about this, can someone pointing me to the right direction please?
index.php
$info = array();
foreach($stmt as $x)
{
$info[] =
"<h4>" . $x['name'] . "</h4><hr />".
"<h5>Address: </h5>" . $x['Address']."<br />" .
"<h5>Postcode: " . $x['postcode'] ."</h5><br />" .
"<button onclick='window.location.href= \\\"details.php?marker=". "<h4>" . $x['name'] . "</h4><hr />".
"<h5>Address: </h5>" . $x['address']."<br />" . "<h5>Postcode: " . $x['postcode'] ."</h5><br />" . "\\\" ' >
View Details</button>";
}
$i=' "'.implode('","', $info).'"';
details.php
echo $infomarker = $_GET['marker'];
You have to use $x['id'] insted of $x['name'] which is unique in your database and also use base64_encode() for encryption of your id "details.php?marker=".base64_encode($x['id'])."
In your details.php
$infomarker = base64_decode($_GET['marker']);
Try using AJAX to get the info from details.php and then load it into your InfoWindow.
I didn't realise how simple this was, all I need is use that id, write it inside a sql statement in details page then call any part of the statement out. Thanks everyone. Thanks to #Manjeet Barnala for encode tips.

Passing variables between two .php pages

On the catching page i have
$storeID= $_REQUEST['store'];
$custID= $_REQUEST['cust'];
I have links on different pages to the above page like the following
on page 1.
echo "<a class='btn btn-info' rel='nofollow' target='_blank' href='/go-to-store.php?store=" . $KID . "&cust=" . $user_ID . "'>" . "shop" . "</a>";
on page 2.
echo "<form action='/go-to-store.php' target='_blank' method='post'>"
. "<input type='hidden' name='store' value='$postid'>"
. "<input type='hidden' name='cust' value='$user_ID'>"
. "<button class='btn btn-mini btn-info' type='submit' style='margin-top:5px;'>"
. "shop" . "</button>";
Are both of these ways valid acceptable way of doing things. I have no reason not to show the values to user and there is no harm or motive for anyone to alter these values.
I'm tracing a problem on my site and basically narrowing down any possible scenarios where there could be even a remote chance of something causing the problems i have.
The $storeID looks like it contains data that is relevant only to a specific set of pages on the site, but which people might want to link to. It should form part of the URL so that people can link to it.
The $custID looks like it contains data specific to the user, but which should persist across the entire site (and isn't going to change unless the user logs out). It should be stored in a cookie (or stored on the server in a session which is associated with a browser with a cookie) and not passed in each request.
use cookies or session to store data and use them any page you want.
<?php
session_start();
$_SESSION['storeID'] = $_REQUEST['store'];
$_SESSION['custID'] = $_REQUEST['cust'];
// now access session variables from other pages
echo "Store ID : ". $_SESSION['storeID']."<br />";
echo "Cust ID". $_SESSION['custID']
// to delete variable
unset($_SESSION['storeID']);
unset($_SESSION['custID'])
?>
with cookies
<?php
// store varible in cookie for one day
setcookie("soreID", $_REQUEST['store'], 60*60*24);
setcookie("custID", $_REQUEST['cust'], 60*60*24);
// retrive data
echo "Store ID : ". $_COOKIE['storeID']."<br />";
echo "Cust ID". $_COOKIE['custID']
// delete cookie
setcookie("soreID", $_COOKIE['store'], time()-3600);
setcookie("custID", $_COOKIE['cust'], time()-3600);
?>
Option 1: Encode variables by base64 so your users can't see them without decoding. Put variables into url.
$storeID= urlencode(base64_encode($_REQUEST['store']));
$custID= urlencode(base64_encode($_REQUEST['cust']));
// then use following to get data from url:
$storeID= base64_decode(urldecode($_GET['sid']));
$custID= base64_decode(urldecode($_GET['cid']));
Option 2: Use sessions. Sessions allow you to save data to server, so they won't show to users.
session_start();
$_SESSION['storeID'] = $_REQUEST['store'];
$_SESSION['custID'] = $_REQUEST['cust'];
// then use following to get data from sessions:
session_start();
$storeID= $_SESSION['storeID'];
$custID= $_SESSION['custID'];
Option 3: Use text files. Keep in mind; i do not recommend this option because it loads server a bit and it doesn't beat other options. (you can use dbs also)
file_put_contents()
file_get_contents()
Edit:
session_start();
if(isset($_POST['store']) && isset($_POST['cust'])){
$_SESSION['storeID'] = $_POST['store'];
$_SESSION['custID'] = $_POST['cust'];
}
else {
echo 'please fill are fields.'
}

Javascript wont run in PHP

I have this piece of code:
if(isset($_POST['btnSubmit']) && $_POST['btnSubmit'])
{
require_once($_SERVER['DOCUMENT_ROOT'] . 'database.php');
$derpCard = $card;
$derpAccessGroup = $_POST['tbAccessGroup'];
$derpComments = $_POST['tbComments'];
if(isset($_POST['cbActivated']))
$derpActive = $_POST['cbActivated'];
else
$derpActive = "DEACTIVATED";
$x = editCard($derpCard,$derpAccessGroup, $derpComments, $derpActive);
if($x)
{
$_SESSION['editcard'] = $derpCard;
$_SESSION['editgroup'] = $derpAccessGroup;
$_SESSION['editcomments'] = $derpComments;
$_SESSION['editstatus'] = $derpActive;
echo "<script>";
echo "alert(\"Done!\");";
echo "</script>";
}
echo "<script>location.reload(true);</script>";
}
Basically, editCard runs an SQL "UPDATE ... where..." to edit the content within the db. If this is sucessful, I want it to display an alert telling the user it's been updated, as well as refresh the page.
Both the alert and reload code do not run, and i've been trying any and all alternatives! If someone has any idea as to simply refresh the page (thats the minimum i need!) It would be greatly appreciated!
I have to apologize if this answer is too short but the question is too broad or is missing more info. I noticed that one of your lines is wrong.
require_once($_SERVER['DOCUMENT_ROOT'] . 'database.php');
should be:
require_once($_SERVER['DOCUMENT_ROOT'] . '/database.php');
There should be / in it since $_SERVER['DOCUMENT_ROOT'] returns something like this:
"C:/xampp/htdocs"
So if you are to concatenate that with "database.php", you'll be having
"C:/xampp/htdocsdatabase.php" instead of "C:/xampp/htdocs/database.php"
In any case, you should try using firebug or similar browser add-on to help you debug those javascript errors(if there are any).
I hope this helps.
Try to format the script echo like this:
echo "\n<script>\n<!--\n";
echo "alert(\"Done!\");";
echo "\n-->\n</script>\n";
and
echo "\n<script>\n<!--\nlocation.reload(true);\n-->\n</script>\n";
Note the new lines added.
You appear to be missing the type attribute for script.
If you want to specify javascript, you need to include the type.
echo "<script type=\"text/javascript\">";
echo "alert(\"Done!\")";
echo "</script>";
Same goes with the other line
echo "<script type=\"text/javascript\">location.reload(true);</script>";
If the above does not help in the slightest, the problem could be with your logic statements, or that your javascript may just not be outputting what you want.
There are tools to help you figure out these issues, such as the apache logs and firebug plugin
EDIT: Forgot missing semicolon

PHP echo button onclick function

For a little "webshop project" I create a table with PHP and echo"..." function. The table displays some values and in the last cells, there shall be a button which enables the user to delete the corresponding row (or better said, purchase). The data is held in a database and read out while the page loads and than displayed in the table.
I use a "purchase id" to find out which rows have to be deleted, and it works fine if I just implement the function itself. The problem is that I can't get the function working as "onclick" event for the button.
So, some code:
function delete_purchase($purchase_id){
mysql_query("DELETE FROM purchase WHERE purch_id = '$purchase_id'");};
That's the PHP function which deletes the rows, easy enough.
$result = mysql_query("SELECT purchase.purch_id, item.name, purchase.amount, purchase.purch_date, delivery.meaning, item.weight FROM purchase, item, delivery WHERE purchase.cust_id='$cust_id' AND delivery.del_id = purchase.delivered AND purchase.item_id = item.item_id");
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['amount'] . "</td>";
echo "<td>" . $row['weight'] * $row['amount'] . "</td>";
echo "<td>" . $row['purch_date'] . "</td>";
echo "<td>" . $row['meaning'] . "</td>";
echo "<td><button onclick=\"delete_purchase('" . $row['purch_id'] . "')\">Kill</button></td>";
echo "</tr>";
}
And this is the part which doesn't seem to work. I get the variable and some other values from the database and insert them into my table as long as there are values. Everything is displayed, even the buttons; but clicking on them doesn't do anything.
Source code of the website seems fine:
<td><button onclick="delete_purchase('138')">Kill</button></td>
Hope everything's clear, and you guys have some ideas what's wrong. If you need to know additional stuff, just ask and I'll see what I can do.
onclick="delete_purchase('138')"
calls a Javascript function called delete_purchase, which doesn't seem to exist in your code. You only have a PHP function with that name.
Since all PHP is executed on the server side, the HTML will be built long before the client ever sees the code and therefore you will never be able to call the delete_purchase PHP function from the client side.
The only two ways to get around this are:
- Create a delete_purchase JS function that then calls a PHP file through the use of AJAX.
- Don't call the onclick JS function at all and make the button a regular form submit that you then catch on the server side to delete the purchase. This however would involve a complete page refresh.
Your delete_purchase() function is defined in server-side which is not available in client side. You need to send a request to server and send the id, for example:
?action=delete&id=1
Then you can validate it on server side and call the function
<?php
if(isset($_GET['action']) && $_GET['action'] == 'delete'){
//do some staff
}
?>
you try to call a PHP-function directly from HTML (from browser)
this is impossible!
you may call it using 2 ways:
1) AJAX-call of php-script which will delete the purchase
2) redirect browser to php-script which will delete the purchase and then redirects you back

Categories