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.'
}
Related
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'>"
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I have an HTML table, linked to PHP $_SESSION data, to which I wish to add a Delete button to every row that deletes not only that row from the HTML table, but also from the $_SESSION variable.
This is the code that populates my table:
tableData.php
// echo the table headings
echo <<<HERE
<tr>
<th>CityID</th>
<th>State</th>
<th>City</th>
<th></th>
</tr>
HERE;
if (isset($_SESSION['cityData']))
{
foreach($_SESSION['cityData'] as $city)
{
echo "<tr>";
// print each row of data
foreach($city as $data)
{
echo "<td>" . $data . "</td>";
}
//echo '<td><button action="<?php unset(' . $_SESSION['cityData'][key($_SESSION['cityData'])] . ')?>">Delete Row</button></td>';
echo "</tr>";
}
}
The line that I commented out,
echo '<td><button action="<?php unset(' . $_SESSION['cityData'][key($_SESSION['cityData'])] . ')?>">Delete Row</button></td>';
is the line that creates the button that I am trying to create, to do what I am wanting it to do. I am trying to figure out the best way to name the array that I want gone.
P.S. I know, I should have it invoke some other function that does both tasks, it is just, if I pass the array in like I did, it will complain of " Array to string conversion ". Is there a way to do what I am trying to do, cleanly?
It's just not that simple. You need to get your buttons to submit to a link, and then have the PHP unset the content.
foreach($_SESSION['cityData'] as $index => $city) //added $index =>
{
echo "<tr>";
// print each row of data
foreach($city as $data)
{
echo "<td>" . $data . "</td>";
}
echo '<td><form method="post" action=""><input type="hidden" name="delete" value="' . $index . '"><input type="submit" value="Delete Row"></form></td>';
echo "</tr>";
}
So I added a form that a button that will submit to data that indicates the row number, so when your client clicks on the button, it will submit them and the row number will be passed as a POST variable.
At the top of tableData.php, you can then have logic handling the delete. Simply check if the delete is set, and then attempt to unset from there.
if (isset($_POST['delete']))
unset($_SESSION['cityData'][$_POST['delete']]);
You will want to have further validation that checks if POST delete within the bounds of $_SESSION['cityData'], but the basic idea is there.
You're mixing client-side and server-side code the wrong way here :(
The "client" is something like a user's browser. When a user clicks that button on their browser, it will run client-side code (i.e. JavaScript) - your PHP won't exist anymore at that stage so you don't have access to that array.
PHP is executed when a page has been requested from your server. That's when you can perform whatever computation you need and then deliver a textual response (via echo for example) back to the user's browser or whatever the client may be.
That button should make another request to your server so you can use PHP to delete the row. Then your PHP server should echo a response back to the requesting browser so users can know if it worked or not.
The link on the button will need to be provided some additional details, like the index of the row that the user wants to delete, so the PHP script doesn't delete the wrong one. See Dave Chen's answer below for some example code.
I want to pass a couple of variables from one PHP page to another. I am not using a form. The variables are some messages that the target page will display if something goes wrong. How can I pass these variables to the other PHP page while keeping them invisible?
e.g. let's say that I have these two variables:
//Original page
$message1 = "A message";
$message2 = "Another message";
and I want to pass them from page1.php to page2.php. I don't want to pass them through the URL.
//I don't want
'page2.php?message='.$message1.'&message2='.$message2
Is there a way (maybe through $_POST?) to send the variables? If anyone is wondering why I want them to be invisible, I just don't want a big URL address with parameters like "&message=Problem while uploading your file. This is not a valid .zip file" and I don't have much time to change the redirections of my page to avoid this problem.
Sessions would be good choice for you. Take a look at these two examples from PHP Manual:
Code of page1.php
<?php
// page1.php
session_start();
echo 'Welcome to page #1';
$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();
// Works if session cookie was accepted
echo '<br />page 2';
// Or pass along the session id, if needed
echo '<br />page 2';
?>
Code of page2.php
<?php
// page2.php
session_start();
echo 'Welcome to page #2<br />';
echo $_SESSION['favcolor']; // green
echo $_SESSION['animal']; // cat
echo date('Y m d H:i:s', $_SESSION['time']);
// You may want to use SID here, like we did in page1.php
echo '<br />page 1';
?>
To clear up things - SID is PHP's predefined constant which contains session name and its id. Example SID value:
PHPSESSID=d78d0851898450eb6aa1e6b1d2a484f1
Here are brief list:
JQuery with JSON stuff. (http://www.w3schools.com/xml/xml_http.asp)
$_SESSION - probably best way
Custom cookie - will not *always* work.
HTTP headers - some proxy can block it.
database such MySQL, Postgres or something else such Redis or Memcached (e.g. similar to home-made session, "locked" by IP address)
APC - similar to database, will not *always* work.
HTTP_REFERRER
URL hash parameter , e.g. http://domain.com/page.php#param - you will need some JavaScript to collect the hash. - gmail heavy use this.
<?php
session_start();
$message1 = "A message";
$message2 = "Another message";
$_SESSION['firstMessage'] = $message1;
$_SESSION['secondMessage'] = $message2;
?>
Stores the sessions on page 1 then on page 2 do
<?php
session_start();
echo $_SESSION['firstMessage'];
echo $_SESSION['secondMessage'];
?>
Have you tried adding both to $_SESSION?
Then at the top of your page2.php just add:
<?php
session_start();
Use Sessions.
Page1:
session_start();
$_SESSION['message'] = "Some message"
Page2:
session_start();
var_dump($_SESSION['message']);
In MVC, you can pass variable one page to another like this:
<?php $this->load->view('Overview', ['customer' => $customer , 'job_id' => $job_id , 'email' => $emailid]);?>
In Overview.php page you can display variable data like this
echo $customer; // it will display customer value
echo $job_id;
echo $email; // it will display email id
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
I have a list of products that I wish to be editable. When a user hits the edit button, then the content of only the selected product needs to be changed (for example to a textbox so the user can edit the title on the fly). But how do I prevent php to echo for example a textbox to all the products- I guess it would do that automatically?
I also guess that i should use some Jquery stuff to make the content editable :P ?
The list is being looped like this:
$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
echo $products['product_name'];
echo 'Edit me';
}
As your first commenter pointed out, PHP alone is not enough here. You'll need on-page JS code that can communicate the changes in the browser, and a PHP script that can take those changes and work them back into the database. You can either write that yourself, or use proven libraries that exist specifically for this purpose, like http://backbonejs.org/ or http://angularjs.org/
These are model/view frameworks that let you show a view of your database data on a page, while keeping them editable, updating the database records when you update the entry online. But be warned: if you've never worked with MVC frameworks, you get to look forward to probably being very confused at first. The approach is completely different from the much simpler "get data from db with PHP, generate page content, send off to client, the end" approach.
Not necessarily the most efficient, but if there aren't a huge number of products how about including a simple form for each product but just hiding it until the 'Edit' link is clicked?
The list/forms:
$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
echo "<span>" . $products['product_name'] . "</span>";
echo "<a class='editButton'>Edit</a>";
echo "<form action='products.php' method='post' style='display: none;'>
<input type='hidden' name='product' value='" . $products['prodcut_id'] . "' >
<input type='text' name='title' value='" . $products['product_name'] . "' >
<input type='submit' value='Update' >
</form>";
echo "<br/>";
}
The jQuery:
$(".editButton").click(function(){
//Hide the text entry and the edit link
$(this).prev().hide();
$(this).hide();
//Show the form
$(this).next().show();
});
If you'd rather not reload the page to submit changes you could submit them via ajax too for a more dynamic user experience.