How to get a username in the url after the /? - php

I am using PHP to create a social media platform. I have a fully sizeable page for the user you are viewing that is adjusting by who you are trying to view in the URL. If you go to profile.php?user=(USERNAME) it will display the data of that user.
But I want something extra to that. I do not want my users to have to fill in a difficult URL like that. I want them to be able to type profile/(USERNAME) and that it will show the data of the user they are viewing.
So how can I make it possible that the GET from ?user=(USERNAME) is in the /(USERNAME).
I hope my question is clear. Looking forward to questions or answers.
Kind regards,
Serge

The following should work for you.
Set up an input field and set the value to /profile -> <input value="profile/">, (see below HTML code for example), so that auto populates in the field for the users to type into. Then run your post value through php and check if set, sanitize (see https://www.php.net/manual/en/function.urlencode.php for more info), then build your url, lastly run that through a header redirect to redirect to the profile page.
Example below:
HTML:
<form method="post"><!--// No action needed as we will redirect with php `header()` if submit is pushed. //-->
View Users Profile:
<input type="text" value="profile/" name="searchUser" id="searchUser" ><br><br>
<input type="submit" name="submit" value="Submit">
<?=$url?><!--// Used simply to echo out your url string for testing purposes, if you are testing, simply comment out the header line in the php so the code does not redirect you to the url //-->
</form>
PHP:
$url = null; // Declare an empty variable to display URL for testing purposes
// * Not needed if your not displaying this url to test the output of your url string
// Make sure the $_POST globals are set using isset()
if(isset($_POST['submit']) && isset($_POST['searchUser'])){
// Remove the `profile/` string from the input value so we only have the user being searched
$post = str_replace("profile/","",$_POST['searchUser']);
// More sanitation may be needed depending on what you allow your users to use for usernames
$cleanPost = filter_var ( $post, FILTER_SANITIZE_STRING);
// Get the server host
$host = $_SERVER['HTTP_HOST'];
// Get the directory
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
// Get the root
$root = 'myawesomesocialsite.com';
// Set the path to profile and add the field input from user
$profile = "/profile?user=".$cleanPost;
// Construct the URL using the declared variables
$url = "http://$host$uri/$root$profile";
// Redirect user using header()
// Comment the header("Location: $url"); out to test the output of your $url string if you're getting errors with redirect
header("Location: $url");
exit();
}
Using a function:
function constURL($root, $dir){
$post = str_replace("profile/","",$_POST['textInput']);
$cleanPost = filter_var ( $post, FILTER_SANITIZE_STRING);
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$urlPost = "?user=".$cleanPost;
$url = "http://$host$uri/$root$dir$urlPost";
header("Location: $url");
exit();
}
// USE FUNCTION
// Make sure you set the values for root and dir
if(isset($_POST['submit']) && isset($_POST['searchUser'])){
$root = 'myawesomesocialsite.com';
$dir = "/profile";
constURL($root, $dir);
}

Related

Dynamically load page from unique identifier

How would I go about this?
I am allowing users to sign in via various social websites. I get their unique identifiers and than redirect them to some other page
$id = ($profile->identifier);
$newURL = "/your-data/$id";
header('Location: '.$newURL);
, where they will be able to store some data about themselves.
I know and I will get here all data neccessary and save it to database.
I would like, on /your-data/98432048320
show them website generated from /template/header,index,footer.php
Here is what I have done so far to get this working:
on your-data/index.php
<?php
include("templates/header.htm");
// Set the default name
$action = 'index';
// Specify some disallowed paths
$disallowed_paths = array('header', 'footer');
if (!empty($_GET['action'])) {
$tmp_action = basename($_GET['action']);
// If it's not a disallowed path, and if the file exists, update $action
if (!in_array($tmp_action, $disallowed_paths) && file_exists("templates/{$tmp_action}.htm"))
$action = $tmp_action;
}
// Include $action
include("templates/$action.htm");
include("templates/footer.htm");
?>
I can not get it to run. It`s just plain PHP, no frameworks...
You should not generate dozens of templates for each unique user. It would be quite redundant.
Instead, make one php file, let's call it content.php (whatever).
Such file can contain dynamically generated data respectively to certain user. Include content.php to your main index.php.
your-data/index.php:
<?php
include("templates/header.htm");
$action = 'index'; // Set the default name
if (!empty($_GET['action'])) {
$tmp_action = basename($_GET['action']);
if (is_numeric($tmp_action)){ // check if user identifier was passed in
include("templates/content.php");
}
}
include("templates/footer.htm");
?>
Now $tmp_action variable is freely accessible within content.php.
content.php:
<?php
$userId = (int) $tmp_action;
// possible case
$query = "SELECT name, age, activity FROM social_users WHERE id = ". $userId;
// here you can get all needed data for certain user
// which can be shown in #mainContainer div
?>
<div id="mainContainer"></div>

Link value of form in PHP

I have an html file, basically a simple form: The purpose is to submit a value that runs a piece of code on a PHP file ('alternative.php') See sample of html code:
<form name="input" action="alternative.php" method="POST">
Area: <input type="text" name="area"><br><br>
<input type="submit"><br>
</form><br><br>
This runs smoothly
Now I have a second PHP file ('alternative2.php') and this file automatically needs to link to the data that is input in the form.
Excerpt of php code for alternative2:
<?php
require_once 'header.php';
/** Create HTTP POST */
$accomm = 'ACCOMM';
$region = '';
foreach ($result->area as $entry) {
$region = $entry->attributes()->area_name;
break;
}
$page = '10';
Both alternative.php and alternative2.php require header.php.
Excerpt of header.php:
<?php
/** Create HTTP POST */
$country = 'Australia';
$area = htmlspecialchars($_POST["area"]);
$seek = '<parameters>
<row><param>COUNTRY</param><value>'. $country .'</value></row>
<row><param>AREA</param><value>'. $area .'</value></row>
</parameters>';
Currently it returns "Notice: Undefined index: area in C:\xampp\htdocs...." when I run it.
How do I go about this?
Thanks
The error suggest that $_POST["area"] is not defined, if you don't reach alternative2 from your form, then that's why you see this; if you want to reach alternative2 from other place (for example directly), or if the value of a variable must be the same on several pages, then you may want to consider using Sessions.
Check if the $_POST values exist before using them...
if (isset($_POST["area"])){
//do stuff
}
Basically it has to do with which file your form actually submits to. If your form submits to only alternative.php then you aren't receiving the POST information to your second page. The easiest and logical choices in my opinion (based on what I see from your code) is to merge the functionality of alternative.php and alternative2.php into a single page, or use sessions to store the POST information which will then be available to both pages. If you were to use sessions you would be doing something like shown below.
Start with the file that handles your form input (alternative.php I presume) and add
session_start();
to the top of that file. Then, in whatever block of code you have getting your form information add the following line:
$_SESSION['area'] = $_POST['area'];
Now your information is stored and will be available from request to request.
Then in your head.php file, access the info via $_SESSION variables.
<?php
/** Start Session */
session_start();
/** Create HTTP POST */
$country = 'Australia';
$area = htmlspecialchars($_SESSION['area']); //Access your session variable.
$seek = '<parameters>
<row><param>COUNTRY</param><value>'. $country .'</value></row>
<row><param>AREA</param><value>'. $area .'</value></row>
</parameters>';
?>

How should I sanitize _GET variables that are only used on page?

I am fairly new to PHP and am using a couple of _GET variables to determine page layout/web service data and some other logic on the page. I am not storing the data or writing to a DB of any kind. What kind of sanitization should I be using for this?
For example, one var I'm using is like this:
$querystring = $_SERVER['QUERY_STRING'];
if(isset($_GET['semester']) && $_GET['semester'] != ''){
$listxml = simplexml_load_file("http://path/to/webservice/?".str_replace('semester','term',$querystring));
What's going on there is if the querystring has the ?semester= set and not blank then I replace it with 'term' and pass through the querystring as is to a web service URL (the web service uses the term variable but the term variable interferes with wordpress and redirects to the posts page for that 'term' (tag/category in WP) so I pass it through WP as semester and then just change it to term for the web service call.
So in this case I'm not doing anything with the _GET except passing it on as is to a web service what the web service does with the querystring is out of my hands, but should I 'prep' it in any way for them?
--
I've also got cases similar to this:
$display = '';
if (isset($_GET['display'])) {
$display = $_GET['display']; //set sort via querystring
} else {
$display = 'interest'; //set to default by interest
}
later:
<div id='byalphabet' class='<?php global $display; if($display != 'alphabet'){echo 'hide';} ?>'>
and
<div id="byinterest" class="<?php global $display; if($display != 'interest'){echo 'hide';} ?>">
--
Also using for some dynamic javascript:
$view = '';
if (isset($_GET['view'])) {
$view = $_GET['view']; //set view via querystring
}
Later:
<script>
<?php if ($view != ''){ $view = str_replace('/','',$view); ?>
jQuery('#<?php echo $view; ?>').trigger('click'); //activate view option accordion pane
jQuery('html,body').animate({'scrollTop':jQuery('#<?php echo $view; ?>').offset().top - 50},500); //scrollTo view
</script>
--
Other cases include searching an array for a _GET value array_search($_GET['major'], $slugs); and redirecting a page using:
$parts = explode('/',$_SERVER['REQUEST_URI']);
Header( "HTTP/1.1 301 Moved Permanently" ); //SEO friendly redirect
Header( "Location: http://www.site.ca/programs/outline/".$parts[3]."/" );
Edit: I have read many of the suggested similar questions that popped up but they mostly refer to using the data in some other way such as inserting into a DB.
You should always sanitize input parameters. Even if you aren't using them in the database, you are still vulnerable to cross site scripting/XSS attacks.
<?php $view = $_GET['view'] ?>
<script>jQuery('#<?php echo $view; ?>').trigger('click');</script>
For example given the above code, everything is fine if ?view=page_one because your JavaScript looks like jQuery('#page_one').trigger('click');.
But what if your querystring is ?view=hacked%27)%3B%20alert(document.cookies)%3B%20jQuery(%27%23page_one - now your javascript looks like the following on the page:
jQuery('#hacked'); alert(document.cookies); jQuery('#page_one').trigger('click');
The alert() could just as easily be an AJAX request to send auth tokens, etc to a different server.
Ultimately the type of sanitizing you do depends on the context that you are using the input. In this example, you might want to make sure you escape single quotes for example, but what is appropriate may differ between implementations.
Good article on sanitizing inputs here: http://coding.smashingmagazine.com/2011/01/11/keeping-web-users-safe-by-sanitizing-input-data/

Issue Passing JS variable to PHP include file

I have a php file where I am using it to setup dynamically generated pages based on the input variables. It starts on and index.html page where the variables are gathered some of which are not simple strings but complex Google Earth objects. On the submit of that page it is posted to another page and you are redirected to the created file. The trouble is coming when I try to use that variable within the php include file that is used to generate the pages.How do i properly get a variable from this form and then pass it through to be able to use it on the new generated page. Here is what I am trying currently.
On the click of this button the variable flyto1view is set.
$("#flyto1").click(function(){
if (!flyto1view){
flyto1view = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
$("#flyto1view1").val(flyto1view)
}
else {
ge.getView().setAbstractView(flyto1view);
}
});
Then from here I have tried setting the value to an hidden field but Im not sure if that kinda of variable has a value that can be set like that. Whats the best way to get this variable to here after post
<?
if (isset($_POST['submit']) && $_POST['submit']=="Submit" && !empty($_POST['address'])) {//if submit button clicked and name field is not empty
$flyto1view1 = $_POST['flyto1'];
$address = $_POST['address']; //the entered name
$l = $address{0}; // the first letter of the name
// Create the subdirectory:
// this creates the subdirectory, $l, if it does not already exists
// Note: this subdirectory is created in current directory that this php file is in.
if(!file_exists($l))
{
mkdir($l);
}
// End create directory
// Create the file:
$fileName = dirname(__FILE__)."/$address.html"; // names the file $name
$fh = fopen($fileName, 'w') or die("can't open file");
// The html code:
// this will outpout: My name is (address) !
$str = "
<? php include ('template.php') ?>
";
fwrite($fh, $str);
fclose($fh);
// End create file
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
die();
}
// The form:
?>
Firstly. creating files from user input is pretty risky. Maybe this is only an abstract of your code but doing a mkdir from the first letter of the input without checking that the first letter is actually a letter and not a dot, slash, or other character isn't good practice.
Anyway, on to your question. I would probably use $_GET variables to pass to the second file. So in the second file you use <?php $_GET['foo'] ?> and on the first file you do:
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
You could also echo the variable into your template like so:
$str = '
<?php
$var = \'' . $flyto1view1 . '\';
include (\'template.php\')
?>';

How do I redirect to referring page/url after successful login?

I'm aware that this topic has been covered before here on Stack, and I have looked at some answers, but I'm still a bit stuck, being fairly new to PHP. Every page on my website requires a login, and so users are redirected to a login page on page load. At the top of each page then I have:
<?
require("log.php");
include_once("config.php");
include_once("functions.php");
?>
This redirects the user to log.php (with new code added):
<?
session_name("MyLogin");
session_start();
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php"; // default page for
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","",""); // your MySQL connection data
$db = mysql_select_db(""); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM users WHERE login='$name'");
if (!$q_user) {
die(mysql_error());
}
if(mysql_num_rows($q_user) == 1) {
$query = mysql_query("SELECT * FROM users WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) {
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/$url"); // success page. put the URL you want
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}
// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}
?>
The login form is contained in login.php. The code for login.pho relevant to the PHP/log.php is:
<?
session_start();
if($_GET['login'] == "failed") {
print $_GET['cause'];
}
?>
and
<form name="login_form" id="form" method="post" action="log.php?action=login">
The answer that I came across stated that I should add:
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
to the top of each page, which I did, at the top of the page (above "require("log.php");"), and then add:
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php"; // default page for
to my login page, and use the following URL for redirect on successful login:
header("Location: http://example.com/$url"); // perform correct redirect.
I am not 100% where the code which stores the referring URL should go, at the top of log.php or login.php.
I have tried adding it to both, but the login page is just looping once I have entered the username and password.
I wonder if someone could help me get this working?
Thanks,
Nick
It appears that I don't have the privilege to comment on your post, so I'll do the best that I can to answer. I apologize for all of the scenarios, I'm just doing the best I can to answer on a whim.
SCENARIO 1:
If you've truly not selected a database in your code, as demonstrated here, could that potentially be your issue? Please do note, that the code below, is the code you've posted.
$db = mysql_select_db(""); //put your database name in here
SCENARIO 2:
The code below is not something I've ever used in anything I've built, might I suggest that you try replacing that line of code with the line below it?
if(session_is_registered("name") == false) { // Current
if(isset($_SESSION['name']) == false) { // Potential Replacement
SCENARIO 3:
If you're logic for the following, exists on the login.php file as well... That could potentially be your problem. Upon visiting your site, I noticed your form appears on login.php, yet your logic is posting to log.php. I'm hoping this bit of code can help rule out that "jump", as login.php might be saving itself and overwriting the $_SESSION variable you've established
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
If it's too complex to take it out of the login.php file, if you even have it there, I've put together some code that you can use to create "internal" breadcrumbs, so you can go 2 pages back in your history.
if(!isset($_SESSION['internal_breadcrumbs']))
$_SESSION['internal_breadcrumbs'] = array();
$_SESSION['internal_breadcrumbs'][] = $_SERVER['REQUEST_URI'];
$max_breadcrumbs = 5;
while(count($_SESSION['internal_breadcrumbs']) > $max_breadcrumbs)
array_shift($_SESSION['internal_breadcrumbs']);
That will create an array with a max of $max_breadcrumbs elements, with your most recent page at the end, like the following
Array
(
[internal_breadcrumbs] => Array
(
[0] => /other_page.php
[1] => /other_page.php
[2] => /other_page.php
[3] => /user_page.php <-- desired page
[4] => /login.php <-- most recent page
)
)
So now... you can setup your url to be something more like the following...
// I'm doing - 2 to accommodate for zero indexing, to get 1 from the current page
if(isset($_SESSION['internal_breadcrumbs']))
$url = $_SESSION['internal_breadcrumbs'][count($_SESSION['internal_breadcrumbs']) - 2];
else
$url = "index.php"; // default page for
All the best, and I certainly hope this has helped in some way.
IN SCENARIO 4
From the client test the login/password which ajax XMLHttpRequest with javascript code to a dedicated script for validation (do it on mode https for secure)
If response is right send the login password to your script server.
Stips : Encoding password is better secure !
Using header() function it's a bad idea.
Manual specification say ;
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
So in your case, i suggest that to use cookies with an ID generate only for the session, at the first connection its generate, and the duration of the cookie maybe for only from 2 to 10 minutes.
Regenerate cookie each time the loging.PHP is called !
Have a nice day

Categories