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
Begby
Apr 7, 2005

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

fletcher posted:

What's a clean/efficient way to do bbcode replacements for format tags

This has been done a lot. It would probably be a good idea to check out the source for a php package that has already implemented this.

On the surface it looks easy, you could just replace all the [ b]'s with <strong> and all the [/b]'s with </strong>. But if you want it to be right you need to make sure there is a matching closing tag for every open tag and vice versa. Otherwise you could break the rest of your layout. You also need to check if the tags are nested properly. I am sure there are other issues as well.

Adbot
ADBOT LOVES YOU

Begby
Apr 7, 2005

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

fletcher posted:

Which has corrected the malformed html. Is this a bad solution?

It might be ok. Just test the ever living poo poo out of it with as much bad data as you can to make sure you get the desired results as you don't really know what is going on deep in the innards of DOMDocument.

That is a pretty good idea btw, good thinking.

Begby
Apr 7, 2005

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

drcru posted:

What kind of timestamps are these?

12314
12345
12356
12367
12378
12456
12859

Do you have any hints such as where you found these?

Begby
Apr 7, 2005

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

admiraldennis posted:

I know you "want to do it yourself" but seriously if your site is getting hammered and your host is complaining just buck up and either 1) go learn to do this with a database, or 2) have somebody else do it for you and study the code and db schema to figure out how it works.

I have to agree with this guy's view point.

Personally I cringe whenever I have to write or read from any sort of files. Its nots terribly difficult, but more difficult than working with a database. If you have any sort of head on your shoulders and are not illiterate, you should be able to figure out how to create a database, write to it, then read from it in 4 hours max.

Begby
Apr 7, 2005

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

drcru posted:

How can I improve this system of including/defining?

code:
define('ROOT_PATH', '/home/username');	// set the ROOT_PATH here
define('BACKYARD', '/lawn');		// set the backyard path here
include_once(ROOT_PATH . BACKYARD . '/config.inc.php');
include_once(ROOT_PATH . BACKYARD . '/skin.php');
include_once(ROOT_PATH . BACKYARD . '/db.inc.php');
include_once(ROOT_PATH . BACKYARD . '/error.inc.php');
I've set up 3 pages so far but I'm worried about making changes for when we go live...

You can setup a config.php file in your root, or even above your site root, then include that at the top of your pages. Then use the constants in your pages.

in config.php you might have something like this.....

code:
define('SITE_ROOT', dirname(__FILE__));
define('INCLUDE_PATH', SITE_ROOT.DIRECTORY_SEPARATOR.'/lawn');
Then in one of your pages
code:
require_once('../config.php');
require_once(INCLUDE_PATH.'/error.inc.php');
'__FILE__' means 'the full path name of the file I am currently in'. So if you're config.php file is in /some/path/config.php, that is exactly what will be in __FILE__. Try echoing it.

dirname() will take a string that is a file path and try to chop off the file and return the directory only. So if you pass it /some/path/config.php it should return /some/path.

'DIRECTORY_SEPARATOR' is a predefined constant that has the directory separator specific to the OS you are running php on. So if you are on windows it will return '\\' and on linux '/'.

So now if you have a single include that is setup like that you never have to change any of this even if you move your app to another server, which is handy. The only thing you might need to change is the require_once('../config.php') if you start moving files around.

Begby
Apr 7, 2005

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

Sewer Adventure posted:

Either way, not using an ORM is just making more work for yourself.

I have tried plenty of ORM's, they often turn out to be more work. Its often much much easier to just use an SQL join instead of setting up a bunch of objects to do a join. It also makes it a lot easier to optimize SQL statements if they are staring right at you instead of trying to figure out what SQL statements the ORM is making up and how to make them run faster.

A good bridge is something like PDO or Zend_DB with prepared statements. It is pretty close to database generic (although swapping out drivers would probably require a little bit of work) and will let you write SQL without having to escape everything. Zend_DB includes a lot of handy methods that help with simple queries.

If the app is well written, and you have some wrappers so that your SQL ends up all in a clearly defined set of classes, then not using an ORM can be a very robust maintainable solution.

Begby
Apr 7, 2005

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

Kaluza-Klein posted:

I have a general question about arrays and objects. I have been using code igniter a lot lately and it is (in most cases) happy to accept an object as a function input anywhere that it will take an array.

I think my code is a bit easier to read using objects instead of arrays. The syntax of arrays always seemed a bit clunky to me.

There are a few places where CI will not take an object and only works with arrays so I have had to break out the odd array here and there throughout my code. It has me thinking now about arrays and objects and if I should be using one over the other.

I realize objects can hold more data types but I have never built my own object/class. I don't have any class functions inside my objects. I tried in CI once and failed miserably. I don't know if I was doing it completely wrong or if I wasn't following CI's specifications.

So my objects just look like arrays for the most part. In fact, anywhere that I was forced to use an array I always change the variable to an object type as soon as I can to continue working with it.

Should I be using objects in this manner? I am just using them to store string variables which I pass between functions for the most part. I just think it looks nicer when you define them, and especially when you have to echo them out into your final html.

Using objects can help immensely. So you are on the right track, but could get your learn on in the realm of OO.

Here is an example of a simple object and how it might be useful.

code:

class Person
{
  public $birthYear;
  public $firstName;
  public $lastName;

  public function Age()
  {
     return date('Y', time())  - $this->birthYear;
  }  

}

$me = new Person();
$me->birthYear = 1976;
echo $me->Age();
The above is pretty simple. You have an object that represents a person, but we added something that calculates an age. I think you can probably figure out the usefulness.

Anyways, there are a billion books out there on OO theory. You don't have to get one that is based on PHP, you can read one that is about Java or even C++ and as long as you understand the theory you can apply it to PHP.

As far as CI is concerned, you can make an object behave more like an array in php by having it implement some interfaces (there are also magic methods defined here http://www.php.net/manual/en/language.oop5.magic.php)

Here is a simple example. You would probably want to use the __get() and __set() magic methods to make it a little more solid.

code:

// The ArrayAccess interface defines 4 methods that you implement, this lets you use your
// object with array-like bracket syntax
class Person implements ArrayAccess
{
  public $firstName = "";
  public $lastName = "";

  public function offsetExists ($offset)
  {
    if isset($this->$offset) return true ;
    throw new Exception ('offset undefined');
  }

  public function offsetGet ($offset)
  {
    if isset($this->$offset) return $this->$offset;
    throw new Exception ('oh crap');
  }

  public function offsetSet ($offset, $value)
  {
    if isset($this->$offset) $this->$offset = $value;
    throw new Exception ('oh crap');
  }

  public function offsetUnset ($offset)
  {
   etc.
  }
}

$me = new Person() ;
$me['firstName'] = 'Fred'; // This calls the offsetSet method and passes it 'firstName' for $offset and 'Fred' for $value
$me->firstName = 'Fred'; // bypasses the offsetSet method, but
$me['food'] = 'taco'; //throws an exception

There are lots of things you can do with objects in PHP. The above may not solve your CI solution, it depends on what the functions are doing with the array you pass it, but there are other interfaces such as GetIterator that may solve your problem. You can look them up here http://www.php.net/~helly/php/ext/spl/


Before you do any of that though, brush up on some theory.

Begby
Apr 7, 2005

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

drcru posted:

So last night I wrote a fairly simple calendar function. It seems to work fine but it looks inefficient. Keeping within the same principles... how would you make it better?

The first thing to do to make this better is to maybe comment it then tell us what it is supposed to do and why.

Begby
Apr 7, 2005

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

Zorilla posted:

Why not use trim() to remove trailing spaces before checking instead?

Yes, this is a better approach. Trim() also removes whitespace characters like enters and tabs as well.

Begby
Apr 7, 2005

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

cLin posted:

I'm guessing it's similar to the post below yours where you just execute a sql query using one of their methods, but are either of these small in size? I don't want to make a program even slower by including a big file.

You can use PDO too

https://www.php.net/PDO

code:
$pdo = new PDO($dsn, $login, $password);

$stmt = $pdo->prepare("SELECT * FROM people WHERE name=:name");
$stmt->BindParam(":name", "fred");
$stmt->execute();
This will let you do prepared statements securely and it is a compiled module so you aren't going to have to include any big libraries or anything.

Its not bundled with all distributions of PHP 5 though, so YMMV.

Begby
Apr 7, 2005

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

Grigori Rasputin posted:

Another day, another PHP question. Is there a way to hide URL arguments like "index.html?pageid=123&type=x" from the user? I figured it would be configurable in php.ini but I haven't stumbled upon anything yet.

Also, is using URL arguments like this the preferred way to communicate between pages? It's very easy to do, but I wasn't sure if there was a better way.

Keep in mind that one thing that is handy about having those arguments on the URL line is that it makes it so you can store the page in a bookmark. If you use sessions or post that won't work. Also, if you use post, then clicking on the back button in your browser can generate warnings.

You can also use a framework that will let you do more human readable arguments like

http://www.mysite.com/products/page/123/type/x

Most users though really don't care about what is in the URL. Go to some major sites and look up there and see all the incomprehensible garbage that ends up there.

Begby
Apr 7, 2005

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

Phiberoptik posted:

I want to look at designing an application designed to interact with another website. Basically, I want to be able to read data and interact with the other page through PHP. (Automate a control panel which I do not want the user to have full access to) Can anyone point me in the right direction on what I would use to do this?

1. Use curl to download a page from the other site

2. Curl will return the page source as a string. You can then read through this string using regular expressions, or if it is well formed maybe DOM.

3. After you find what you need in the page, you can then send another request back to the site with curl to post data to forms etc.


This could be relatively simple or it could be a total clusterfuck nightmare, it really depends on what you need to do with the other site and how well structured the HTML on that site is.

P.S. If the pages change that you are interacting with, it could break your code, so be careful

Begby
Apr 7, 2005

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

drcru posted:

Faster and or more efficient than in_array?

Probably not. One thing to keep in mind is that in_array is a compiled c routine, so its going to be pretty quick.

However even if yours was faster, who cares. I don't think you need to worry about milliseconds of difference (which is what the difference would be) unless your site is getting a million hits an hour.

Begby
Apr 7, 2005

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

nbv4 posted:

I'm not really "checking" for dupes, I'm just doing: .....

A couple of things to keep in mind

1. Don't worry about how memory intensive it is unless you are actually seeing a performance hit under load.

2. Searching on array keys is faster than searching on array values



One thing you can do is read from the old array, and insert into a new array and have it keyed by the value you want to have unique

code:
foreach($oldArray as $value)
{
  $reversedValue = implode("-", array_reverse(explode("-", $value)))
  if (!array_key_exists($value, $newArray) && !array_key_exists($reversedValue, $newArray)
  {
   $newArray[$value] = 'stuff'
  }
}
Using the above, the first iteration the new array is length 0, the second iteration length 1, and so on. That way you aren't searching a 5000 item array on every iteration.

Secondly, its searching on keys instead of values. So this should be a lot faster.

Begby
Apr 7, 2005

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

fletcher posted:

I'm trying to use this PHP Serial Extension following this reference for XAMPP but it's still saying the extension isn't loaded. What could be causing this?

My phpInfo() is showing:

Server API: CGI/FastCGI
Loaded Configuration File: C:\xampplite\php\php.ini

and that is the php.ini where I put:

extension=php_ser.dll

Did you look in the error log? I am guessing that it is not finding the dll file.

Begby
Apr 7, 2005

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

xluna posted:

Awesome. Great idea. I didn't know how static methods worked, and this just made life a lot simpler. I knew there had to be a way to simply use class methods without instantiation as you do it all the time in C++, i just wasn't sure how because of my new-ness to it all.

Static methods are handy, but don't overuse them. If you do you will make your classes harder to reuse since they are dependent on the implementation and naming of classes. Also, it makes it harder to do unit tests.

I fell into this trap, and ignoring the advice I received on this forum and others dug some deep holes for myself that are still biting me in the rear end.

For instance, you might be tempted to create a database class and call it like mydbclass::query($sql). Then mydbclass might have a singleton db connection or something.

The problem arises when you try to reuse dependent classes in a different application, you have to have mydbclass wherever that class is uses. Or what if you want to query two databases with the same object that depends on mydbclass. You would be up a creek.

So it can be handy, but don't overuse it. Often it is better to pass objects in constructors like this, and to make classes dependent on interfaces:

code:
$db = new mydbclass();
$people = new peopleThingy($db);
That is a lot better than making peopleThingy use a static db class, its more flexible, plus you can unit test it without too much trouble, also you can swap out $db for any other object as long as it implements the same interface.

Begby
Apr 7, 2005

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

Aturaten posted:

Is there any way to get a DIVs size using PHP? I really need to find this out soon, this image gallery is killing me.

PHP outputs HTML on the server and sends it to your browser. Your browser then renders the div and creates the size, at that point PHP is done processing.

You would need something client side to read the div. You could however send this back to PHP via javascript or something.

That is unless I am missing your point, if so be more descriptive.

Begby
Apr 7, 2005

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

Munkeymon posted:

Good point. I guess you would have to go back and add up the days from every year unless you were expecting short file lifetimes. Or the PHP devs could make a propper time span object.

Edit: kind of ugly, but it works according to Python's datetime class.
php:
<?
$now = new DateTime();
$ft = new DateTime(date('c',filemtime($filePath)));
//days this year
$diff = intval($now->format('z')) - intval($ft->format('z'));
//days in other years
$ft = intval($ft->format('Y'));
for($i = (intval($now->format('Y'))-1); $i >= $ft; --$i)
{
    $now = new DateTime('Dec 31, '.$i);
    $diff += intval($now->format('z')) + 1;
}
?>


This should give the exact same result, unless I am missing something.
php:
<?
$secsInDay = 60 * 60 * 24;
$daysOld =  floor((Time() - filemtime($filePath)) / $secsInDay);
?>

Begby
Apr 7, 2005

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

Munkeymon posted:

Not every day has that many seconds. http://en.wikipedia.org/wiki/Daylight_saving_time

Oh sure man, get all exact on me why don't you....

I think this whole calendar thing is bullshit anyways, we should start over and just count days since Chuck Norris was born or something and get rid of the whole weeks, months and years thing. Its all so complex and confusing.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.
I have found the best way to get the absolute path is this

php:
<?
define("ROOT_PATH", dirname(__FILE__));
?>
That works if the file it is called from is in the root, or you can get the dirname and explode it into an array using DIRECTORY_SEPARATOR as the delimiter, pop some directories off the end, and implode it back into a string and use that as the root path.

This will work either in a command line program or website.

Begby
Apr 7, 2005

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

Lumpy posted:

I assume PDO cleans bound parameters of nasties, or must one still do that manually?

It cleans them for you.

Begby
Apr 7, 2005

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

drcru posted:

Would it be very memory/cpu intesive if I looped through this and checked for conditions?

Looping through an array is not that memory intensive in php. You can probably increase that array to include a couple of thousand elements and not notice too much of a hit. Try creating a loop from 1 to 10,000 that generates an array like this, then loop through it and see how much of a difference it makes.

Bottlenecks typically appear in database queries and file access.

Begby
Apr 7, 2005

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

Lankiveil posted:

What is the current cool framework to use for PHP? At the moment I'm playing with CodeIgniter, but I'm happy to jump ship if there's something better out there.

I tried them all and keep going back to codeigniter. I do use some Zend libraries within it though. One nice thing about Zend is that it is very modular and well written as far as dependencies go. You can grab modules out of it and just use those pieces without having to do a bunch of framework wide stuff. However, the View and Controller stuff in Zend were really frustrating for me to use.

In codeigniter its pretty easy to replace stuff with your own junk. For instance you don't have to use their model or db objects, its pretty easy to write your own within their framework.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.
Does the SOAP API you are referencing require attachments? I was working with a SOAP API with attachments and found that for some reason in php5 its totally borked due to libxml or some such dependency. I ended up fixing it by hacking around with the pear soap library and I finally got it to work that way.

Also, you might want to try fiddler instead of wireshark. Its heaven for this kind of stuff, a lot easier than wireshark.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.
Probably the best thing to do is check for magic quotes one time in your bootstrap, then turn it off if its on.

Then, drop mysqli and use PDO with prepared statements.

Begby
Apr 7, 2005

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

Eararaldor posted:

Got another interesting question for you goons...

In ASP.NET, theres a ASP.NET Calendar Control function. I was just wondering if theres something I can use that's similar in php?

I'd rather not trust the user typing it out themselves, so an actual calendar popping up would be awesome.

The PHP language itself does not include any libraries of GUI elements. You'll need to find a 3rd party javascript thing to do this.

Begby
Apr 7, 2005

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

VerySolidSnake posted:

This is odd as the function works fine if I call it straight on the page, but once I call it from this other function it fails. Sorry for taking up so much room in this thread but here is a more full version of the code.

What you want to do is get your includefile stuff into an array, then loop through that array after closing the statement. You cannot execute another prepared statement while another is open.

So in your while(mysqli_stmt_fetch($stmt)) loop you will add the results to an includes file array, close the statement, then do a foreach on the array.

Speaking of that, you aren't closing any of your statements nor are you doing any error checking in your teamlist function.

Also, speaking of that, its generally a pretty bad idea to do something like $myfunction($arg) where $myfunction comes from text that is editable outside of your source files. If someone had access to your database they could put whatever fun things they wanted into the includefile field and PHP would happily execute it.

Begby
Apr 7, 2005

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

VerySolidSnake posted:

Is there a Holy Grail function for sanitizing user input (when considering I'm using prepared statements for every query)? Or am I pretty safe as long as I use html_special_characters on input and have an 'allowed' functions list?

Prepared statements are pretty secure, html_special_characters is good if you are going to be echoing any db content. You might want to look into how to protect yourself against XSS attacks as well, google for it (cross site scripting attacks).

You also might want to take a look at PDO if you are going to be doing a lot of prepared statements. It makes it so you don't have to pass around a connect resource everywhere. Zend Framework has a nice wrapper for it that even simplifies it further.

Begby
Apr 7, 2005

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

Supervillin posted:

Just emphasizing something that VerySolidSnake had backwards in his question. You should typically sanitize immediately before using something, no sooner.

The main reason for that, of course, is if you htmlspecialchars stuff on the way IN, you're assuming everything in your database is safe for output later. However, anything could happen between the time it's stored and the time it's used. Not necessarily an attack, either - what if you have to manually enter a row for whatever reason, and forget to manually escape it? You don't have to worry about that if you only use htmlspecialchars immediately before echoing the text.

Excellent point, this is something that I should do more often.

Begby
Apr 7, 2005

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

sonic bed head posted:

Thanks for the advice.

I would like a nice form UI though and I also want a session associated with each user. It's not that important in that the information that this login is protecting isn't really critical and no one would care that much if other people got into their account. It's important in that I would like it to look nice and like a regular web application.

Crypt is fine, just make sure you use a different random salt each time.

Begby
Apr 7, 2005

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

sivo posted:

Zend_Form. This class seems to "suffer" from the ZF use-at-will design in that it blurs together aspects of the view (decorators) and the model (validation logic) - I just have no idea where to stick my Zend_Forms.

Your model should just be the data and thats it. Ideally if you dropped zend framework and went with code ignitor, you should just be able to take the zend model class and maybe the zend pdo class with you and your models should work fine. If not, then stuff isn't separated like it should be.

Think of it this way, you should be able to code your model so that you could satisfy all requirements of your app by running it through command line scripts and no GUI. If forms became tied to your model this would break. So stick your forms outside the model.


sivo posted:

To me, it looks like B is the way to go, but I can't help but feel worried that I am robbing Controllers of what seems to be, fairly often, their only responsibility (that you write yourself, at least) - that A is so popular doesn't help my confidence in B.

A is the way to go. You want your views to just display data without actually doing any logic. Your controllers should do the querying and decisions.


Overall though, I think I went down the same path as you previously. Just because it is included in Zend, doesn't mean you have to use it. Its good to learn how to use things and learn the theory, but more often than not using all of the framework for everything leads to pattern overuse and unnecessary complexity. Sometimes its better to just hand write forms in HTML instead of using form generators.

Begby
Apr 7, 2005

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

drcru posted:

Whats a good way to encrypt and decrypt a variable with a specific salt?

What exactly are you trying to accomplish? Do you want to encrypt some text and store it and decode it with a password or keyphrase later? Or are you trying to encrypt a password for storing in a db? something else?

Begby
Apr 7, 2005

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

Lamb-Blaster 4000 posted:

Im working on a site hosted at a server running mysql 4, my dev machine's php has mysql 5 and when I attempt to connect to the remote server I get

Unknown MySQL server host '<the server>' (11004)

the same when I try to shell in.

is there an easy way to tell my dev php to use the mysql4 driver? and also is there a way to do the same when I use the shell?

This error does not have to do with mysql versions, but rather there is a problem connecting to the remote mysql machine. Either you are using an invalid IP address, or there is a DNS issue where the name is not resolving correctly, or its trying to connect over a proxy or something.

Begby
Apr 7, 2005

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

http://bugs.php.net/bug.php?id=48139

Begby
Apr 7, 2005

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

Tap posted:

I have a 'dataprocessor' library written in PHP that parses through a CSV file that varies in size (1K to 2M). The larger files end up taking quite a bit of memory because of the looping required to manipulate the actual data itself.

Now my question - is there a way to free up memory in PHP during the execution of the script? I call the unset() function on the variables that are unused but I don't think that unset is actually meant to free up memory.

Hrmm.... I wouldn't know how to optimize your code unless I saw it, but PHP is not always memory efficient when you load up a file. It could very well be that a 2mb file takes up 40mb of memory when you load the whole file up. Its just the way PHP is.

You should read up on how php manages memory and reference counting. Often unset won't do what you expect it to do, for instance in this case

code:
$x = 'hi there';
$y = $x;
unset($x);
Calling unset($x) in this example doesn't do much but free up a single reference. What the php processor did was set aside memory for 'hi there'. Then when you do $y=$x, $y actually becomes a reference to 'hi there' and the string is not actually copied (even though its supposed to be a copy). So when you do unset($x) all that happens is the reference count for 'hi there' is decremented by 1 and no real memory is actually freed.

From a coding and functional viewpoint though, you can work as though it was copied. If you then change the value of $x to something else, $y still will have a value of 'hi there' and $x will get assigned the new value. At that point the original memory location reference count is decremented by 1, and you now have two strings in memory, each with a ref count of 1. No calling unset($x) would actually free up space.

Confusing hey? Well you could be running into issues such as this when trying to optimize your code.

Begby
Apr 7, 2005

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

Recycle Bin posted:

I'm working on a simple gallery program for my website, and I'm in the middle of cleaning up my code. I replaced a bunch of the echo statements with heredocs for stuff like forms, but because I have to have my delimiter placed all the way to the left, I want to separate these heredoc statements in their own separate file to keep things organized. Problem is, these statements have variables, and if I stick my include statement at the top of the file, the variables will just show up as blanks when it comes time to call them. My questions are:

1) How can I make a call to a string containing variables from outside its original file?
2) Is there a more efficient way to do what I described? I'm fairly new at this.

You have to put the include after where the variables are set.

You might want to look into an MVC framework. Codeignitor is pretty simple and easy to pick up. It helps you separate your view (in this case your heredoc stuff) from your program logic.

Begby
Apr 7, 2005

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

drcru posted:

Are there any reasons as to why this function gets occasionally slow?

php:
<?
    public function show_map($sector, $galaxy, $distance = 2)
    {
        $start_sector    = $this->galaxies[$galaxy]['start_sector'];
        $width            = $this->galaxies[$galaxy]['width'];
        $end_sector        = $start_sector + ( ($width * $this->galaxies[$galaxy]['height']) - 1 );
        $min            = $distance * -1;
        $tile            = 0;

        $map = array();

        for($l = $min; $l <= $distance; $l++)
        {
            $mid_of_line = ($sector + ($width * $l));

            if( ($mid_of_line < $start_sector) || ($mid_of_line > $end_sector))
                $mid_of_line = -1;

            $line = ceil(($mid_of_line - $start_sector + 1) / $width);
             $start_of_line = $width * ($line - 1) + $start_sector;
            $end_of_line = $start_of_line + $width;

            for($s = $min; $s <= $distance; $s++)
            {
                $current = $mid_of_line + $s;

                if( ($current < $start_of_line) || ($current >= $end_of_line) || ($current > $end_sector) )
                    $current = -1;

                if($current > 0)
                {
                    $map[$tile] = $this->info[$current];
                    $map[$tile]['sector'] = $current;
                    $css = "sector";
                    if($current == $sector)
                        $css .= " current";
                    if( in_array($current, $this->get_exits($sector)) )
                    {
                        $css .= " linked";
                        $map[$tile]['link'] = "./move.php?sector=$current";
                    }
                }
                else
                    $css = "explored sector";

                $map[$tile]['css'] = $css;

                $tile++;
            }
        }

        return $map;
    }?>
Could the fact that $sector is different on every page load as it is updated in MySQL have anything to do with it?

For one thing there is a lot going on there. I don't think anybody is going to get out a pencil and try to make an attempt to try and figure out what you are trying to do. Perhaps you should try to comment your code and/or simplify it a bit or break it into smaller functions.

I have no idea what $sector is or what you are talking about with the mysql thing.

The only thing I can see offhand is $distance. You are looping through it, then looping through it again within that loop.

So, if $distance is 1000, you will end up doing 2000 iterations ($min would be -1000), and 2000 iterations within that. This would mean the inner for loop would run 4,000,000 times, which turns out to be a lot of processing if you are doing in_array().

Not sure what your range is on $distance though, if it is always low numbers then thats probably not what is slowing it down.

edit: Also, what does $this->get_exits($sector) do? Does that do any db queries? You should note that if you comment it.

Begby fucked around with this message at 14:31 on Jun 5, 2009

Begby
Apr 7, 2005

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

Golbez posted:

Though in retrospect there's really no reason for me to use "getData" and "setData"; all those commands do is verify the array key exists in $Record. I could just have public variables like, y'know, $UserID, $CaseTypeID, etc. Would make the sanitize function a little more complicated (having to run specifically on each variable, rather than just pass an array to it), but it might make life simpler. And since most of what sanitize() does is escape it, I could skip that if I'm still parameterizing.

Thoughts?

Edit: Or I could skip using the functions to read its own data and pass the Record directly. Duh.

The idea of using prepared statements is that the API does the escaping for you, you shouldn't need to do any sanitizing as far as database security (but still want to check user input for validity).

Personally I used PDO or Zend_DB (which you can have ride on top of PDO). Also, its really easy to extend PDO or Zend_DB into your own subclasses, which is extremely handy.

With Zend_DB you don't have to use the entire gay framework, just the DB library, and you can do stuff like this, but still have the power to write your own SQL statements when needed.

code:
$values = array(
  'name' => 'Abe Vigoda',
  'status' => 'alive',
  'comments' => $comments
);
$db->insert('mytable', $values);
$newID = $db->lastInsertId();
You could also rather easily subclass PDOStatement/PDO and create your own insert method that does the above, might be good practice if you want to learn PDO inside and out.

Begby
Apr 7, 2005

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

Golbez posted:

I *like* writing queries. Why do all these advanced things take that tiny joy away from me? :sigh:

You still can with PDO if you want. You can do stuff like this, and it will still do all the data cleansing.

$sql = "INSERT into mytable(field) VALUES(@field)";

Then you can do $stmt->bindValue("@field", $value);

(probably not exact syntax, but something similar).

Adbot
ADBOT LOVES YOU

Begby
Apr 7, 2005

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

drcru posted:

Is there anyway to do the following with PDO?

Original
Array ( [0] => Array ( [map_id] => 1 [name] => Peanut Butter [width] => 25 [height] => 15 [start_sector] => 1 ) [1] => Array ( [map_id] => 2 [name] => Cold Lamb Sandwhich [width] => 11 [height] => 15 [start_sector] => 376 ) )

Array Index is map_id
Array ( [1] => Array ( [name] => Peanut Butter [width] => 25 [height] => 15 [start_sector] => 1 ) [2] => Array ( [name] => Cold Lamb Sandwhich [width] => 11 [height] => 15 [start_sector] => 376 ) )

I'm using fetchAll(PDO::FETCH_ASSOC) right now.

I don't believe so. But it is pretty easy to create a function that will take your array from pdo and spit out your new fancy array. Like

code:
$newArray = ReKeyArray('map_id', $resultArray);

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