PHP - remove parameters from URL but still pass to another page - javascript

I have a php website. The first page contains a list of products and I'm currently passing the ID (picked up from mysql database) for the product within the URL to the items page i.e. localhost/item.php?4
I don't want to show any parameters in the URL so have investigated another option which is using a session.
The issue with this is that the link to each of my items is in a while loop retrieving ID and product name from the database so I'm having issues making the session mirror the ID when an item/link has been clicked.
Here's a snippet of my code (I've removed the session code):
$stmt = $con->prepare("SELECT pid, product_name FROM persons where deleted = ? order by order_age desc");
$stmt->bind_param("i", $del);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<tr><td>';
$phn = $row["pid"];
echo "<span><a class='storage' href='item.php'>" . $rows["product_name"] . "</a></span>";
}
echo "</td></tr>";
}
I guess I have two questions:
Is it possible to achieve what I need to do
What is the correct way of achieving this
Thanks in advance,
Pete

Options, briefly
You could first load /item.php?id=4 then redirect to /item-hidden.php & use $_SERVER['HTTP_REFERER'] & parse_url & process the GET portion of the referrer url.
You could also use session for this. Set the session variables when the page loads to the long-url, then redirect to the short url, load the session & clear the session.
If you just want to shorten the url, then you could use uniqid() And put the unique id in the url & save the paramaters to a session variable with that unique id.
You could use a pre-made url shortener.
You could roll your own url shortener using a reference file that holds an array or a database.
There are surely other creative solutions that I haven't thought of
My thoughts:
Hiding the url altogether will make for a poor user experience - inability to bookmark, using the back-button will be funky, hard to share an item on social media or a blog
Shortening the url is nice but not necessary
Depending on the options you're working with, you might be able to create shorthands that are more friendly to look at in the url bar or db-references for sets of options that are extremely common
What you're trying to do seems like a great learning project - learn about sessions, http_referer, databasing & whatnot. I think by doing what you're wanting, you'll learn that you don't really like how it feels - or you might come up with a clever way to make your URLs prettier & make the UX really nice.

Related

website with different content for each type of user (about security)

