I am new to php, I need small help
I m creating a page in php named index.php
i want when someone view that page automatically a number or anything would be added to the url end
Like www.abc.com/index.php ---> www.abc.com/index.php?abc or ?132
when ever that index page is refreshed it should get a number or any variable in the end
Try this:
<?php
if (!isset($_GET["123"])) {
header("Location: " . $_SERVER["PHP_SELF"] ."?123");
}
$QS = $_SERVER["QUERY_STRING"];
$URL = "http://www.example.com/index.php";
// Check if Anything already assigned
if( empty($QS) ) {
// Generate Any RANDOM Number Here
$NUM = mt_rand(999, 9999);
// Reload Page and assign number
header("Location: {$URL}?{$NUM}");
}
Place this code in the very top of your page
Give this a go
<?php
$num = '123';
if(!isset($_GET[$num])){
header("Location: /path/to/page?$num");
}
Related
I'm trying to code the last 5 page names the user viewed on my site and produce it into a list. I'm currently able to get the current page name, but I don't know how to get the previous pages. This is the code I'm using to get the current page name:
<?php
$pageName = basename($_SERVER['PHP_SELF']);
echo $pageName;
?>
PHP Sessions should get you going in the right direction. For example:
session_start();
if(!isset($_SESSION['pages'])) {
$_SESSION['pages'] = array();
}
if(count($_SESSION['pages']) < 5) {
$_SESSION['pages'] [] = $_SERVER['PHP_SELF'];
} else {
echo "Limit reached";
}
print_r($_SESSION['pages']);
I recommend you use PHP Sessions to accomplish this.
So, save the current page name that you want to the sessions variable like so:
<?php
$pageName = basename($_SERVER['PHP_SELF']);
$_SESSION['pageName'] = $pageName;
?>
And then continue to save these names. #Len_D just beat me to the punch with an answer that uses arrays and is likely what you need.
my code is related to breadcrumbs.. that is it should display previous page or from where it is navigated and i achieved it partially , while im refreshing 2-3 times im getting the current page not the previous page.. so pl help me on this
my code lies in session.php as
$add = $_SERVER['PHP_SELF'];
if($_SESSION['pageadd'][1]!= $_SESSION['pageadd'][2])
{ $_SESSION['pageadd'][2]= $_SESSION['pageadd'][1];
}
echo $_SESSION['pageadd'][2];
if(($_SESSION['pageadd'][1]!= $add) )
{ $_SESSION['pageadd'][1]= $_SESSION['pageadd'][0];
$_SESSION['pageadd'][0]=$add;
}
What you want isn't a breadcrumb - it's a history for visited pages! This could be achieved with something like this:
if (!isset($_SESSION['pageadd'])) {
$_SESSION['pageadd'] = array();
}
// add page
$_SESSION['pageadd'][] = $_SERVER['PHP_SELF']
// only save last 5 pages
if (count($_SESSION['pageadd'])) > 5) {
array_shift($_SESSION['pageadd']);
}
Try to use $_SERVER['HTTP_REFERER'] it will return you previous url. However you need to store it in some hidden field or session like you are doing now.
Hope this help :)
I have a link, an offer page and a destination page. I need to carry the variables from the original link and input them into the links on the offer page.
original link
www.example.com/offerpage.php?offer=1&aff_id=var1&aff_sub=var2
Where you see var1 and var2, those could be any number.
I'm assuming I could do something like this (this is a total guess, just want to make sure I do it correctly).
<?php
if(array_key_exists('aff_id', $_GET)){
$aff_id = $_GET;
}
else {
$aff_id = '1';
}
?>
Then the links on the offer page would be
www.offer.com/index.php?offer=1&aff_id=<?php echo $aff_id; ?>&aff_sub=<?php echo $aff_sub; ?>
and whats the correct format for doing multiples?
This should probably do what you want:
if (!array_key_exists('aff_id', $_GET)) {
$_GET['aff_id'] = 1;
}
echo http_build_query($_GET);
If the query string is offerpage.php?offer=1&aff_id=var1&aff_sub=var2then the output will be:
offer=1&aff_id=var1&aff_sub=var2
And, if the query string doesn't contain aff_id, i.e. offerpage.php?offer=1&aff_sub=var2 then the output will be:
offer=1&aff_sub=var2&aff_id=1
I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!
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