Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
BioEnchanted
Aug 9, 2011

He plays for the dreamers that forgot how to dream, and the lovers that forgot how to love.
Thanks for your help. The mysql method was taught at university so it was the only one that I knew, and thanks for the tips on better practices. Also I'm doing this from scratch as a learning exercise, mostly involving being able to access databases with a website, as I didn't do well with it in university and I wanted to make sure that I could. I'm trying to keep in practice because I haven't done this for over year and didn't want to 'lose it'.

Currently having trouble with PDO though... we'll see ^_^

Adbot
ADBOT LOVES YOU

McGlockenshire
Dec 16, 2005

GOLLOCKS!
So, they're teaching PHP at a university. There's no excuse for that.

Your courses are poo poo, and your professor is blatantly incompetent.

In case you didn't know.

BioEnchanted
Aug 9, 2011

He plays for the dreamers that forgot how to dream, and the lovers that forgot how to love.
Yeah, the module was more general web dev on a Business IT course and we didn't have much time with php. By the way, if I want to encrypt my pass before putting it in the source code, and still have it work, what is the best way with just home software? and to be fair it was Sql Server, so not as bad a mysql :P just can't get server working at home and the host has a built in mysql database function. It's just to practice the basics of php and I can modify it for different types of databases when I start working with them.

mewse
May 2, 2006

BioEnchanted posted:

if I want to encrypt my pass before putting it in the source code, and still have it work

Nope

mewse
May 2, 2006

As a more serious answer, passwords are a serious subject because of security concerns but Computer Bros have been working with them since the first multi-user operating system was on the scene.

With a multi-user system, the only real way to protect passwords from other users is to use a one-way hash. When a person logs in, the operating system hashes the input and checks whether the hash matches the stored hash for that user.

There is really no way to "encrypt" a password so that you can use it in the same script to access the database. Anything you do will result in the attacker being able to decrypt it using the same script that you just wrote.

What most PHP developers do is store the database details in a separate file and make sure that that file has permissions set so that nobody can access it except the web server process and/or user (ie. the www-data user and/or group). This file is then included in all the other files for database access.

Welcome to the weird and dumb world of web security.

BioEnchanted
Aug 9, 2011

He plays for the dreamers that forgot how to dream, and the lovers that forgot how to love.
Ok, thanks. I'll look into the text file thing, that shouldn't be too hard. I'm grateful for everyone's help so far. I've mainly been trying to get into practice, as I'm hoping to find a job that uses my degree, and it'll help if I have a few examples of completed projects in each discipline so that I can prove to future employers (and myself :P) that I can handle it. In case anyone's curious the other disciplines are Python, which daniweb's been very helpful with and though unrelated to my degree, I am writing a videogame script (a friend from an amateur dramatic troupe has a friend in a third party dev studio, I want something to show before I get his details though).

EDIT: Something is weird now with my PHP - it's not showing up in the f12 window. This is the relevant code (with username and password blanked out this time:
code:
<html>
<head>
<title>My new blog/ information website! </title>
<link rel="stylesheet" type="text/css" href="default_game_site.css"/>
<?php

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = '**********';

/*** mysql password ***/
$password = '*********';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database';
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?>
</head>
But everything in the php tag doesn't even display. If you go to the site and hit f12 you should see. What could be causing this? And at this point should I start a new thread?

BioEnchanted fucked around with this message at 10:28 on Jan 7, 2012

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
That's supposed to happen. PHP is executed on the server, and only the output is sent to the browser.

What you should be seeing is either the "Connected to database" message, or the error message if the connection fails - but if you see the PHP itself, then something's not working right.

BioEnchanted
Aug 9, 2011

He plays for the dreamers that forgot how to dream, and the lovers that forgot how to love.
Yeah, it's working now. Thanks for all your help. If I need any more advice I'll possibly start a new thread, but I'll get the site working properly, then I can worry about optimizing when everything at least behaves. Next stop - getting it to read the username and password from the .txt :)

Sab669
Sep 24, 2009

If you can afford it, I personally really like these books for learning languages:
http://www.murach.com/books/phps/index.htm

I find the murach books just have really clean and easy to understand examples. The text itself is, of course, a bit dry but out of all the books I've used in school these are my favorite.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

BioEnchanted posted:

Yeah, it's working now. Thanks for all your help. If I need any more advice I'll possibly start a new thread, but I'll get the site working properly, then I can worry about optimizing when everything at least behaves. Next stop - getting it to read the username and password from the .txt :)

The best way to store your database credentials is as follows:

1. Make sure that they are in a file with a .php extension.
2. Make sure that file is stored outside of webroot.

The first of these means that in order for users to see the credentials, the server would have to be misconfigured in such a way that it outputs PHP code rather than executing it and outputting the result. The second means that in order for users to see the credentials, the server would have to be misconfigured in such a way that users can access files that are outside of webroot (which by definition they are not supposed to be able to do). Using both of these together means that two separate things have to go wrong in order for your database credentials to be displayed to visitors.

Reading configuration data for your application from a file outside of webroot is just a case of using the require() function. The only tricky thing could be getting the correct path to the file (if you are not familiar with what the path should look like on the host in question).

By the way, it is a matter of preference but I think that using constants is better than variables for database credentials, i.e.

code:
define('DB_USERNAME', 'nsf001');
define('DB_PASSWORD', 'smashthestate');
rather than

code:
$username = 'nsf001';
$password = 'smashthestate';

BioEnchanted
Aug 9, 2011

He plays for the dreamers that forgot how to dream, and the lovers that forgot how to love.
Just need clarification here - where do you mean when you say webroot? I've never heard that term before. Does it just mean store the file on my computer as opposed to uploading it to freeehosting.com?

Impotence
Nov 8, 2010
Lipstick Apathy

BioEnchanted posted:

Just need clarification here - where do you mean when you say webroot? I've never heard that term before. Does it just mean store the file on my computer as opposed to uploading it to freeehosting.com?

/home/yoursite/www/index.php
/home/yoursite/db.config.php

Webserver only serves out of www/

McGlockenshire
Dec 16, 2005

GOLLOCKS!
The folder might also be called "htdocs" or "public_html"

BioEnchanted
Aug 9, 2011

He plays for the dreamers that forgot how to dream, and the lovers that forgot how to love.
By the way, whenever I change the code to the website through freehosting it either doesn't change the site (and f12 brings up code from a few revisions ago) or it changes it exceedingly slowly. Any idea why the site doesn't change as I edit it as it makes troubleshooting a nightmare. I've tested the edits in the f12 bar (which doesn't save changes for security reasons) and it's worked fine but the edits don't stick when it's the php file.

Impotence
Nov 8, 2010
Lipstick Apathy
Free hosting is normally absolutely terrible trash, pay the $2/month to get an account on something that isn't intentionally crippled to death with half the functions disabled

BioEnchanted
Aug 9, 2011

He plays for the dreamers that forgot how to dream, and the lovers that forgot how to love.
Which services do you recommend that won't take forever to update between, well, updates :)

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

BioEnchanted posted:

Which services do you recommend that won't take forever to update between, well, updates :)

I have a lovely host called HostPapa, you just ftp your poo poo up there and f5, no wait. You can argue with the cPanel thing, but I prefer to go command-line. It dies horribly if you get popular, but for $5 a month that's what you get.

BioEnchanted
Aug 9, 2011