So i know some html, css, js, php and mysql but my knowledge is very limited regarding security issues
and for a website i'm building till now i just used css display:none (triggered with js) to
show or not to show some content to the user depending on his type (client, employee, boss).
I've understood that if you don't want to have the risk of someone seeing something he should
not (inspect page or some other way) you should not send that information(from server-side = php) at all.
I'm not sure if the way i have in mind is the right one.
If i have 3 types of users 1)clients 2)employees 3)Boss
and i want to show different content (basically the same content but a bit more information
to employees and even more to boss) to each of them for 5 of the pages that exist in the website would it be effective
to have 3 different php files(one for each type of user) for each page , store at $_SESSION['authority'] different values for each user during the login process and use that value to decide which page he can access?
For example the starting page is index.php and when the user logs in depending on his authority level (retrieved from database) he will be
redirected by using header("Location: name_of_page.php"); to index.php if he is a client, to index_employee.php if he is an employee
and to index_boss.php if he is the boss.
And in each of these pages use something like the following to prevent users with different authority to enter.
index_boss.php
<?php
session_start();
if($_SESSION['authority'] == 2 && $_SESSION['loggedin'] == true) {
?>
page content
<?php
}
else
{
if( $_SESSION['authority'] == 1 )
{
header("Location: index_employee.php");
}
else
{
header("Location: index.php");
}
}
?>
Is this the correct way to tackle this issue?
Are there ways to just use 1 php file for all users and hide or show some of the content with some other secure way?
YES it possible in the same page to do this! Just do tit like this:
according to: 1)Boss 2)employees 3)clients
index.php
<html>// Start the session here
<?php session_start();?>
<head>
//Your configuration
</head>
<body>
<?php
if($_SESSION['authority'] == 1 && $_SESSION['loggedin'] == true) {
?>
Here the Contents of the boss
<?php
elseif($_SESSION['authority'] == 2 && $_SESSION['loggedin'] == true) {
;?>
Here the contents of employee
<?php }else{ ?>
Here the contents of clients
<?php };?>
</body>
</html>
The appropriate solution here is a role based system. In other words, create 3 roles and put users into those roles. The objects you will need are:
User
Role
Permission
Optionally - application
Optionally - part of an application (action for example)
Create your role based permissions system using these objects. Hope that helps!
Your implementation does seem correct for a low level site. However, as you scale it might be difficult to keep track of these for every single part or sub-part of your website.
I would suggest either using a class approach (create a different class for each user and use objects) or even use a framework which would usually encompass usage of classes within its own structure to ease the process of implementation and coding from your side.
Frameworks you might like to implement include CodeIgniter or Laravel (in no particular order) - bear in mind that at the moment, your code is doing these if checks every single reload - a correctly implemented class or framework would in most cases automatically know what to do giving a slightly quicker reaction time but more importantly, a clearer code structure and a good base to develop on.

$_SESSION is empty when calling an api rendered with React

Context:
I have an api that is rendered with React. When I log in and I go to the admin page, I only want to see my own content, created by me and only me. To do so, I must check if my $_SESSION['user_id'] matches the publisher_id in my database. The api allows the logged in user to create/delete/edit his post. The structure for the api is :
post.php where we create a class called Post with multiple methods ( create,edit etc ).
create.php , edit.php , read.php etc where we create a Post object and call the function we require for the action wanted.
The latter then is called in one of the components in React called Create.js etc which will then be rendered after being encapsulated in other components.
$_SESSION['user_id'] is absent until after React finishes rendering all of our posts.
When I call echo $_SESSION['user_id'] right before my React container on the content.php page, the user_id will show up correctly. ( I use session.start() at the top of the page )
<?php
echo $_SESSION['user_id']; // works
//Container for our React component.When calling the api inside the
//component, $_SESSION['user_id'] is empty
echo "div id='app'></div>";
echo $_SESSION['user_id']; //works again, $_SESSION['user_id'] is the same as before
Problem:
When React renders the content from my database, nothing will show up if in my SQL query I write "... WHERE p.publisher_id=" . $_SESSION['user_id'] . " ... " which means that $_SESSION['user_id'] is not there anymore.
Any suggestions on how can I fix it?
Try adding session_start(); inside that div, or if that does not work, do define('_SESSION', $_SESSION);
I have found the cause of the issue and a solution. Here they are:
Cause: The session variable is not availble in the call of the api. Opening a session there won't help either. The cause may be because the api .php file is never used to display any html.
The solution: Create a new class called User and give it the function get_user_id that will return the following : return json_encode($variableinwhichyousavedsession);
Then go to the react class that must do any of the 4 CRUD functions, use $.get("filename.php" , function { ... ) in componentDidMount. Make sure you use json.parse to get the session id and save it into a state. This way you can operate with the session id.
One problem I encountered is that you can only use $.post when you send some input or press a button. What I need to do is for it to be called when I load the page. If I find an alternative to that or an answer, I will edit this.
EDIT: it seems that I was doing something wrong when handling the $_SESSION in my api. I have corrected it and did the following:
$product->publisher_id = $_SESSION['user_id'];
And that pretty much solved everything.

Pass data from website a to website b using java script to then use as a post query

I have website A i need to pass info to website B.
website A a user is logged in, using the current session on website A i will collect UserID from the session and i want to post UserID and UniID=3 to a data structure on website B that will store the data in variables that can be used in a post query from website B
I was thinking of using simple JavaScript like (on website A)
<div id="linkto"> <p>www.websiteb.com/&uniId=3 <P></div>
$('linkto').on('click',function(event){
UserId['UserId'] = $UserId
$(post).(url'www.websiteb.com', data );
});
then collecting the UserID and UniID somehow and then using them as variables in a post query
My question is this the correct way of going about it, I basically need to collect UserID from one website and use it on another website
Ok, I think I may have solved it.
Website A
<script language="JavaScript">
JSarray = new Array();
JSarray[0] = "$UserId";
JSarray[1] = "$var2";
function send_value(){document.myform.secret.value = JSarray.toString();}
Website B
<?php
$secret = $_POST['secret'];
$ar=explode(',',$secret);
print_r($ar);
You could also just set up the link like you have www.websiteb.com?&uniId=3. One you get to website B you covert uniId in a session and than redirect to the URL with out the uniId in the URL. This way you now have it as a session.
<?php
session_start();
$_SESSION['unvId'] = $_GET['unvId'];
header('Location: http://websiteb.com');

create html pages dynamically with proper url

I want to dynamically create webpages using a php script(for example : category.php) which takes on variable 'category' and do a mysql query to get data from the server and create a webpage.
category.php
< ? php
include_once("php_includes/db_conx.php");
$sql = "SELECT * FROM PRODUCTS WHERE CATEGORY = 'CLOTHING' ";
$result = $db_conx->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
/*GENERATE SOME WEBPAGE*/
}
}
? >
So when a user clicks a link "/category/clothing " it should pick the variable value (category = 'clothing' ) from this link and dynamically generate a webpage with the address "www.example.com/category/clothing" instead of something like "www.example.com/category/?category=clothing"
What i want to avoid is a url having '?' and '='
So I want to achieve 2 things:
A single php file generating pages dynamically by taking values from links like "/category/clothing"
Url of the new webpage should be simple and proper "www.example.com/category/clothing" (of course it should be same as the link clicked ) and not like "www.example.com/category/?category=clothing"
Can someone write a example php or js script which can achieve this or point me in the right direction(in case its very simple)
PHP can't do this by itself. You are going to need an .htaccess apache module called mod rewrite. Here is a tutorial how to make pretty urls.
http://code.tutsplus.com/tutorials/using-htaccess-files-for-pretty-urls--net-6049

Joomla - get array of article IDs, retrieve text, and link to them

I'm building a Joomla module that can get an array of all articles on the site -- regardless of category -- then identify the category, retrieve intro text and title, and display the titles, categories, and intro text of the most recent two articles in each category in a tiled layout. I have the layout done, but I don't know where to start on the rest. Is it possible?
I'm not averse to getting the articles from category blogs, but I'm not sure if that's possible.
There is the best way to retrieve the articles:
$jcontent=JControllerLegacy::getInstance('Content');
$jarticles=$jcontent->getModel('Articles');
$jarticles->getState();
$jarticles->setState('filter.article_id', $ids);
$jarticles->setState('list.limit', count($ids));
$jarticles->setState('filter.published', 1);
$articles=$jarticles->getItems();
This code was tested and, as for me, this is the best way - it uses Joomla abstractions to retrieve the articles, it uses Joomla caching and is not dependent on database structure.
This is code is not tested, you may need to check and make minor modifications.
Method 1: In this you need to query the category details again from the category id you get inside the loop.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__content');
$db->setQuery((string)$query);
$res = $db->loadObjectList();
foreach($res as $r){
//query category details also here
echo '<h3>'.$r->title.'</h3>';
echo $r->introtext;
}
Method 2: In this method you are supposed to get both content and category details in one query. In the select query you need to include the field names which you need.
$db = JFactory::getDbo();
$db->setQuery('SELECT #__content.title as contentTitle, #__categories.title as catTitle FROM #__content, #__categories WHERE #__content.catid = #__categories.id');
$details = $db->loadObjectList();
print_r(details);

Categories