So I am trying to practice PHP and I am stuck with using headers. I am using xampp in doing this. I have a simple form wherein the user will log in in the "index.php" now when the log in is successful the header function will start and redirect the page to "includes/profile.php". Now here is the problem, after the header I am currently in "includes" folder so when I use other .php or .css files outside includes folder i need to do "../example/example.php". This mess up my paths because my CSS file is in "css/example.css" so i need to put "../". Is there any way to always make the "pointer" go back to the parent directory even after using header so that i dont need to use "../"?
index.php
<?php
session_start();
if(isset($_SESSION['username'])&& isset($_SESSION['password']))
{header("Location: includes/profile.php");exit;}
if (isset($_POST['submit'])) {
if($_POST['username']=="junji" && $_POST['password']=="secret"){
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['expiry']=time();
$username = $_SESSION['username'];
$password = $_SESSION['password'];
header("Location:includes/profile.php");
exit;
}
else{
$username = "";
$password = "";
session_destroy();
}
}
?>
//end of index.php
now inside the profile.php
<?php
session_start();
if(isset($_SESSION['username'])&& isset($_SESSION['password']))
{if(time()-$_SESSION['expiry']<5){?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php include_once('head.php');
?>
</head>
<body>
<div class="container">
<h1>Junji's Bio</h1>
<div class="row">
<div class="col-xs-8">
<h2>Content</h2>
<?php
include_once ('content.php');?>
</div>
<form method="POST">
<div class="col-xs-4 sidebar">
<div class="alert alert-success"> <?php print "You are currenly logged in as ";
print '<br><h3>';
print $_SESSION['username'];print "\t".'<input type="submit" class="btn btn-info" name="submit" value="Logout">'; ?></h3> </div>
</div></form>
</div>
</div>
</body>
</html>
<?php if(isset($_POST['submit'])){
session_destroy();
header("Location: ../index.php?msg=You have been successfully logged out!");
exit;
}
}else
{session_destroy();
header("Location:../index.php?msg2=Your session has expired! Please Log-in again.");
exit;
}
}
else
{session_destroy();
header("Location:../index.php");exit;
}
as you can see the includes are directly called and no "includes/example.php" is needed. which means inside my "head.php" i need to make two
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css"> just so i can get the css to work on both "index.php" and "includes/profile.php"
If you don't mind using an absolute path,
Try using "http://localhost/css/example.css"
The way I handle this is to set a level variable at the top of the page:
$level = ''; This would be top level
$level = '../' This would be for files in a top level folder
$level - '../../'; This would be for files in a sub directory... and so on
Then all you need to do is set the $level var in the path:
$level.'css/example.css -- works everytime
NOTE: If you are using .htaccess you need to call the full url to both .css and .js files
You could define a constant containing the absolute root, and include that in each path. If you save your root in a variable or constant, instead of write it directly in your files, it will be easier for you if your root changes in the future.
define("ROOT", "http://localhost/");
include ROOT . 'example/example.php';
Or maybe construct a function to call?
function path($string, $echo = TRUE) {
$root = "http://localhost/";
if($echo === TRUE) {
echo $root . $string;
} else {
return $root . $string;
}
}
path('index.php');
header("Location: " . path('test.php', false));
Related
I am using this sessions logic if user is not admin so he don't have to get access admin page function is it good sessions logic? approach or should i use another one please guide me further.LOOK this index page i have some links have to access the other member then admin and all links for admin please tell me what links is in url component you are using
<?php
include "config.php";
session_start();
if( (!isset($_SESSION['username'])) && (!isset($_SESSION['type'])) ){
header('location:login.php');
}
if($_SESSION['type'] != 'Administrator')
{
header('location:index.php');
}
?>
index.php
<?php
include "config.php";
session_start();
if(!isset($_SESSION['username']))
{
header('location:login.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="list-group">
Article
Categories
<?php
if($_SESSION['type']=='Administrator'){
?>
Media
tempelate
Setting
<?php
}else{
?>
Profile
<?php
}
?>
Logout
</div>
</div>
</body>
</html>
Since you want the user to not get access to the admin page, a slightly more robust check would be to probably first ascertain whether the current page is indeed admin.php. If yes, then type can be verified so as to know if it's indeed set to Administrator, before the access can be granted.
If it is not set or is set to something else, then the user may be taken back to index.php page.
<?php
include "config.php";
session_start();
$url_components = explode('/', $_SERVER['SCRIPT_NAME']);
$current_url = $url_components[count($url_components) - 1];
if(!isset($_SESSION['username'])){
header('location:login.php');
}
if(!($current_url == 'admin.php'
&& isset($_SESSION['type'])
&& $_SESSION['type'] == 'Administrator')){
header('location:index.php');
}
?>
I cannot get images to show using php function. All permissions have been granted and image location is correct but get this ..see picture
index.php file
<?php
include 'inc/function.inc.php';
include 'header.php';
fetchProfile($conn);
?>
<script src="assets/js/bootstrap.js"></script>
</body>
</html>
function.inc.php file
function fetchProfile($conn){
if ($rowImg['status'] == 0) {
$username = $row['uid'];
$image = '../assets/img/profile.png';
echo "<img src='".$image."' style='width:120px;height:120px' class='img-responsive' alt=''>
<div class='captionN'>
<h4>" . $username . "</h4></div>;
Solved ->
When operating from functions in a different file, the path will remain the location from the index.php and not from the function.inc.php's location.
index.php file
<?php
include 'inc/function.inc.php';
include 'header.php';
fetchProfile($conn);
?>
<script src="assets/js/bootstrap.js"></script>
</body>
</html>
function.inc.php file
function fetchProfile($conn){
if ($rowImg['status'] == 0) {
$username = $row['uid'];
$image = 'assets/img/profile.png';
echo "<img src='".$image."' style='width:120px;height:120px' class='img-responsive' alt=''>
<div class='captionN'>
<h4>" . $username . "</h4></div>;
The source of the image is ../assets/img/profile.png, if the file index.php is at the root of your site it is normal that the image doesn't appear because you are trying to fetch a file that is outside your site.
The problem could be that the folder assets is outside of your site or that your path is not correct.
This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 7 years ago.
config.php ( edited but still have same problems ):
<?
$judul ="my site title";
?>
my index.php:
<?php
session_start();
include('config.php');
mysql_connect($server,$login,$pass) or die("Nggak bisa koneksi");
mysql_select_db($db);
$fail = " ";
?>
<title><? echo "$judul"; ?></title>
</head>
the result is my website title is
<? echo "judul; ?>
not like i want to...
Is there anything that I should change?
the goal is:
I want to put some variable like footer copyright title inside config.php so if I need to edit it's only need to edit config.php
----edited----
by the way thank you for all answer
it is work now
i use #Tanuel comment
once again thankyou
i vote answer ( green checklist ) based on the first answer, since i use syntax from comment
config.php
define('title','Hello Word');
index.php
include('config.php')
`<title><?php echo title; ?></title>`
First, you have a mistake in your config.php. You forgot $. Second, you $judul is not declared in your index.php. May be you must change it to $title after correcting config.php?
In config.php, the variable declaration is incorrect. Use the below code for that.
<?php
$title = "Site Title";
?>
If your idea was to define the title as a constant, use the below code instead (on config.php)
<?php
define('title',"Site Title");
?>
In the index.php, incorrect variable is used. Use $title to get the actual title initialized in config.php (if you are using variable to get title). Use the below code on index.php
<?php
session_start();
include('config.php');
mysql_connect($server,$login,$pass) or die("Nggak bisa koneksi");
mysql_select_db($db);
$fail = " ";
?>
<head>
<title><?php echo $title; ?></title>
</head>
If you want to use the constant instead, use the below code
<?php
session_start();
include('config.php');
mysql_connect($server,$login,$pass) or die("Nggak bisa koneksi");
mysql_select_db($db);
$fail = " ";
?>
<head>
<title><?php echo title; ?></title>
</head>
Define the variable config.php as global variable.
<?php
global $pageTitle;
$pageTitle = "Site Title";
?>
And in the index.php again you have to call it as global variable.
<?php
session_start();
include('config.php');
mysql_connect($server,$login,$pass) or die("Nggak bisa koneksi");
mysql_select_db($db);
$fail = " ";
global $pageTitle;
?>
<head>
<title><?php echo $pageTitle; ?></title>
</head>
If you want in multiple pages just use it like array.
In config.php
<?php
global $pageTitle;
$pageTitle['page1'] = "Site Title 1";
$pageTitle['page2'] = "Site Title 2";
?>
Use this code
config.php
<?php
define('title','my site title');
?>
my index.php
<?php
session_start();
include('config.php');
mysql_connect($server,$login,$pass) or die("Nggak bisa koneksi");
mysql_select_db($db);
$fail = " ";
?>
<title><?php echo title; ?></title>
</head>
Can some one tell me how to "include" a variable from another .php file without all its other content.
index.php
<?php
$info=file('somedir/somefile.php');
$v1=trim($info[2]);
$v2=trim($info[3]);
$v3=trim($info[4]);
?>
the somedir/somefile.php
<?php
$variable=something;
$variable2=someotherting;
$variable3=thirdone!;
All the other content there may not be runned or showed.
?>
Can anybody please help me??
Edit:
Its for my dynamic page.
<html>
<?php
include_once 'config.php';
include_once 'includes/mysqlconnect.php';
$url_slash=$_SERVER['REQUEST_URI'];
$url= rtrim($url_slash, '/');
//$url = basename($url);
$info=file('sites/'.$url.'.php');
$title=trim($info[2]);
?>
<head>
<meta charset="UTF-8">
<title>$title</title>
<link rel="stylesheet" type="text/css" href="<?php echo $domain;?>themes/reset.css">
<link rel="stylesheet" type="text/css" href="<?php echo $domain;?>themes/<?php echo $theme;?>.css">
</head>
<body class="body">
<div class="container-all">
<?php include_once 'includes/header.php';?>
<div class="container">
<?php include_once 'includes/navigationbar.php';?>
<?php include_once 'includes/rightsidebar.php';?>
<div class="content"><?php
if ($url==''){
include_once "sites/home.php";
}
elseif (file_exists("sites/$url.php") && is_readable('/var/www/html/sites/'.$url.'.php')){
include_once '/var/www/html/sites/'.$url.'.php';
}
else {
include_once 'sites/404.php';
}
?></div>
<?php include_once 'includes/footer.php';?>
</div>
</div>
</body>
</html>
Hope you understand my question now.
Programming is just driving your thoughts :)
So what i want to say that your question is how you can include just some part of an included file and my answer is that you can achieve that by doing a test each time the main file is included from withing this file to see if the file is included internally or not and you can be more precise in a way that you split your main file into block which are loaded due suitable variable
Take a look for this workaround and hope you will understand what i mean
Supposing we have the main file named main.php contains that contents
<?php
echo 'I am a java programmer';
echo 'I know also PHP very well';
echo 'When the jquery is my preferred toast !';
?>
now i have three external files that will include that file each file is specific for one of this 3 programming language
So i will create my 3 files in this way :
File : java.php
<?php
$iamjavadevelopper = 1;
include_once("main.php");
?>
File : phpfav.php
<?php
$iamphpdevelopper = 1;
include_once("main.php");
?>
File : jquery.php
<?php
$iamjquerydevelopper = 1;
include_once("main.php");
?>
and my main.php will be coded in this way
<?php
if(isset($iamjavadevelopper))
echo 'I am a java programmer';
if(isset($iamphpdevelopper))
echo 'I know also PHP very well';
if(isset($iamjquerydevelopper))
echo 'When the jquery is my preferred toast !';
?>
By this way each one of our three external files will show just a part of the included file :)
The only way I can think of without cookies or session's is to make an if condition in the page.
like that:
index.php
<?php include('somedir/somefile.php');?>
the somedir/somefile.php
<?php
if ($pageName != 'somefile.php') {
$variable=something;
$variable2=someotherting;
$variable3=thirdone!;
} else {
// All the other content
}
?>
Save the variables in a separate file that can be included separately. Do it the sane way. Structure your code properly, don't try to invent solutions for problems you have because your structure is messy.
I have a site under development with a "News" section and an "Older News" section. The news are stored individually in external PHP files which are loaded by the server by PHP (the server counts the number of PHP files and displays the last one – the current news – in the "News" sections and all the others in the "Older News" section:
<!-- ####### NEWS ####### -->
<div id="news">
<h2>NEWS</h2>
<div>
<a id="showoldnews" href="#news">OLDER</a>
</div>
<?php $directory = "assets/news/"; if (glob($directory . "*.php") != false) { $newscount = count(glob($directory . "*.php")); } else {} ?>
<?php include('assets/news/news' . $newscount . '.php'); ?>
<!-- ####### OLDER NEWS ####### -->
<div id="oldnews">
<h2>OLDER NEWS</h2>
<?php
$newscount = $newscount-1;
while ($newscount>0) {
include('assets/news/news' . $newscount .'.php');
--$newscount;
}
?>
</div>
The "Older News" section is initially hidden and only made visible by a jQuery trigger:
// Show old NEWS
$('a#showoldnews').click(function () {
$('#oldnews').show(400);
});
But I am expecting problems in long-term: since all news are loaded in the first place, this means that with more and more news coming up the website will be loading slower. And even if it's "acceptable", it's still not the ideal solution.
I was thinking on using jQuery.load() to load an external PHP file that would then load the old news only when the user asks for it.
The problem is that I don't know if its possible to load the following script by using jQuery.load() after the user clicks on a link:
<?php
$directory = "assets/news/";
if (glob($directory . "*.php") != false) {
$newscount = count(glob($directory . "*.php"));
}
else {
}
?>
<?php
include('assets/news/news' . $newscount . '.php');
?>
It this approach acceptable? I have tried, but it didn't work at all (I could load static content with the load() function, but I was not able to make the server process the PHP script. I don't know if it's possible to make the server process the PHP code, because PHP processing is done on the the server side before the website begins loading... which is not the case.
UPDATE #1
I have the following that loads the 'load.php' file from the server:
<script type="text/javascript">
$('#oldnews').load('load.php');
</script>
The content of the load.php file is:
<div class="section" id="oldnews">
<h2>OLDER NEWS</h2>
<div class="topLink">
TOP
</div>
<div class="topLink2">
<a id="hideoldnews" href="#news">HIDE</a>
</div>
<?php
$newscount = $newscount-1;
while ($newscount>0) {
include('assets/news/news' . $newscount .'.php');
--$newscount;
}
?>
</div>
The "TOP" and "HIDE" links appear without any problems. However, the PHP block seems to not be processed at all...
PHP can be run before jQuery grabs the content... Here is what I setup and tested...
test.html
<!DOCTYPE HTML>
<html>
<head>
<script type="text/JavaScript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<div id="feeds"><b>45</b> feeds found.</div>
<script type="text/JavaScript">
$("#feeds").load("go.php");
</script>
</body>
</html>
go.php
<?php
echo 'Hi';
?>
And the result is that #feeds .innerHTML is "Hi"... I would love more information/code in replicating the situation. It might help to take a peek at the jQuery load API documentation.
As #joseph told its correct and helped me, but in mycase i wanted to hide the content of the External Php file,
Below is my code changes which had helped me !
<!DOCTYPE HTML>
<html>
<head>
<script type="text/JavaScript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<b>Db file result</b>
<div id="feeds" hidden=""></div>
<script type="text/JavaScript">
$("#feeds").load("db.php");
</script>
</body>
</html>
My Php file had database connection so i had to hide it,
db.php
<?php
session_start();
$db = pg_connect("host=ec2-xxx-x0-xxx-xx.compute-1.amazonaws.com port=5432 dbname=dxxxxxxxxx user=vxxxxxxxxxx password=1xxxxxxxxxxxxxxxxxxxxxxxxxxxxd");
pg_select($db, 'post_log', $_POST);
$query=pg_query("(SELECT id,name, FROM organization WHERE is_active = 'true' AND account_token = '".$_SESSION['account_token']."');
$json=array();
while ($student = pg_fetch_array($query)) {
$json[$student["is_user"]."-".$student["id"]] = $student["name"]."-".$student['pan'];
}
$textval = json_encode($json);
$foo = "var peoplenames=" . $textval;
file_put_contents('autocomplete-Files/'.$_SESSION['account_token'].'.js', $foo);
echo "<script>location='filename.php'</script>";
?>