He plays for the dreamers that forgot how to dream, and the lovers that forgot how to love.
I'll look into that, thanks. I'll 'shop' around and see what hosts there are, and see which ones speak to me. Also, I've been updating the site visually, so while it is a little bland right now, at least it isn't ugly and it is still a work in progress (This isn't close to the final revision yet).

Impotence
Nov 8, 2010
Lipstick Apathy
General rule of thumb(s):
Never pay yearly. Never pay a setup fee (for shared). Never pay more than monthly.
If you see unlimited disk or bandwidth, run far away.

BioEnchanted
Aug 9, 2011

He plays for the dreamers that forgot how to dream, and the lovers that forgot how to love.
By the way, when I do migrate to a better ftp how would I move the database? would a simple export to sql file, import to whatever the new tool is work?

Also, will this code work? The intention is to put a single cell of data on each div (title, date, body). I'm using php to assign the variables and hoping they'll pass into a javascript function so I can assign each function to a div. Any easier ways to do this?
code:
<?php

$hostname = "localhost";
$username = "***************";
$password = "***************";
 
try {
    $dbh = new PDO("mysql:host=$hostname;dbname=gamepers_blog", $username, $password);
    echo "Connected to database"; // check for connection
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }

$sql = "SELECT Title FROM TABLE 'Blog Posts' WHERE Id = 0";
$blo = $dbh->prepare($sql);
$blo->execute();
$Title = $blo->fetchColumn(1);
echo $Title;


?>
<script type="text/javascript">

findTitle($Title){
    echo "<div class='post-head'>".$Title."</div>";
    }
</script>

BioEnchanted fucked around with this message at 15:23 on Jan 8, 2012

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

BioEnchanted posted:

Which services do you recommend that won't take forever to update between, well, updates :)

I use Lithium Hosting, they work fine for me. The basic package is like $10 a year or $1 a month if you use one of the goon discount codes (go look in SA-mart) and iirc you can get a month or so free as a trial period.

quote:

By the way, when I do migrate to a better ftp how would I move the database? would a simple export to sql file, import to whatever the new tool is work?

Yes. If you're not happy doing that kind of thing from the command line then you need a host that provides stuff like cPanel, phpMyAdmin etc. for you to use.

MrMoo
Sep 14, 2000

Is chunked encoding standard in PHP? I noticed many old examples explicitly encoding the chunks but with my PHP 5.3.2 and Lighty I only have to set the header and flush.
php:
<?
header ('Transfer-Encoding: chunked');
header ('Content-Type: application/json; charset=utf-8');

function json_chunk ($json) {
    echo json_encode ($json) . "\r\n";
    flush();
}

set_time_limit (60);
$max = 349997;
json_chunk (array('status' => 200, 'state' => 0, 'text' => 'request not initiated.'));
json_chunk (array('status' => 200, 'state' => 1, 'text' => 'server connection established.'));
json_chunk (array('status' => 200, 'state' => 2, 'text' => 'request received.'));
for ($i = 0; $i < $max; $i += 4096) {
    time_nanosleep (0, 10000000);
    json_chunk (array('status' => 200, 'state' => 3, 'loaded' => $i, 'total' => $max, 'tex
t' => 'processing request.'));
}
json_chunk (array('status' => 200, 'state' => 4, 'text' => 'request finished.'));
?>
Example: http://junko.hk/ck.php and JS wrapping: http://junko.hk/j.html

Seems to work in Chrome and Firefox, I'm sure MSIE will hate it.

MrMoo fucked around with this message at 00:41 on Jan 9, 2012

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

So I've got a STUPID loving breadcrumb class in oscommerce/php. It's really straightforward. I'm trying to get the last item in it. And I can't. Because it's loving STUPID.

Here's basically the whole class except for the exploder:
code:
class breadcrumb {
    var $_trail;

    function breadcrumb() {
      $this->reset();
    }

    function reset() {
      $this->_trail = array();
    }

    function add($title, $link = '') {
      $this->_trail[] = array('title' => $title, 'link' => $link);
    }
So being clever, I think 'ok, I'll just add a Last function inside the class definition':

code:
function last() {
    $last_title = '';
    $last_count = sizeof($this->_trail);
    
    $last_title .= $this->_trail[$last_count]['title'];
    
    return $last_title;
    }
And nothing happens. The actual breadcrumb FIVE LINES DOWN THE PAGE cheekily renders properly, but my Last picker gets bupkis.

SubG
Aug 19, 2004

It's a hard world for little things.

Hammerite posted:

The best way to store your database credentials is as follows:
1. Make sure that they are in a file with a .php extension.
2. Make sure that file is stored outside of webroot.
Rather than storing sensitive data in a .php file, I'd suggest using an extension that isn't used by any of the other files you're serving and then explicitly denying access to that extension in the server config. So if you put your credentials in an .ini file and you're using apache:
code:
<Files ~ "\.ini$">
     Deny from all
</Files>
And then also storing the file outside the webroot.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Scaramouche posted:

:words:

Your problem is that arrays are indexed starting from 0, rather than from 1.

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Actually I thought of that and tried (SizeOf(x))-1 (and -2, and -3) and it didn't make a difference (NULL). I know this is probably down to me not knowing some dumb syntax rule in php but it's maddening nonetheless. I've also tried end(), but that didn't work either.

I think it's because I'm assuming the array will have an index that's an integer, whereas here it says:
http://php.net/manual/en/language.types.array.php
"A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices."

You'll see in my previous post that the add is using strings as keys, so the problem isn't me getting the length necessarily, it's using that length as a numeric index/key and expecting anything to come out of it. I'm assuming the array exists as
code:
(0)('title1')('link1')
(1)('title2')('link2')
When it probably doesn't. Holy god what a mess:
http://www.php.net/manual/en/language.types.array.php#105496

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Here's some example code, which works as expected ($arr[sizeof($arr)] is NULL, $arr[sizeof($arr) - 1] is the last element): http://ideone.com/wa1Fs

Try using var_dump to print out the whole _trail structure - it might show up something that we're both missing.

KuruMonkey
Jul 23, 2004
end() doesn't give a poo poo about key types; if that's not working its time for a var dump. In fact:

php:
<?
function last() {
  throw new Exception("Trail: ".print_r($this->_trail));
}
?>
see what that gives you.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
code:
<?php

class breadcrumb {
    var $_trail;

    function breadcrumb() {
      $this->reset();
    }

    function reset() {
      $this->_trail = array();
    }

    function add($title, $link = '') {
      $this->_trail[] = array('title' => $title, 'link' => $link);
    }
    
    function last() {
    $last_title = '';
    $last_count = sizeof($this->_trail) - 1;
    
    $last_title .= $this->_trail[$last_count]['title'];
    
    return $last_title;
    }
}

$b = new breadcrumb();
$b->reset();
$b->add('apple', 'apple');
$b->add('ball', 'ball');
$b->add('cat', 'buttflap');

echo $b->last();

?>
This works for me. It outputs 'cat'.

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Ha, thanks guys. I should have started with the var_dumps in the first place. There were three problems:
1. Something was inserting empty array rows that I have no idea why it exists (I inherited this osCommerce install) so I'm trim()ing them now and hope it don't break.
2. There were edge cases where a page could have no breadcrumbs
3. $breadcrumb was being instantiated early enough for me to reference it, but not populated until a later point

Why I didn't go to var_dump first was because it seemed to be working (after all the bread crumbs were displaying) so I figured I could just hack something on. This is also the most php I've done in... ever, so I'm not too smart in those ways. Regardless, thanks a lot for your help guys, it got me thinkin on the right paths.

IT Guy
Jan 12, 2010

You people drink like you don't want to live!
I have a question regarding sanitizing user input.

When echoing HTML I escape using htmlspecialchars()
When entering data into a MySQL database, I escape with mysqli_real_escape_string()

What do I use or do I even have to use anything when just doing stuff in PHP. For example (using twitters API):

php:
<?

$count = (isset($_GET['count'])) ? $_GET['count'] : 20;
$parameters = array('include_entities' => 'true', 'include_rts' => 'true', 'count' => $count);
$tweets = $twitteroauth->get('statuses/home_timeline', $parameters);

?>
Do I need to sanitize this type of stuff? I realize Twitter is going to sanitize my query anyway but does it affect me at all?

Another example:

php:
<?

$multiplier = (isset($_GET['multiplier '])) ? $_GET['multiplier '] : 2;

$calculation = 10 * $multiplier;

?>
Ignore the fact that I'm not validating the data type on the above example.

I'm mostly worried about XSS attacks. I always escape when echoing HTML or entering data into a database.

Impotence
Nov 8, 2010
Lipstick Apathy
Use pdo/bindparam, dont try to sanitise by yourself for sql - eventually you might forget one, too

$count = (isset($_GET['count'])) ? $_GET['count'] : 20;

Maybe force $count to be (int)?

Impotence fucked around with this message at 03:58 on Jan 12, 2012

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
What you do to sanitise data generally depends almost entirely on what you will use that data for (database, output in HTML, use in filesystem, etc.). But there are one or two things you will probably always do to make sure received data is "sensible" (or coerce it to sensible values).

Firstly, make sure it has the correct type (e.g. if it is supposed to be a string, make sure it is indeed a string and not an array; if it is supposed to be an integer, coerce it to integer using intval()). Secondly, make sure the value is "sensible" for what it's meant to be used for. If it is meant to be a nonnegative integer, check that it is indeed nonnegative, and either set it to a default value or error out if it is negative. If you have a maximum length of string in mind, check the string isn't too long. If there are things you don't want to appear in that string, obviously check for them.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

IT Guy posted:

Do I need to sanitize this type of stuff? I realize Twitter is going to sanitize my query anyway but does it affect me at all?

I'd say yes. Sanitize everything. You don't need to have one way of doing things in this spot, and another way of doing things in some other spot. Do it all the exact same way.

Also, use PDO. Don't bother with that mysql_real_escape_string() crap or the mysql_* and mysqli_* functions.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Biowarfare posted:

Use pdo/bindparam, dont try to sanitise by yourself for sql - eventually you might forget one, too

$count = (isset($_GET['count'])) ? $_GET['count'] : 20;

Maybe force $count to be (int)?

instead of all that
code:
$count = (isset($_GET['count'])) ? $_GET['count'] : 20;
stuff that can start to accumulate and make your code ugly (ha, PHP) I make a function, like

php:
<?
function gv($key, $default=null){
  if(isset($_GET[$key])){
    return $_GET['key'];
  }
  return $default;
}
?>
so you can just do
code:
$count = gv('count', 20);
. You could add a validator too if you want:

php:
<?
function gv($key, $default=null, $validator=false){
  if(isset($_GET[$key])){
    return validate($_GET['key'], $validator, $default);
  }
  return $default;
}

function validate($val, $kind, $default){
  switch($kind){
    case 'numeric': return is_numeric($val) ? $val : $default;
    case 'pants' : return strpos('pants', $val)===false ? $default : $val;
    default: return $val;
  }
}
?>

IT Guy
Jan 12, 2010

You people drink like you don't want to live!
So basically I only have to escape or sanitize when I want to actually do something with the value? I haven't read too much on XSS but I typically don't have to sanitize until I actually output the value somewhere whether it be a database or HTML, etc?

I was just scared about doing this:

php:
<?
$var = $_GET['value'];
?>
So the above is safe until I actually use the variable in something, correct?

Sorry for my paranoia but until recently I've just been doing web development on internal apps for a small number of users and no one really gave a poo poo about security. Recently I've been tasked with public facing sites though so I need to be thorough. We've had sites taken down via XSS before (not my work), specifically c99.php.

IT Guy fucked around with this message at 14:21 on Jan 12, 2012

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

IT Guy posted:

So basically I only have to escape or sanitize when I want to actually do something with the value? I haven't read too much on XSS but I typically don't have to sanitize until I actually output the value somewhere whether it be a database or HTML, etc?

I was just scared about doing this:

php:
<?
$var = $_GET['value'];
?>
So the above is safe until I actually use the variable in something, correct?

Yes. Are you worried that the GET variable could be somehow executable and that the assignment operation could have side effects? That isn't a thing.

To talk of sanitising a variable doesn't really make sense without some context as to for what purpose you want to sanitise it (for a database, for HTML, etc.) But as I was saying it may well make sense to check that a submitted variable has a "sensible" value (whatever that means in a specific case).

Edit: I mean to say that there is nothing intrinsically unsafe about that line of code, however it may obscure the fact that $var is unfiltered request data, which might be seen as bad style.

Edit 2: Of course, if $_GET['value'] isn't defined, then that line of code will trigger a notice, and $var will be null, so it does have an unwelcome side effect if you want to prevent notices (which is a good idea).

Hammerite fucked around with this message at 15:12 on Jan 12, 2012

IT Guy
Jan 12, 2010

You people drink like you don't want to live!

Hammerite posted:

Yes. Are you worried that the GET variable could be somehow executable and that the assignment operation could have side effects? That isn't a thing.

This is exactly what I was concerned about. That answers my question actually.

ryo
Jan 15, 2003
Can someone suggest some frameworks to try out that have unit testing and are "DRY"? In particular I only want to specify my models in one place, like in Django or Rails. I'm using CodeIgniter for a project at the moment and am seriously considering learning another framework, as having to update apps in CodeIgniter is just not much fun.

Adbot
ADBOT LOVES YOU

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

FeloniousDrunk posted:

I have a lovely host called HostPapa, you just ftp your poo poo up there and f5, no wait. You can argue with the cPanel thing, but I prefer to go command-line. It dies horribly if you get popular, but for $5 a month that's what you get.

Is that Tech 9 in your avatar?

Also you can actually get some pretty good hosting for :5bucks: a month if you look around. If you use like a Litespeed, Nginx+Apache, or (maybe) Apache+Varnish host, you probably won't have problems with your website going down like ever, unless the concurrent connections just get crazy on a highly unoptimized website. Or if you run out of bandwidth.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply