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
Juanito
Jan 20, 2004

I wasn't paying attention
to what you just said.

Can you repeat yourself
in a more interesting way?
Hell Gem
My free guestbook site has a very simple captcha on it, and it gets hammered pretty hard by spammers. Any suggestions for a good captcha that can block Xrumer?

This has a nice list, http://www.ajaxline.com/best-free-captcha-solutions

http://www.phpcaptcha.org/ looks pretty good.. but I get the impression that Xrumer has its way through all of these.

Any suggestions?

Adbot
ADBOT LOVES YOU

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Juanito posted:

Any suggestions?

Make it a custom question instead. My favorite was one that had "Enter the word four" as it's CAPTCHA. The site owner said it worked great.

Juanito
Jan 20, 2004

I wasn't paying attention
to what you just said.

Can you repeat yourself
in a more interesting way?
Hell Gem
I've thought of that, I guess my main issue is that I don't want people who don't speak English to have any problems. But it does seem like the best solution.

mpeg4v3
Apr 8, 2004
that lurker in the corner
Okay, this might be kind of long. It's more of a conceptual question than just pure coding. Sorry if this is the wrong place for it.

First off, I'm not a programmer. I don't have the mind for it. I get by pretty well with PHP and what not, but it isn't what I'm best at. I just recently started delving into OOP, and I'm still trying to get my head around a lot of concepts.

So anyway, as part of a project for a web development class I had last year, I developed a scheduling application for my work. Since implementing it way back when, I've just been adding on to it and adding on to it, never properly, with code reused all over the place and no consistency or anything. Pretty much the entire project could go in the "worst code you've seen" thread. No classes or object oriented programming, big colossal files that are a pain to sort through and not reusable at all, etc. But I recognize it's terrible, and I want to redesign it properly.

My goal with redesigning it is to build everything around a completely modular web site. Basically, I want to just have the basic core web site structure, (namely Users, Groups, Menus, Pages, and Modules), and then have all of the content generated from modules that are added to the system. So, for example, if I add the Calendar module to the site, the menu will automatically contain a link to the Calendar, and clicking on that link will load the Calendar in the content section of the web site. I've pretty much figured out how to do this.

However, I also want modules to be able to add content to other modules. This is part of where I'm currently stuck. I'm not really sure how to have one module add content or features to another module. Let's take the Calendar again for example. Say the Calendar is loaded, displaying all of the Shifts people are working that week. Now let's say I add in a module that allows people to switch their shifts with someone else, and I want that option to display on the shift information in the Calendar. How would I go about getting it to display?

The way I've thought of so far is to have some sort of Hooks system. Basically, whoever wrote the module would be responsible for including locations in their code where they get all of the external functions that are hooking in to that bit of code. So, in the example, in the individual shift section, something like:
$hook->getHooks('shiftdisplay');
This would go through, get all modules that have hooks to the currently displayed module, then, for each of those modules, display any content for the 'shiftdisplay' section of their code.

The thing is, this seems so clunky to me; it feels like I'm not going the proper way about it at all. I've tried to read up on the observer pattern concept and all of that, but I just can't get my head around it. Nor really interfaces and what not in terms of PHP classes.

The other issue I'm trying to wrap my head around is Access Rights and User Groups. Let's say there's two Users, John Doe, a worker, and Jane Doe, a manager. John Doe is a member of the Worker group, while Jane Doe is a member of both the Worker and Manager groups. The Worker group can view the Calendar and the shifts being worked. The Manager group can do all of the same things the Worker group can do, but also add/edit/delete shifts.

The simplest idea I could come up with is to have a Functions table, that contains the name of every function for each module. So, the Calendar module would have the View Shifts function, the Add Shift function, the Delete shift function, etc. etc. Then there'd be a GroupFunctions table, where each group would have what functions it can do. For example, the Group Functions table would have something like the following (for easier readability):
View Shifts - Workers
View Shifts - Managers
Add Shifts - Managers
Edit Shifts - Managers
Delete Shifts - Managers
Then, in the Calendar module, it would do something like:
$access = new AccessRights();
if ($access->check('View Shifts') == true) { /*Shift Information*/ } else { /*Error*/ }
if ($access->check('Add Shifts') == true) { /*Add Shift Code*/} else { /*Show Nothing*/ }
... and so on. Basically, whoever wrote the module would be responsible for running access checks for each function in the module, and then displaying what occurs if the person does or does not have access. The Check function in the Access Rights class would just see if the User is a member of a Group that can use that Function.

But this doesn't really feel right to me either. It seems too simple to me and I have a feeling I'm not thinking through all of the scenarios properly. Like it won't work for modules and hooks, for example.

I know I can't be the only newbie-ish programmer facing these issues, so I was wondering if anyone could help point me in the right direction for how I could go about tackling this, or if I'm on the right track already.

kanis
Nov 18, 2004
salad shooter

mpeg4v3 posted:

Okay, this might be kind of long. It's more of a conceptual question than just pure coding. Sorry if this is the wrong place for it.

First off, I'm not a programmer. I don't have the mind for it. I get by pretty well with PHP and what not, but it isn't what I'm best at. I just recently started delving into OOP, and I'm still trying to get my head around a lot of concepts.

So anyway, as part of a project for a web development class I had last year, I developed a scheduling application for my work. Since implementing it way back when, I've just been adding on to it and adding on to it, never properly, with code reused all over the place and no consistency or anything. Pretty much the entire project could go in the "worst code you've seen" thread. No classes or object oriented programming, big colossal files that are a pain to sort through and not reusable at all, etc. But I recognize it's terrible, and I want to redesign it properly.

My goal with redesigning it is to build everything around a completely modular web site. Basically, I want to just have the basic core web site structure, (namely Users, Groups, Menus, Pages, and Modules), and then have all of the content generated from modules that are added to the system. So, for example, if I add the Calendar module to the site, the menu will automatically contain a link to the Calendar, and clicking on that link will load the Calendar in the content section of the web site. I've pretty much figured out how to do this.

However, I also want modules to be able to add content to other modules. This is part of where I'm currently stuck. I'm not really sure how to have one module add content or features to another module. Let's take the Calendar again for example. Say the Calendar is loaded, displaying all of the Shifts people are working that week. Now let's say I add in a module that allows people to switch their shifts with someone else, and I want that option to display on the shift information in the Calendar. How would I go about getting it to display?

The way I've thought of so far is to have some sort of Hooks system. Basically, whoever wrote the module would be responsible for including locations in their code where they get all of the external functions that are hooking in to that bit of code. So, in the example, in the individual shift section, something like:
$hook->getHooks('shiftdisplay');
This would go through, get all modules that have hooks to the currently displayed module, then, for each of those modules, display any content for the 'shiftdisplay' section of their code.

The thing is, this seems so clunky to me; it feels like I'm not going the proper way about it at all. I've tried to read up on the observer pattern concept and all of that, but I just can't get my head around it. Nor really interfaces and what not in terms of PHP classes.

The other issue I'm trying to wrap my head around is Access Rights and User Groups. Let's say there's two Users, John Doe, a worker, and Jane Doe, a manager. John Doe is a member of the Worker group, while Jane Doe is a member of both the Worker and Manager groups. The Worker group can view the Calendar and the shifts being worked. The Manager group can do all of the same things the Worker group can do, but also add/edit/delete shifts.

The simplest idea I could come up with is to have a Functions table, that contains the name of every function for each module. So, the Calendar module would have the View Shifts function, the Add Shift function, the Delete shift function, etc. etc. Then there'd be a GroupFunctions table, where each group would have what functions it can do. For example, the Group Functions table would have something like the following (for easier readability):
View Shifts - Workers
View Shifts - Managers
Add Shifts - Managers
Edit Shifts - Managers
Delete Shifts - Managers
Then, in the Calendar module, it would do something like:
$access = new AccessRights();
if ($access->check('View Shifts') == true) { /*Shift Information*/ } else { /*Error*/ }
if ($access->check('Add Shifts') == true) { /*Add Shift Code*/} else { /*Show Nothing*/ }
... and so on. Basically, whoever wrote the module would be responsible for running access checks for each function in the module, and then displaying what occurs if the person does or does not have access. The Check function in the Access Rights class would just see if the User is a member of a Group that can use that Function.

But this doesn't really feel right to me either. It seems too simple to me and I have a feeling I'm not thinking through all of the scenarios properly. Like it won't work for modules and hooks, for example.

I know I can't be the only newbie-ish programmer facing these issues, so I was wondering if anyone could help point me in the right direction for how I could go about tackling this, or if I'm on the right track already.

Looking through this, many of these issues are addressed by existing frameworks. You might want to look into implementing Drupal given its modularity, or look into a rapid application development framework like CodeIgniter or Kohana. CodeIgniter doesn't take too long to pick up, and it seems that it's fairly easy to learn across the gamut in terms of experience. That said, Kohana is built on CodeIgniter (or rather forked from it) and actually comes with an auth module with built-in roles that you can enable and customize. The other solution I mentioned, Drupal, comes with a lot of these features you wanted (modularity, interoperability, roles and permissions, hooks)... but there's a learning curve as it comes to having to learn Drupal's infrastructure and API to get any customization done.

Anyway, this is mostly a "don't reinvent the wheel if you don't have to" post; however, it does come down to the ability to devote time to learn the framework, and see if the benefits outweigh the overhead for doing that.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

mpeg4v3 posted:

Okay, this might be kind of long. It's more of a conceptual question than just pure coding. Sorry if this is the wrong place for it.

:words:

I know I can't be the only newbie-ish programmer facing these issues, so I was wondering if anyone could help point me in the right direction for how I could go about tackling this, or if I'm on the right track already.

Over the weekend, I shall write a reply to this... it's an involved question, so don't let a dearth of quick replies make you think nobody cared. kanis' reply is a great start. Take a look at Code Igniter and Kohana, paying special attention to the MVC design pattern behind them. That's very often the key to these "ahhhh! Big stuff w/ lots of related parts... ahhhh!" problems.

kanis
Nov 18, 2004
salad shooter

Lumpy posted:

Over the weekend, I shall write a reply to this... it's an involved question, so don't let a dearth of quick replies make you think nobody cared. kanis' reply is a great start. Take a look at Code Igniter and Kohana, paying special attention to the MVC design pattern behind them. That's very often the key to these "ahhhh! Big stuff w/ lots of related parts... ahhhh!" problems.

Yeah, especially when time/budget comes into play. We use CI a lot at work, just now getting into Kohana now that it seems to have ripened a lot since Blue Flame... though I'm still not completely happy with Kohana's documentation--though it's gotten a lot better.

MVC is a great design pattern, and what's even better with CI or Kohana is that if you _need_ to break or circumvent that pattern (for time or overhead reasons), you can do that fairly easily... it's a lot nicer than having to succumb to a strict framework's way of doing things.

mpeg4v3
Apr 8, 2004
that lurker in the corner

kanis posted:

Anyway, this is mostly a "don't reinvent the wheel if you don't have to" post; however, it does come down to the ability to devote time to learn the framework, and see if the benefits outweigh the overhead for doing that.

Lumpy posted:

Over the weekend, I shall write a reply to this... it's an involved question, so don't let a dearth of quick replies make you think nobody cared. kanis' reply is a great start. Take a look at Code Igniter and Kohana, paying special attention to the MVC design pattern behind them. That's very often the key to these "ahhhh! Big stuff w/ lots of related parts... ahhhh!" problems.

Thanks to both of you for the replies, I was beginning to worry my question didn't fit the whole "don't need their own thread" bit. I'll look into the frameworks that you both mentioned. I've been kind of lost as to where to start with frameworks and PHP programming in general, so I am very thankful for the suggestions.

Lumpy, I'll definitely look forward to your reply, too. I'm still very new to everything PHP, and even though I've moved beyond the "let's make gigantic PHP files with copy and pasted code everywhere whenever I need to do something and have giant if/elseif trees!" stage to the "hey, these class things are pretty cool" stage, I really haven't done it with any structure so I know I'm lacking on a lot of core concepts.

The thing is, even if I find a good framework that easily does what I need, a part of me wants to do it on my own, anyway, just so I can learn how to do it. I figure it'll be pretty valuable knowledge to have and to learn, even if I am just reinventing the wheel, since I'm getting the feeling I'm probably going to end up having to do a lot more web app development in the future for work.

Elected by Dogs
Apr 20, 2006

Juanito posted:

My free guestbook site has a very simple captcha on it, and it gets hammered pretty hard by spammers. Any suggestions for a good captcha that can block Xrumer?

This has a nice list, http://www.ajaxline.com/best-free-captcha-solutions

http://www.phpcaptcha.org/ looks pretty good.. but I get the impression that Xrumer has its way through all of these.

Any suggestions?
Possibly try combining reCAPTCHA (Javascript would probably mess with spammers a bit) and an empty field that's hidden with CSS and should always return a certain value.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

mpeg4v3 posted:

Thanks to both of you for the replies, I was beginning to worry my question didn't fit the whole "don't need their own thread" bit. I'll look into the frameworks that you both mentioned. I've been kind of lost as to where to start with frameworks and PHP programming in general, so I am very thankful for the suggestions.

Lumpy, I'll definitely look forward to your reply, too. I'm still very new to everything PHP, and even though I've moved beyond the "let's make gigantic PHP files with copy and pasted code everywhere whenever I need to do something and have giant if/elseif trees!" stage to the "hey, these class things are pretty cool" stage, I really haven't done it with any structure so I know I'm lacking on a lot of core concepts.

The thing is, even if I find a good framework that easily does what I need, a part of me wants to do it on my own, anyway, just so I can learn how to do it. I figure it'll be pretty valuable knowledge to have and to learn, even if I am just reinventing the wheel, since I'm getting the feeling I'm probably going to end up having to do a lot more web app development in the future for work.

A couple things I would like to suggest.

1. Although OOP is good, you can easily over-complicate things by trying to apply patterns everywhere or creating too many interdependencies. Try to make your classes as independent as possible and keep them separate. Don't overuse classes either, just because they exist doesn't mean you have to use them.

2. As an alternative to creating instances of objects within your classes (which causes dependencies), and also to avoid using globals or singletons, start using injection wherever possible. Say you have a DB object that some class needs access to, instead of doing this

php:
<?
class Address()
{
  function FindAddress($id)
  {
     $db = new DataBaseClass();
     ...
  }
}
?>
... use injection instead ...

php:
<?
class Address()
{
   private $db;
   
   public __construct(IDataBase $db)
   {
      $this->db = $db;
   }
   
