Show Posts
Pages: 1 2 3 4
1  Server Scripting / PHP / Basic Intro to arrays in PHP on: Dec 28, 2011, 10:02:39 am
Arrays are a special data type in PHP that is used to hold a list of data items. The ability to hold a list of data is valuable as it allows us to hold and pass sets of related data to different point in our application with ease.

Array Syntax
The simplest way to use arrays is to declare one using the array() function when declaring a variable.  There are a couple different ways to add data to an array, we can assign a value to the array with an empty index or by passing the values as parameters to the array() function.

When the array() function is used without any parameters an empty array is created.
Highlight Mode: (PHP)
  1. $ourList = array();

Passing values as parameters creates a non empty array. Passing a value to the array with an empty index also pushes a value to the end of the array.

Highlight Mode: (PHP)
  1. /* Fill an array by passing values as parameters */
  2. $ourList = array('Hello', 'World'); // pass values as parameters
  3. var_dump($ourList); // Visual Representation of the array.
  4. /* Filling an array by passing an empty index */
  5. $ourList2 = array(); // empty array
  6. $ourList2[] = 'Hello'; // pushes a value into the array
  7. $ourList2[] = 'World'; // pushes a value into the array
  8. var_dump($ourList2); // Visual Representation of the array.

Note: In the case that the array has not been explicitly created, simply using array syntax and assigning it a value will create an array with the key (if any) and values provided.

Array Indices
Arrays hold data as list and  list held by the array needs to be access in order to be useful. If you use a function like var_dump() or print_r() you can see a visual representation of the array like below:
Highlight Mode: (PHP)
  1. array(2) {
  2. [0]=>
  3. string(5) “Hello”
  4. [1]=>
  5. string(5) “World”
  6. }

Our array consists of two string values with a length of five characters. The important thing to notice is the value in the square brackets, this is the index that is used to refer to that value.

To access a given item in an array we simply use the name of the variable that holds the array and then use the index of the item in square brackets.

Highlight Mode: (PHP)
  1. # Fill an array by passing values as parameters
  2. $names = array('Leon', 'Ivan', 'John', 'Mohamed', 'Jose');
  3. echo $names[0], "<br>\n"; // Displays: Leon
  4. echo $names[1], "<br>\n"; // Displays: Ivan
  5. echo $names[2], "<br>\n"; // Displays: John
  6. echo $names[3], "<br>\n"; // Displays: Mohamed
  7. echo $names[4], "<br>\n"; // Displays: Jose
  8. # Visual representation of array.
  9. var_dump($names);

By default array indices begin at zero and count to one minus the number of elements. The array above has five elements and the indices range from zero to four.

Note: Indices can also be referred to as keys.

Specifying Indices (keys)
PHP automatically specifies the indices for arrays when none is specified. We can specify a different key starting point or do away with numerical numbering and use a string key names for our arrays indices.

To start numbering at a different value, we simply use the  “=>” operator when specifying values. Note that the parser will number any indices after that point in sequential order until a different index value is specified.

Highlight Mode: (PHP)
  1. $br = "<br>\n"; // Used for formatting
  2. /************************** EXAMPLE 1 ************************************/
  3. // Specify the count to start at 1 rather than 0
  4. $ourList = array(1 => 'Mercury', 'Venus');
  5. echo $ourList[1], $br; // Displays: Mercury
  6. echo $ourList[2], $br; // Displays: Venus
  7. /************************** EXAMPLE 2 ************************************/
  8. // Specify the a different index for certain values
  9. $ourList2 = array(1 => 'Mercury', 'Venus', 4 => 'Mars'); // 3 not defined!
  10. echo $ourList2[1], $br; // Displays: Mercury
  11. echo $ourList2[2], $br; // Displays: Venus
  12. echo $ourList2[3], $br; // Displays: Mars
  13. /************************** EXAMPLE 3 ************************************/
  14. // Specify a string key
  15. $ourList3 = array('home' => 'Earth', // key: home value: Earth
  16. 'largest' => 'Jupiter', // key: largest value: Jupiter
  17. 'center' => 'Sun', // key: center value: Sun
  18. 'Astroid Belt'); // key: 0 value: Astroid Belt
  19. echo $ourList3['home'], $br; // Displays: Earth
  20. echo $ourList3['largest'], $br; // Displays: Jupiter
  21. echo $ourList3['center'], $br; // Displays: Sun
  22. echo $ourList3[0], $br; // Displays: Astroid Belt

Note: PHP does not take white space into account when parsing code, for readability the example shows how we can set different keys and values on their own line. Arrays that contains string key names are referred to as associative arrays.

Arrays Inside Arrays
Arrays are nothing more than a list that holds other data types. Arrays can also be multi-dimensional, meaning that they can hold other arrays and those arrays can hold other arrays.
We can define arrays like the example below, or you can nest array() functions in one another.

Highlight Mode: (PHP)
  1. $family = array();
  2. // key 'adults' contains an array with keys and values
  3. $family['adults'] = array(
  4. 'mother' => 'Lea',
  5. 'father' => 'Lucas'
  6. );
  7. $family['children'] = array(
  8. 'son' => 'Leo',
  9. 'daughter' => 'Lisa'
  10. );
  11. echo $family['adults']['father'], "<br>\n"; // Displays: Lea
  12. echo $family['adults']['mother'], "<br>\n"; // Displays: Lucas
  13. echo $family['children']['son'], "<br>\n"; // Displays: Leo
  14. echo $family['children']['daughter'], "<br>\n"; // Displays: Lisa
  15. print_r($family); // Visual Representation of the array

Note: To access the data inside the inner array you specify a key of the array holding the inner array, then the key of the enclosed array.
Highlight Mode: (PHP)
  1. $variableName['outer array key']['inner array key'];
Note: This pattern continues if more arrays are enclosed.

Array Related Errors
While using arrays you may come across the following error.

Highlight Mode: (PHP)
  1. Notice: Undefined offset: key in file.php on line 20

Depending on the PHP setting on the server, this may or may not appear. In this example this is a PHP notice, which means the rest of our script will finish parsing and continue to be executed. If this was a fatal error our PHP script would stop executing all together.

This notice means that we have not defined this particular key for our array. To fix this you must specify the key the parser is trying to find at the line it specifies, or remove this reference all together, depending on what the script is supposed to be doing.

Arrays are a special data type in PHP that can hold a list of data including other arrays.  Arrays have sequential numerical keys (indices), but you have the ability to specify string key names or an alternate starting number. Arrays are commonly used to group related data in order to make it simple to pass the data to different parts of an application.
2  General Category / General Discussion & Chit Chat / Re: Looking for a nice "1940's" style theme on: Apr 17, 2011, 08:39:44 pm
What kind of content?  Images, text, video?

It'll be mostly text with a few images. The whole site will only be a few pages.
3  General Category / General Discussion & Chit Chat / Re: Looking for a nice "1940's" style theme on: Apr 13, 2011, 03:56:44 pm
A custom, one-off job.
4  General Category / General Discussion & Chit Chat / Looking for a nice "1940's" style theme on: Apr 10, 2011, 05:16:45 pm
I'm looking for nice "1940's" style theme for a kind of tribute to Frank Sinatra...any suggestions on where to look, or any specific examples of a site that has a retro or 1940's look to it?
5  Server Scripting / PHP / Re: Easy way to de-dupe a large list? on: Apr 10, 2011, 08:31:35 am
phpMan's bash script is perfect for what I need, but I'm also going to use one of your snippets for some other de-duping I need to do on a regular basis (via cron). My server restricts non-root users from running eval(), passthru(), or exec() so I can't use a bash script from within a PHP script...but I can use what you provided. Thank you.

This may use upwards of a meg of memory or so, but it sounds like a one-and-done thing (possibly on your local machine?)  so no worries. Smiley

Highlight Mode: (PHP)
  1. $lines = file( './domains.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
  2. $lines = array_unique( $lines );
  3. $lines = implode( PHP_EOL, $lines );
  4. file_put_contents( './domains.unique.txt', $lines );

...and by replacing array_unique() with array_flip()/array_keys() you can cut the processing time in half-ish:
Highlight Mode: (PHP)
  1. $lines = file( './domains.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
  2. $lines = array_flip( $lines );
  3. $lines = array_keys( $lines );
  4. $lines = implode( PHP_EOL, $lines );
  5. file_put_contents( './domains.unique.txt', $lines );
6  Server Scripting / PHP / Re: Easy way to de-dupe a large list? on: Apr 10, 2011, 08:28:32 am
Highlight Mode: (Bash)
  1. sort listofdomains | uniq > uniqed

Awesome- exactly what I was looking for, a slick one-liner. Thank you!
7  Server Scripting / PHP / Re: Easy way to de-dupe a large list? on: Apr 08, 2011, 02:02:28 pm
Here's a sample:
8  Server Scripting / PHP / Easy way to de-dupe a large list? on: Apr 07, 2011, 07:33:10 pm
I've got a list of about 50,000 lines of items, some of which are probably (read: definitely) duplicates. I'd like to de-dupe them either with PHP or possibly a bash script...anyone have any snippets to do this efficiently?

(Yes, I could write a small script to do this but my guess is that some has a nifty snippet already tucked away somewhere, and it's probably smarter and faster than what I'd churn out.)
9  Server Scripting / PHP / Re: mysql_real_unescape_string ? on: Apr 06, 2011, 07:17:29 pm
You could use stripslashes() on the affected fields. I think using 'SELECT REPLACE...' would remove all slashes, including any that are supposed to be there.

I have some strings that I used mysql_real_escape_string on prior to putting them in the database and now ... needless to say ... they're coming out with backslashes  ...

I resorted to the following:

SELECT REPLACE ( `field`,"\","" ) AS `field` FROM `table`;

am I missing a better solution?
10  Security & Performance / Security Issues / "Lizamoon" attack hits millions of sites on: Apr 01, 2011, 03:31:30 pm
FYI, not an April Fools joke.

PC World - Hundreds of thousands -- possibly millions -- of websites have been hit with a cyberattack that some are calling "one of the biggest mass-injection attacks we've ever seen."

The attack was discovered on March 29 by security firm WebSense, and the injected domain was called -- thus, the name of the mass-injection is "LizaMoon." According to WebSense, LizaMoon uses SQL Injection to add malicious script to compromised sites. While the first injected domain was, additional URLs have since been injected in the attack (WebSense has a full list here).

Visitors to various "lizamoon" addresses are greeted with bogus warnings that their computers have been compromised, according to Websense.

The exploit appears to inject code into the "title" attribute, judging by the images and code samples.
11  General Category / General Discussion & Chit Chat / IT World: Apple to buy Redhat? on: Apr 01, 2011, 07:48:09 am
April Fools Smiley lol
12  General Category / General Discussion & Chit Chat / Microsoft to Release VISTA source code for development on: Apr 01, 2011, 07:41:47 am
Just Kidding - April Fools! Smiley
13  Security & Performance / Security Issues / Re: Sanitizing email form on: Mar 29, 2011, 10:43:22 pm
There are two things I'm aware of that might work:

1) HTMLawed

2) Configurable Sanitizer

There are other general sanitizer functions out there as well, like this:

I've no idea how good that is, but it might be a place to start.

It's not just an email field, it's all sorts of fields (text, textarea). I just wanted to use something generic, but I like the no special chars suggestion too.
14  Security & Performance / Security Issues / Re: Sanitizing email form on: Mar 29, 2011, 12:16:23 pm
I would also disallow any characters that aren't "legal" in the various fields.

As per the spec, an email address can only contain letters, numbers, dashes, underscores, periods, the ampersand (@) and "+" signs. Technically they can contain spaces but I don't allow them in my forms (no one really seems to use spaces in email addresses, even though they're technically allowed by the RFC).  There are a few other characters that are "sort of" permitted, but they're more or less disallowed by everyone these days:

I'm creating an email form, and the fields are subject to change depending on needs and I was hoping to create a basic function that I could reuse in several places to easily sanitize everything without having to specify exact names of the fields... Is there any problem if I use something like this?

function sanitize_input($content){
$content str_replace("\\r","",$content);
$content str_replace("\\n","",$content);
$content str_replace("Content-Type:","",$content);

$_POST as $key=>$value){
$_POST[$key] = sanitize_input($value);

$_POST as $key=>$value){
$key.": ".$value."<br>";

It seems to do what I want and that is strip out any carriage returns or attempts to change the content type, but security has never really been my thing and I've had forms exploited before so I figured I'd ask first...
15  Browser Scripting / CSS / Pure CSS GUI Icons on: Mar 29, 2011, 08:07:26 am
This is so slick:

Pseudo-elements used to create simple GUI icons using CSS and semantic HTML- no image files at all.

The HTML is a basic unordered list of links:
Highlight Mode: (HTML)
  1.   <li class="power"><a href="#non">Power</a></li>
  2.   <li class="play"><a href="#non">Play</a></li>
  3.   <li class="stop"><a href="#non">Stop</a></li>
  4.   <li class="pause"><a href="#non">Pause</a></li>

Each icon uses its own set of styles. For example, the key parts of the CSS responsible for the “expand” icon are as follows:
Highlight Mode: (CSS)
  1. .expand a:before {
  2.   content:"";
  3.   position:absolute;
  4.   top:50%;
  5.   left:1px;
  6.   width:5px;
  7.   height:0;
  8.   border-width:7px 7px 0;
  9.   border-style:solid;
  10.   border-color:transparent #c55500;
  11.   margin-top:-4px;
  12.   /* css3 */
  13.   -webkit-transform:rotate(-45deg);
  14.   -moz-transform:rotate(-45deg);
  15.   -o-transform:rotate(-45deg);
  16.   transform:rotate(-45deg);
  17. }
  19. .expand a:after {
  20.   content:"";
  21.   position:absolute;
  22.   top:50%;
  23.   left:5px;
  24.   width:8px;
  25.   height:8px;
  26.   border-width:3px 0 0 3px;
  27.   border-style:solid;
  28.   border-color:#c55500;
  29.   margin-top:-6px;
  30. }
  32. .expand a:hover:before,
  33. .expand a:focus:before,
  34. .expand a:active:before {
  35.   border-color:transparent #730800;
  36. }
  38. .expand a:hover:after,
  39. .expand a:focus:after,
  40. .expand a:active:after {
  41.   border-color:#730800;
  42. }
16  General Category / General Discussion & Chit Chat / Carnegie Mellon University dumps object-oriented programming on: Mar 26, 2011, 10:53:55 am
According to this blog post from professor Robert Harper, the Carnegie Mellon University Computer Science department is removing the required study of object-oriented programming from the Freshman curriculum.

'Object-oriented programming is eliminated entirely from the introductory curriculum, because it is both anti-modular and anti-parallel by its very nature, and hence unsuitable for a modern CS curriculum.' It goes on to say that 'a proposed new course on object-oriented design methodology will be offered at the sophomore level for those students who wish to study this topic.'

I've never been a fan of object-oriented programming, but that's just me. In many of the instances I've seen it used it's 1) unnecessary, 2) complicates the code for no reason, and 3) often appeared to be done just because the author learned object-oriented programming and decided that everything in the world should therefore be coded in in an object-oriented style.
17  Server Scripting / PHP / Using mail() on certain hosts on: Mar 26, 2011, 08:55:45 am
I recently acquired a new Debian server and started running into issues with mail(). I found a *LOT* of my outgoing emails sent with the mail() command were being rejected by Yahoo, Hotmail, Comcast, Verizon, etc (and even to my own servers!). The error message in the returned mail was always along the lines of "Sender address rejected", and the sender address was showing up as something like "", even though it was being set explicitly in the mail() header string.

"vu2035" is the name of the virtual user under Debian, and "" was, of course, the server itself.

The "cure" for this was simple: use the '-f' command line parameter to set the "from" address, which for some reason wasn't being set properly by PHP running under Debian.

Highlight Mode: (PHP)
  1. $to = '';
  2. $headers = '';
  3. $subject = "Sample email subject";
  4. $message = "Sample message text";
  5. $headers = "From:\r\n";
  6. // send email
  7. mail($to,$subject,$message,$headers);

Highlight Mode: (PHP)
  1. $to = '';
  2. $headers = '';
  3. $subject = "Sample email subject";
  4. $message = "Sample message text";
  5. $headers = "From:\r\n";
  6. // send email
  7. mail($to,$subject,$message,$headers, '');

Notice the last line. Some setups allow a space between the '-f' and the email address, some don't.

The php mail() page is filled with caveats about using this parameter, so you may need to experiment a bit:

18  Browser Scripting / CSS / Re: CSS from PHP - why doesn't it work? on: Mar 26, 2011, 08:35:42 am
Good job on finding that. I'd probably have puzzled over this until the Sun burned out.

I found the answer by comparing the headers sent by .js and .css files that didn't run through PHP using FireBug.  I needed to set a the Content-Type header, because the rewrite was causing the Content-Type to be set as "Content-Type   text/html; charset=UTF-8"

Highlight Mode: (PHP)
  1. <?php require_once 'common.php'; ?>
  2. <?php header('Content-Type:text/css; charset=utf-8;') ?>

Worked - for the CSS, and I put it in the js, too.

19  Server Scripting / PHP / Cheesy, sleazy trick - avoid session timeouts on: Mar 24, 2011, 12:30:50 pm
I can't remember where I saw this, but it was so simple and so sleazy I had to copy it in case I might want to use it. Smiley

Basically it's a way to avoid session timeouts without mucking about with the session ini settings or gc_ variables. At the bottom of the page you want to "keep alive", place a small IFRAME and a little bit of javascript, like this:

Highlight Mode: (HTML)
  1. <iframe id="kp" src="/keepalive.php" style="width:1px;height:1px;"></iframe>
  2. <script type="text/javascript">
  3. function keepAlive(){
  4. if(refreshCount <= 1000){
  5. var kp = document.getElementById('kp');
  6. kp.src = kp.src;
  7. setTimeout('keepAlive()',600000);// run every xxxx milliseconds
  8. // inc the refresh counter
  9. refreshCount++;
  10. }
  11. }
  13. keepAlive();

On the server, place this code in "keepalive.php":

Highlight Mode: (PHP)
  1. <?php
  2. print date('Y-m-d G:i:s');
  3. ?>

The javascript will run every xxxx milliseconds (every 10 minutes in the example above) and refresh the IFRAME. This will run "keepalive.php" on the server and refresh the session (it also prints the time and date to the IFRAME page, but that's hidden by the IFRAME's CSS).

The "if(refreshCount <= 1000){ " line in the javascript can be used to eventually timeout the session by preventing the IFRAME from refreshing after whatever count you want (and since the number can be changed dynamically, it could also be used as a user-settable configuration parameter).

Again, this is so sleazy that I laughed when I first saw it, but after looking at it I decided that it was actually a crude but valid solution to a session time out problem. Elegant? Not terribly, but it works and honestly I can't find anything that's really "wrong" with it.
20  Browser Scripting / CSS / Re: CSS from PHP - why doesn't it work? on: Mar 23, 2011, 10:30:18 am
Could be quite a number of reasons...

How are you delivering it to the browser?
Is it within <style> tags?
Does the CSS validate properly?

I'm using PHP to compose some CSS.  It's created correctly, and delivered to the browser, but it isn't taking effect.

What's wrong?

Pages: 1 2 3 4