If you're on a shared environment, and have no way of disabling register_globals, this little "unregister_globals" snippet could come in handy:
<?php
if (@ini_get('register_globals'))
foreach ($_REQUEST as $key => $value)
unset($GLOBALS[$key]);
?>
Printable View
If you're on a shared environment, and have no way of disabling register_globals, this little "unregister_globals" snippet could come in handy:
<?php
if (@ini_get('register_globals'))
foreach ($_REQUEST as $key => $value)
unset($GLOBALS[$key]);
?>
There is actually a reason why register_globals is enabled by default. So you might as well code your applications to take advantage of it.Quote:
Originally Posted by jaspalmxtech
a) it's disabled by default (both php.ini-dist and php.ini-reccomended have them at off), and b) no you shouldn'tQuote:
Originally Posted by Icheb
I don't have register globals enabled, and I'm sure many people don't. So you're going to leave them out? Bad, bad buisness practices... (Although I'd hope you'd never own a buisness)
Yes, of course, I meant disabled.
And even if it's enabled, the _POST or HTTP_POST_VAR array is still accessible. So there is absolutely no reason why you should code with it being enabled, unless you like developing insecure applications. Bad business practice.
You're not the only one who can be arrogant.
Its possible to modify an array in a foreach statement:
If you do something like this:
The numbers in the original array arent changed at all.PHP Code:$numbers = array(1,2,3,4,5,6);
foreach($numbers as $number){
$number = 7;
}
But this:
Will do the work. :)PHP Code:$numbers = array(1,2,3,4,5,6);
foreach($numbers as &$number){
$number = 7;
}
Look the & sign that you should put in front of the variable, now you array contains only sevens!
While I'm not entirely new to this forum, there's still oodles of stuff I keep discovering all of the time.
I hope I'm not repeating what's been said earlier, but I have a tip for in-bound variables within classes.
This method copies a bunch of stock super global variables into just one associative array variable:
And just to add some extra funk, each time a new variable enters the application, a call is made to a method which checks to see if this session is still active. If not, you're logged out:PHP Code:function getGlobals () {
// if any POST values are issued, they are dealt with here...
if (!empty($_POST)) {
$this->arrayActions = Index::ValidateUserSessionTime($_POST);
// ... else, if any GET values are issued...
} elseif (!empty($_GET)) {
$this->arrayActions = Index::ValidateUserSessionTime($_GET);
// ... else, if any COOKIE values are issued...
} elseif (!empty($_COOKIE)) {
$this->arrayActions = Index::ValidateUserSessionTime($_COOKIE);
} // end if
} // end function getGlobals
I've no doubt that there's room for improvement, or it maybe that others have done better.PHP Code:function ValidateUserSessionTime ($arrayActions) {
/**
When the User logs in, the session is assigned a UNIX date & time stamp. This stamp needs to be varified.
If the stamp is equal to or older than one hour, then the user is automatically logged out of whatever
application they happen to be at the time.
*/
// if the User is already logged in...
if (!empty($_SESSION['activetime'])) {
// if the User has been active for one hour or less...
if (($integerUNIXDateTImeStamp = mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y")) - $_SESSION['activetime']) < SESSION_TIMEOUT) {
// renew the account active date & time session
$_SESSION['activetime'] = mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y"));
// return an array of the global data
return $arrayActions;
// ... else, log them out...
} else {
// create the variables to automatically log the User out
$arrayActions['action'] = "logout";
return $arrayActions;
} // end if
// ... else, if the User has only just entered...
} else {
// return an array of the global data
return $arrayActions;
} // end if
} // end function ValidateUserSessionTime
All I hope for is that this offering might help someone.
Hope that helps?
A simple tutorial on using PHP to load html page templates, for beginners to understand how to seperate code from html.
http://www.sitepoint.com/forums/showthread.php?t=338850
Enjoy!
Now that register_globals is by default, off. The key to using ?p=blah designs is by inserting into the top of your webpage
If the variable is from a linkPHP Code:$blah=$_GET["blah"];
If the variable is from a formPHP Code:$blah=$_POST["blah"];
If the variable is from a server environmentPHP Code:$blah=$_SERVER["blah"];
:)
edit: noticed a brief discussion on the other page, however this gives clear cut information
Quote:
Originally Posted by HarryF
Just read through the thread... lots of useful information. Thanks for all the examples.
I didn't see a response to the assertion above, but felt like adding in some history for the young guys. 80 characters was the number of columns in the old punch cards used in programming back until the 70s. You couldn't physically have bits of code longer than 80 columns, and the practice of limiting code to 80 columns has stuck since. This is true especially since the width of screens wasn't conducive to horizontal scrolling until recently, and wrapping code was not and is still not elegant. It's kind of like that adage that states how the space shuttle's booster rocket size is based off the size of a horse's butt. More fun with punch cards can be found at http://en.wikipedia.org/wiki/Punch_card
That is unclear. $_SERVER is a reserved array that does not accept information, but it can be used to give information about certain things. It has a list of keywords which give the relative information.Quote:
Originally Posted by Durinthiam
$_POST, $_GET, $_REQUEST, $_COOKIE, $_SESSION (all of these require register globals turned off) are arrays that can receive information, but do not hold specific keywords.
The second example will actually show you what method was used to transfer information to that page ($_GET, $_POST etc).PHP Code:$nhostame = $_POST['name']; // can be modified accordingly
$hostname = $_SERVER['REQUEST_METHOD']; // can not be changed
Of course it "accepts" information. You can store whatever you like in $_SERVER.Quote:
Originally Posted by F4nat1c
They are also present when register_globals is enabled.Quote:
Originally Posted by F4nat1c
I can't believe anyone actually assigns variables just for the sake of it. If you have to change the content of the variable in two or more different ways, then it's useful. But in every other circumstance you should just continue to use the original variable name, if only because your code will be easier to comprehend.Quote:
Originally Posted by F4nat1c
I thought the same way, but when I started at this other job the head developer did that. Said it made it easier to read for others. So I did it and it helps me. Theres no real fact to go one way or another I guess. To me this seems cleaner:Quote:
Originally Posted by Icheb
Compared to:PHP Code:$that = trim($_POST['that'];
$sql = "SELECT * FROM table WHERE this='$that'";
But you save a line in the second example. Of course I would "clean" $_POST['that'] prior to putting it into any query.PHP Code:$sql = "SELECT * FROM table WHERE this = $_POST['that']";
Silly
The problem with this (for me) is that it makes the code a lot harder to read when you don't have the assignment right above the query code. If $_POST['that'] were directly included in the query, I'd know in an instant where it comes from. If the query is on line 5.000 and the assignment is taking place on line 250, you have no idea where that variable comes from and you have to search for it, in the worst case across multiple files.Quote:
Originally Posted by Sillysoft
So why not do it "right" right away? Especially if you have the assignment a few lines above the query I don't see how this benefits anyone, because you see right away what's what. (All this isn't limited to queries alone of course.) It just doesn't make sense to me. And if I don't know where $_POST['that'] comes from I most certainly won't know where $that comes from. To me, you are basically taking information AWAY from the code AND cluttering it up at the same time.
Again your way is based on personal preference. There is no fact on either side of the argument. I was merely stating why I assign variables that way, not that its right or wrong.Quote:
Originally Posted by Icheb
Silly
Then please tell me how it's easier to read for you, because that's something I can't understand. As I said, in my opinion it takes information away instead of adding them.
Unless you want your website hacked, you shouldn't be using the raw unvalidated $_POST variables anyway (especially in a query), and your argument kind of loses steam after that...
A simple snippet for adding random numbers to a file while uploading to prevent files over-writing
NOTE: This is a very basic way of doing things with no deep error checking involvedPHP Code://The name of the file passed from the form
$file_name = $_FILES['userfile']['name'];
//A random 6 digit number
$random_digit=rand(000000,999999);
//Put the random digit before the file name, using a decimal point to seperate the two variables
$new_file_name=$random_digit.$file_name;
//Sets the path (relative to the directory of your php script
//For instance, if you had public_html/quotescript/ and want the quotes in public_html/quotes/ then you would make $path ../quotes/ going back a step
//this example is if you want public_html/quotescript/quotes/
$path= "quotes/".$new_file_name;
//if there is a file
if($userfile !=none)
{ //open if statement
//Copy it to the path
if(copy($_FILES['userfile']['tmp_name'], $path))
{//open if statement
echo $new_file_name;
} //close if statement
else
{ //open else statement
echo "Error";
} // close else statement
} // close if statement
Another thing to remember is that if your passing variables across the url to a php file and you also need to get variables passed by a form make sure to use GET in your form action and NOT post :Quote:
Originally Posted by Durinthiam
;)Code:
$id=$_GET['id'];
$MyName = $_GET['MyName'];
blah...
<form method="GET" action="$PHP_SELF">
<input type="text" name="MyName">
</form>
blah...
POST is as good as GET and even better. There is no reason to use GET in a form instead of POST or not that I know of...
What I'm saying is if you have a script that passes both form values and values across the url you would have to use "get" in your form.
For instance if you have a link inside of index.php like so :
index.php?id=123
$_POST won't retrieve the value.
I know that, but why can't you use url values (GET) and POST values of a form at the same time? POST does not come in the url which has some advantages!
Yes there is!Quote:
Originally Posted by jcauweli
Example: a search script.
If the user were to use the POST method each time they went back to the original search results page the browser would require the form to be submitted again giving the 'page expired' warning or that nice little 'Resend you data' pop up. By using GET instead, the variabel is still in the url and so doesn;t need to be resent - it can be read instantly.
Also if you want to use both POST or GET have a look at REQUEST
Spike
Just make sure the string passed is not to big, else you need a post.
Don't use the function to backslash variables stated by Dr_LaRrY_PePpEr,
use the one on php.net
http://mx.php.net/manual/en/function...ape-string.php
PHP Code:<?php
// Quote variable to make safe
function quote_smart($value)
{
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote if not a number or a numeric string
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());
// Make a safe query
$query = sprintf("SELECT * FROM users WHERE user=%s AND password=%s",
quote_smart($_POST['username']),
quote_smart($_POST['password']));
mysql_query($query);
?>
Why?
look here
Making Function Names Shorter:
You can specify a variable with function name and do like this:
Making Variable Names Shorter:Code:$fetch = 'mysql_fetch_assoc';
$arr = $fetch($result); // Will do the same as mysql_fetch_assoc
Evaluate Variable Name:Code:$some_really_long_variable = 'some value';
$s = 'some_really_long_variable';
echo $$s;
// Notice 2 dollar signs! -- Outputs some value
Code:$y = 'hello';
${'data_' . $y} = 'test';
// $data_hello has been set to 'test'
echo $data_hello . ' ' . ${'data_' . $y};
// Outputs test test