   public FindAddress($id)
   {
      $this->db->DoStuff();
   }
}
?>
The difference between these classes is somewhat subtle, but its actually a very big and important difference. The first class is dependent on a specific class called DataBaseClass making it a little inflexible. You cannot reuse Address unless you deploy it with your DataBaseClass, and if your DataBaseClass object has dependencies you cannot deploy it without other stuff as well, etc. So basically you shot yourself in the foot.

In the second instance its dependent upon an interface only. You can replace $db with whatever you want as long as it implements that interface. So you would be able to create a new IDataBase class that writes to SQL server, then one for mysql, and even have one that writes to xml and you would not have to modify the Address class. This is also important for unit testing, you can replace $db with a mock object.

3. Start using unit testing if you haven't already. Unit tests not only helps you write and maintain bug free code, but forces you to maintain classes that are more independent.

4. Separate your logic from your presentation. Imagine that you have to take away the web browser, and instead you have to satisfy the requirements of your program using only a script or just the command line. Can you do this with your code now? For instance if I told you to type in some code in a PHP file would you be able to add a shift to a calendar without any interaction? If not, how you should have it setup is a well tested class that adds and removes shifts with methods like getShifts($userId), findShift($id), updateShift($id, $shiftData), removeShift($id) etc.

Then you would have a presentation layer (another class or set of classes) that showed buttons and crap that people could click on and it would make use of your shift manipulation class with the methods above.

The end result is that your program should still be able to do everything it is supposed to do even if you completely removed the presentation layer.

Goodpart
Jan 9, 2004

quarter circle forward punch
quarter circle forward punch
quarter circle forward punch
rip
edit: I actually fixed something! Incredible! Nothing to see here now

Goodpart fucked around with this message at 17:48 on Mar 13, 2010

apekillape
Jan 23, 2009

by Peatpot
I usually type all my php code out in notepad, because I don't write anything too complicated and I don't really know the difference. What is a good... syntax... knowing... typing... thingie?

I'm sorry, I legitimately have no idea what they're called. The programs that you can write your code in and it shows you when you've missed a bracket or something.

thedaian
Dec 11, 2005

Blistering idiots.

apekillape posted:

I usually type all my php code out in notepad, because I don't write anything too complicated and I don't really know the difference. What is a good... syntax... knowing... typing... thingie?

I'm sorry, I legitimately have no idea what they're called. The programs that you can write your code in and it shows you when you've missed a bracket or something.

They're often called IDEs.

Notepad++ is a nice improvement over the default notepad, it has syntax highlighting and fairly robust search/replace dialog, plus a lot of other nice tools.

Eclipse has support for PHP development, I believe, and it has a lot of nice features, including autocompletition type stuff.

I'm sure other people will recommend other tools.

Rick
Feb 23, 2004
When I was 17, my father was so stupid, I didn't want to be seen with him in public. When I was 24, I was amazed at how much the old man had learned in just 7 years.
After installing apache, mysql, php and making sure everything was running with php, I decided I wanted to go ahead and have a simpler path to mysql. So I uninstalled mysql (from C:\abillionpaths\), reinstalled it at C:\mysql .

I can't quite seem to get php to recognize the move. In phpinfo() it's still displaying the old path. I can't find anything in either httpd conf for apache or php.ini to update this change. Do I have to uninstall and move it back to the default location?

Aturaten
Mar 23, 2008

by elpintogrande

apekillape posted:

I usually type all my php code out in notepad, because I don't write anything too complicated and I don't really know the difference. What is a good... syntax... knowing... typing... thingie?

I'm sorry, I legitimately have no idea what they're called. The programs that you can write your code in and it shows you when you've missed a bracket or something.

Notepad++ is my favourite. Use the font "Consolas" for all developing, and I'm partial to the Obsidian theme.

MrMartyn
Mar 6, 2007

I'm actually quite embarrassed to ask this but since I can't seem to solve it myself I'll go ahead! I'm trying to create a shopping cart and my problem lies in the line:

code:
echo '<td> <a href="cart.php?action=add&id="'.$row['songid'].">Add to cart</a></td>";
for some reason it won't pick up the songid to add into the link. Can anyone spot what I've missed? The query returns all of the values I required, including the songid. The rest of the segment of code is posted below too.

code:

$result = mysql_query("SELECT chart.position, song.title, artist.name, song.album, 
song.genre, song.price, song.songid 
FROM chart, song, artist WHERE chart.songid = song.songid AND song.artistid = artist.artistid");
		
		
		 echo "<table class='style2'>
			<tr>
				<th>Position</th>
				<th>Title</th>
				<th>Album</th>
				<th>Genre</th>
				<th>Price</th>
				</tr>";

			while($row = mysql_fetch_array($result))
			{
			echo "<tr>";
			echo "<td>" . $row['position'] . "</td>";
			echo "<td>" . $row['title'] . "</td>";
			echo "<td>" . $row['album'] . "</td>";
			echo "<td>" . $row['genre'] . "</td>";
			echo "<td>" . $row['price'] . "</td>";
			//echo "<td>" . $row['songid'] . "</td>";
			echo '<td> <a href="cart.php?action=add&id="'.$row['songid'].">Add to cart</a></td>";
			
			echo "</tr>";
			}
			echo "</table>";

gwar3k1
Jan 10, 2005

Someday soon

MrMartyn posted:

I'm actually quite embarrassed to ask this but since I can't seem to solve it myself I'll go ahead! I'm trying to create a shopping cart and my problem lies in the line:

code:
echo '<td> <a href="cart.php?action=add&id="'.$row['songid'].">Add to cart</a></td>";
[/code]

Your quoting is messed up:

code:
echo "<td> <a href='cart.php?action=add&id='".$row['songid'].">Add to cart</a></td>";

Hammerite
Mar 9, 2007

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

MrMartyn posted:

code:
echo '<td> <a href="cart.php?action=add&id="'.$row['songid'].">Add to cart</a></td>";
This code will result in output that looks something like
code:
<td> <a href="cart.php?action=add&id="94>Add to cart</a></td>
You have closed the double quotation marks prematurely. Change it to the following:
code:
echo '<td> <a href="cart.php?action=add&id='.$row['songid'].'">Add to cart</a></td>';

Small White Dragon
Nov 23, 2007

No relation.
edit: repeatedly beaten with my slow connection

Small White Dragon fucked around with this message at 23:34 on Mar 14, 2010

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

apekillape posted:

I usually type all my php code out in notepad, because I don't write anything too complicated and I don't really know the difference. What is a good... syntax... knowing... typing... thingie?

I'm sorry, I legitimately have no idea what they're called. The programs that you can write your code in and it shows you when you've missed a bracket or something.

Seconding the consolas font...

Another option is Netbeans which is actually pretty good and free. I like it a lot better than eclipse.

Zend Studio used to be my favorite, until they switched to an eclipse plugin, then it went to poo poo... =(

apekillape
Jan 23, 2009

by Peatpot

Begby posted:

Seconding the consolas font...

Another option is Netbeans which is actually pretty good and free. I like it a lot better than eclipse.

Zend Studio used to be my favorite, until they switched to an eclipse plugin, then it went to poo poo... =(

I'm rockin' the Notepad++ with Aturaten's settings the now, it's not too shabby. Definitely saves me time hunting down brackets and line numbers, haha.

Thanks a lot guys.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Begby posted:

Seconding the consolas font...



When you guys are ready for the best:

http://www.levien.com/type/myfonts/inconsolata.html

:colbert:

It's actually "heavily inspired" by Consolas, but I like it even better.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Begby posted:

Seconding the consolas font...

Another option is Netbeans which is actually pretty good and free. I like it a lot better than eclipse.

Thirding and seconding :)

Inconsolata always looks fuzzy no matter what I do to it

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:
Just to get this out of the way, I am an infra-gifted street-coder who has only held onto his job because of his looks. I am in the process of writing a CMS. Yes, this is a dumb thing to do, reinventing the reinvented wheel etc etc, but really this problem domain is pretty underrepresented out there. Anyhow, my recurring issue is that I often code myself into a corner where I'm, say, writing PHP that generates javascript that outputs HTML. Something like:
php:
<?
$html='<a href="foo">foo\'s link</a>';
echo('<script type="text/javascript">');
if($some_condition){
echo('$("#foo").html("<?php echo $html ?>");'); // of course this fails later on
}else{
echo('$("#bar")
.html("<?php echo magicalescapingfunction($html?>"
.'<scr'.'ipt type=javascript">alert(\'BAR\');</scr'.'ipt>");'); // ditto, probably
}
echo('</script>');
?>
Hopefully that illustrates the problem -- escaping through multiple levels/languages. Currently my issue is about using PHP to return HTML wrapped in JSON to client javascript that replaces an element on the page (and jQuery is rejecting it as invalid JSON). I'd be really interested in hearing some approaches. Is there maybe something out there that does for javascript what PDO does for SQL?

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH

FeloniousDrunk posted:

Just to get this out of the way, I am an infra-gifted street-coder who has only held onto his job because of his looks. I am in the process of writing a CMS. Yes, this is a dumb thing to do, reinventing the reinvented wheel etc etc, but really this problem domain is pretty underrepresented out there. Anyhow, my recurring issue is that I often code myself into a corner where I'm, say, writing PHP that generates javascript that outputs HTML. Something like:
php:
<?
$html='<a href="foo">foo\'s link</a>';
echo('<script type="text/javascript">');
if($some_condition){
echo('$("#foo").html("<?php echo $html ?>");'); // of course this fails later on
}else{
echo('$("#bar")
.html("<?php echo magicalescapingfunction($html?>"
.'<scr'.'ipt type=javascript">alert(\'BAR\');</scr'.'ipt>");'); // ditto, probably
}
echo('</script>');
?>
Hopefully that illustrates the problem -- escaping through multiple levels/languages. Currently my issue is about using PHP to return HTML wrapped in JSON to client javascript that replaces an element on the page (and jQuery is rejecting it as invalid JSON). I'd be really interested in hearing some approaches. Is there maybe something out there that does for javascript what PDO does for SQL?
:psyduck:

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:

supster posted:

:psyduck:

I know. Help.

Tad Naff fucked around with this message at 05:30 on Mar 17, 2010

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

FeloniousDrunk posted:

I know. Help.

Don't mix php and javascript. Put all your javascript in external files. Use $(document).ready() to javascriptify your html.

DoctorScurvy
Nov 11, 2005
More of a passing curiosity, really
ok FeloniousDrunk, why are you using <?php inside the php function? It looks like you're writing php code to generate javascript that prints the php code for writing html. I don't know enough about jquery or javascript in general but just looking at your php code, this seems to achieve the same result:
php:
<?
$html="<a href='foo'>foo's link</a>";
echo "<script type='text/javascript'>\n";

if($some_condition){
  echo "$('#bar').html('".$html."');\n";
} else {
  echo "$('#foo').html('".$html."');\n";
  echo "alert('BAR');\n";
}
echo "</script>";
?>
ed - swapped some apostrophes around, I think javascript prefers ' to "

DoctorScurvy fucked around with this message at 07:22 on Mar 17, 2010

KuruMonkey
Jul 23, 2004
what fletcher said, plus "use templates".

even if you only use something as naive as this:

php:
<?
    function template($templater_template, $templater_arguments, $templater_return_output=FALSE)
    {
        // if return_output, capture OB
        if($templater_return_output === TRUE)
            ob_start();
        
        extract($templater_arguments);
        
        // might need to do more cunning stuff with your path for a full system
        require($templater_template.".php"); // require means things blow up if not found
        
        // if return output, return OB we captured
        if($templater_return_output === TRUE)
            return ob_get_clean();
    }
?>
still; Use templates. Use MVC (the sw-design paradigm, not any particular framework). Separate your decision making from your output formatting. Don't write code that writes code - its a clear indication of bad (or no) design decisions. (HTML is not code, of course)

If you must drive your Javascript from PHP, write parameterised Javascript modules and feed it JSON data created from PHP.

isagoon
Aug 31, 2009

by Peatpot
On the whole templates topic...

I rewrote some of my block processing code, and I have this. IS there any way to catching parse errors in the included code? I think I have seen Magento do it.

For now, most of this is just testing, which is why a lot of it is incomplete.

php:
<?php
class BlockProcessor extends CCMS2
{
    protected $errors = array();

    public function __construct($base)
    {
        $this->base =& $base;
    }
    
    public function run($file)
    {
        $count 0;
        $file str_replace('../'''$file$count);
        
        if ($count>0)
            $this->logEvent('Cannot include blocks from out of the block directory: '.$file1);
    
        if (!file_exists(APP_ROOT.'/Blocks/'.$file))
        {
            $this->logEvent('Cannot include block: '.$file2);
            return '';
        }
        
        $this->cdir dirname(APP_ROOT.'/Blocks/'.$file);
        
        set_error_handler(array($this'errorRun'), error_reporting());
        ob_start();
        
        include APP_ROOT.'/Blocks/'.$file;
        $phprun ob_get_contents();
        
        ob_end_clean();
        restore_error_handler();
        
        if (count($this->errors)>0)
            $this->logEvent(print_r($this->errorstrue), 2);
        
        
        $this->cdir '';
        
        return $phprun;
    }
    
    protected function errorRun($errno$errstr$errfile$errline$errcontext)
    {
        $errorTypes = Array(
            E_ERROR              => 'Fatal Error',
            E_WARNING            => 'Warning',
            E_PARSE              => 'Parse Error',
            E_NOTICE             => 'Notice',
            E_CORE_ERROR         => 'Fatal Core Error',
            E_CORE_WARNING       => 'Core Warning',
            E_COMPILE_ERROR      => 'Compilation Error',
            E_COMPILE_WARNING    => 'Compilation Warning',
            E_USER_ERROR         => 'Triggered Error',
            E_USER_WARNING       => 'Triggered Warning',
            E_USER_NOTICE        => 'Triggered Notice',
            E_STRICT             => 'Deprecation Notice',
            E_RECOVERABLE_ERROR  => 'Catchable Fatal Error',
        );
        
        $ret = array(
            'number'             => $errno,
            'message'            => $errstr,
            'file'               => $errfile,
            'line'               => $errline,
            'context'            => $errcontext,
            'type'               => $errorTypes[$errno],
        );
        
        print_r($ret);
        
        return false;
    }
}

MC Stevepants
Jan 7, 2006

Who wants a spanking?
Wondering if you guys could help out a total PHP n00blet.

I'm literally just getting my feet wet, started going along with PHP For Dummies, and the first test to see if PHP functions properly on my site just returns a syntax error.

My site is hosted on GoDaddy, and the site stats say that PHP5 is indeed installed, but when I upload a test php statement, well, this happens:

http://www.karosikdesign.com/test3.php

Line 9 is: echo “<p>This is a PHP line</p>”;

HALP!

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

MC Stevepants posted:

Wondering if you guys could help out a total PHP n00blet.

I'm literally just getting my feet wet, started going along with PHP For Dummies, and the first test to see if PHP functions properly on my site just returns a syntax error.

My site is hosted on GoDaddy, and the site stats say that PHP5 is indeed installed, but when I upload a test php statement, well, this happens:

http://www.karosikdesign.com/test3.php

Line 9 is: echo “<p>This is a PHP line</p>”;

HALP!

Why are those quotes so strange looking? ” vs "

Aturaten
Mar 23, 2008

by elpintogrande

MC Stevepants posted:

Wondering if you guys could help out a total PHP n00blet.

I'm literally just getting my feet wet, started going along with PHP For Dummies, and the first test to see if PHP functions properly on my site just returns a syntax error.

My site is hosted on GoDaddy, and the site stats say that PHP5 is indeed installed, but when I upload a test php statement, well, this happens:

http://www.karosikdesign.com/test3.php

Line 9 is: echo "<p>This is a PHP line</p>";

HALP!

Your quotes are not the 'right' quotes. Copy and paste this text, which should work:

code:
echo "<p>This is a PHP line</p>"; 
What are you writing this in? Download Notepad++, PSPad, or any other text editor with syntax highlighting, but I recommend Notepad++.

Also, echo is a language construct, not a function, and I do not recommend that book at all. Pickup "PHP and MySQL Web Development" and, after that, read "Object Oriented PHP".

MC Stevepants
Jan 7, 2006

Who wants a spanking?
Thanks kids. I was writing it in Dreamweaver, but I copy/pasted that line of code from the book PDF(acrobat).

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

mpeg4v3 posted:

Okay, this might be kind of long.

:words:

So, for example, if I add the Calendar module to the site, the menu will automatically contain a link to the Calendar, and clicking on that link will load the Calendar in the content section of the web site. I've pretty much figured out how to do this.

However, I also want modules to be able to add content to other modules. This is part of where I'm currently stuck. I'm not really sure how to have one module add content or features to another module. Let's take the Calendar again for example. Say the Calendar is loaded, displaying all of the Shifts people are working that week. Now let's say I add in a module that allows people to switch their shifts with someone else, and I want that option to display on the shift information in the Calendar. How would I go about getting it to display?

As has been touched on, separate Model, View, and Controller, and how I like to think ( which may or may not be the "right" way, but it works for me ) is to have everything be as "dumb" as possible.

So your Application (site) has modules, each one gets a link in the menu. So, each module should have a drawMenuItem() method. The app shouldn't know how to make them, just how to tell the modules to make them. When it's time to make the menu, you iterate over all loaded modules and call that method.

For your Calendar... it shouldn't "do" anything but display stuff. Have a Model that returns objects based on a User object, month, and a year. If each object has a drawCalendarView() method, the calendar doesn't have to know to do anything other than say "OK, are there any things on this day? Yes? Iterate over the things on this day and call their draw method!" The Calendar doesn't need to know anything about what it is displaying, just that *something* is there.

Your Model works to hand data to something that requests it.. it doesn't care what. Regardless if it's the Calendar, the BigBossReport, or some other class / module requesting it, getEventsForUserInMonth( $user, $month, $year ) should poop back an array of objects. The model can see if the Shifts module exists... if so, it includes Shifts, if the Meetings module exists, it includes those, etc. Using the same method and result, the Calendar will ask each of them to draw their calendar views, the BigBossReport may tell them to draw out in CSV format, whatever... the Model hands them (and anything else) the same exact data.

This also makes things less dependent, like Begby said: the calendar doesn't need that particular model... it needs something that it can ask for data with the getEventsForUserInMonth() method, and for it to return things that can draw their own views. So if the boss says "Hay guys, we are now getting our data from PoopForce instead of our own DB" you can just change the Model to point to a new DB.. all the classes that ask it for data dont' give a crap.

So the short version is: if something is doing a lot, it probably shouldn't be.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

MC Stevepants posted:

Thanks kids. I was writing it in Dreamweaver, but I copy/pasted that line of code from the book PDF(acrobat).

Never copy and paste when you are starting out. Even if you are just copying verbatim from one window to another, type it out. You will learn better!

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:
Just checking in to say my mood has improved considerably since I discovered encode_json(). My snippet up there was intentionally awful btw; even I know that writing javascript with javascript is not a sane thing, and writing PHP that writes javascript that writes javascript is (not sane)^2.

I was 80% done and then my client aka coworker got impressed with a similar tool's interface, so I'm trying to salvage the backend while adding all this AJAX crap to the front, which involves lots of HTML snippets being requested from the server via JSON rather than full page loads. I was not having much success writing my own escaper -- still don't know what I was doing wrong, but that's moot now.

Yeehaw McKickass
Dec 15, 2004
Would someone be able to direct me to some simple contact form resources? Tutorials, or straight up code, what-have-you.

I basically just want something that confirms the mail was sent within the form. I've been looking around and have only been able to find really outdated stuff.

mpeg4v3
Apr 8, 2004
that lurker in the corner

Begby posted:

:words:

Lumpy posted:

:words:

Thanks a ton to the both of you. I've been researching MVC for pretty much the past week after reading the earlier replies, and a combination of that research, Begby's post, this guide, and finally Lumpy's post to snap it all into place in my mind makes me think I finally have a good conceptual understanding of how to do this. I'm still not completely sure though, as it's been a lot to figure out and again, I don't really have the mind for this sort of thing. I'm going to try and write up exactly how I think the whole thing will work in a bit more detail tomorrow, but for now here's a rough idea of what I figured out. Sorry for my crappy pseudo code, I'm doing this in a rush.

URL: index.php?page=shifts&action=viewweek
$page = $_GET['page'], $action = $_GET['viewweek']

Basically, in a nutshell, the system will create a new SuperController, which can create new Models or Controllers. It'll create a Modules Model, figure out what modules to load for the current page based on dependencies and plugins, create new Controllers for each of those modules (which will then create new Models and Views for each new Controller), have each Controller do their built in function for the specified action (which includes storing the resulting data into their View), and then have the View render the output, which will include any of the data from the plugins that hooked into the current page.

Steps:
  1. Create a new SuperController (extends Controller)
  2. SuperController creates new ModulesModel (extends Model)
  3. SuperController->getParent($page) returns the parent module for that page (Shifts is a child of Calendar, and cannot be a child of anything else)
  4. ModulesModel->getDeps($page) iteratively gets all of the module dependencies for that page, sorts them by level (so for example, Shifts requires Calendar), and stores them in $_deps. (I'm not sure if I need this, but I'm wondering about future modules that require more than one module to work, but are only a child of one module)
  5. SuperController goes through each of ModulesModel->_deps, and creates a new ($dep)Controller object (extends Controller) for each dependency.
  6. SuperController creates a new ($page)Controller object (extends Controller), and passes it the $action variable.
  7. ModulesModel->getHooks($page) iteratively gets all of the modules that hook into the current page, as well as their dependencies, and stores them in $_hooks.
  8. SuperController goes through ModulesModel->_hooks and creates a new ($hook)Controller object (extends Controller) for each hook module, and passes it the (($page).($action)) variable.
  9. Each of the Controllers listed above creates their associated Model, so for example ($page)Controller creates ($page)Model (extends Model), ($hook)Controller creates ($hook)Model (extends Model), etc.
  10. Each of the Controllers listed above also creates their own associated View, in the same style as they created their associated Models. ($page)View (extends View) is passed $action, while ($hook)Views (extends View) are passed (($page).($action)).
  11. The SuperController calls the ($page)Controller->$action function, which generates the data for the specified action. So, in this case, it generates all of the shifts during the week. It also calls on a ($page)Controller->set($variable, $data) function, which calls on ($page)View->set($variable, $data), and adds a new array value to the ($page)View->_variables Array with the data. So, for example, ($page)View->_variables['shifts']['monday'] would => an Array with all of the shift information for Monday.
  12. The SuperController does the same thing for all of the ($hook)Controllers->($page.$action), so all of the plugin data is stored in each ($hook)View->_variables array, as well.
  13. This is as far as I've figured it out. I figure from here it won't be too difficult, just figure out a way to control how the ($page)View and ($hook)View renders for that action will be able to be integrated. So, for example, how shiftsView->viewweek render will include any ($hook)Controller->($hook)View->shiftsviewweek renders.

If this is one big, disjointed, confusing mess, I'm sorry. I typed it up really fast, and I know it probably isn't that clear. If it does make sense, I guess my main question is if this is remotely close to the right way of doing it. It seems quite complicated, and I think part of the reason for that is me having a SuperController that basically creates and controls other Controllers, but I couldn't think of any other way for there to be a plugin system, where new data can be processed and returned to the current page's controller without any of the controllers having to know about any other controllers.

Ugh, maybe I just should have started my own thread instead of clogging up this thread with this.

mpeg4v3 fucked around with this message at 07:22 on Mar 19, 2010

Adbot
ADBOT LOVES YOU

DarkLotus
Sep 30, 2001

Lithium Hosting
Personal, Reseller & VPS Hosting
30-day no risk Free Trial &
90-days Money Back Guarantee!

Yeehaw McKickass posted:

Would someone be able to direct me to some simple contact form resources? Tutorials, or straight up code, what-have-you.

I basically just want something that confirms the mail was sent within the form. I've been looking around and have only been able to find really outdated stuff.

What do you mean "Confirms the mail was sent"? Just making sure the mail sending function completed without errors?

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