digital-ether 399 Nearly a Posting Virtuoso Team Colleague

i have a form.. i validated it..
if the form has an empty field, instead of popping up an alert box, i need to display a message that goes off say after 5 seconds..
any idea of how to do it?

You can create or display and HTML Element, that has the message.

Example of creating one:

var msg  = documement.createElement('div');
msg.innerHTML = 'Your message';

Then attach that div to whatever element you want it to display on:

eg:

HTML:

<p class="field">
<label for="form-field-id">Label</label>
<input id="form-field-id" name="form-field-id" />
</p>
// create message element
var msg  = documement.createElement('div');
msg.innerHTML = 'Your message';
// attach it to the DOM
var field = document.getElementById('form-field-id');
field.parentNode.appendChild(msg);

That would append it as a child of <p class="field"> which is the parentNode of <input id="form-field-id" name="form-field-id" />.

To remove it you set a timer.

clearTimeout(timer);
timer = setTimeout(function() {
msg.parentNode.removeChild(msg);
}, 5000);
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Most find that speed is not the issue
post is better for some purposes, get for others
this discussion may help
http://stackoverflow.com/questions/1211881/why-get-method-is-faster-than-post

Something not mentioned on that link is that POST requests are not cached. GET requests are, and thus reduce the load on your server. Subsequent requests using GET will appear much faster, since the request will actually be taken mostly from the browsers cache, and or intermediate HTTP caches. So for anything that doesn't modify data on your server, use a GET. If you want the data to never be cached, use post.

darkagn commented: I didn't know that, but it makes sense. +6
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Here is an interesting page that could be used to create a password strength meter:

http://www.lockdown.co.uk/?pg=combi

kvprajapati commented: Informative page. +4
Salem commented: Nice +36
Nick Evan commented: Cool page! +20
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Yes, is is possible with wordpress. You can create custom pages with the funcitonality you want, through an extension.

I suppose you could yes, you would need to play a little with the configuration. When I say a little I mean you would have to literally rewrite allot of how wordpress work.

Also I have had my shared hosting accout hacked via a loop hole in WordPress, so I wouldn't advise you to use WordPress at all.

Josh, I wouldn't write wordpress off because it got hacked in shared hosting.

Shared hosting is usually more of the problem then the software installed on it.

Almost every account on shared hosting can be hacked, even if you use strict security measures.

ie: PHP usually runs as the same user on a single machine on shared hosting. So it can write to any file that it created, even on a different accounts.

If PHP can write to it, then anyone on the machine can write to it. It is the same for any running process on a shared host.

So when you're on a shared host, no matter how well you secure your site, if a single other site on that machine is vulnerable, your site is.

mr.khurrams commented: Thanks, too Good +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Im pretty sure my hosting is LINUX but I run WINDOWS. But I use windows to access both not linux. So I think I would need to know how to install it on windows first and then contact me web host about installing it on the server? or if i just need to install it on the root I can do that myself as I have access. But that still leaves how to install on windows as it only has linux instructions.

Thanks

On windows you just have to download one of the windows binaries. Here is the link again to an unofficial windows builds:

http://ffmpeg.arrozcru.org/builds/

For example, the latest build they have right now is:

http://ffmpeg.arrozcru.org/builds/bin/ffmpeg-latest.tar.bz2

Download that. Then uncompress it on your computer. This will give you an .exe file. Basicaly you're done.

To use it, you just need to open the command prompt:
Start -> All programs -> accessories -> command prompt

In the command prompt type in the full path to the ffmpeg.exe file you extracted.

eg: c:\downloads\ffmpeg.exe

This should give you some info on ffmpeg if you did it right.

For convenience, you want to put the path to that exec file in your windows system path. This is a list of folders that windows will look for commands.

Just search "edit windows system path" and you should have lots of tutorials on how to do that.

Once in …

OmniX commented: Thanks for the instructions! +3
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

It really doesn't matter since mysql_fetch_assoc() will evaluate to false if there are 0 rows, therefore the while loop will not run. No server should have errors with that basic code.

True, there should be no problems with the while() loop.

It is good to note that if you use foreach() or for() iterators you should always check the type before iterating.

This isn't required in a while because while automatically converts all types to Boolean. So it can handle multiple types (both the Array and Boolean false). Iterators cannot.

The same code in a foreach() loop would get errors.

eg:

foreach($results as $result) {}

If $results is not an Array, it will give an error.

for($i = 0; $i < count($results); $i++) {}

If results is not an array, count will give you 1, even count(FALSE) is 1.

Correct way:

if (is_array($results)) {
foreach($results as $result) {}
}

I hardly see this used however. Instead is seems the common alternative used is:

if ($results) {
foreach($results as $result) {}
}

This works however if the results will always be false, or an Array. I'm sure a type check is faster then boolean conversion anyway.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Here is a bit on uploading files in PHP:
http://www.php.net/manual/en/features.file-upload.post-method.php

You can convert the file to flv after uploading using FFMPEG and FLVTool2 for the metadata.
FFMPEG-PHP can help with this: http://ffmpeg-php.sourceforge.net/

It's probably easier to use FFMPEG and FLVTool2 in the command line first and when you're successful, try doing it from PHP with exec().

The tutorial given previously explains this well.

You'll need root access to install FFMPEG and FLVTool2. If you don't have this, you could probably get away with uploading the video file to a site such as google video or youtube, and then downloading the converted FLV through their API.

Basically there are 2 ways of streaming the FLV to the flash player.

1) using HTTP
2) using a streaming protocols such as RTMP (Real Time Messaging Protocol)

http://en.wikipedia.org/wiki/Flash_Video#Delivery_options

Using RTMP requires a streaming server, such as Red5 (open source).

If you won't want to use a special server, just using your HTTP server would allow you to progressively download the FLV without any special setup. Just giving your choice of flash player (eg: http://www.longtailvideo.com/players/jw-flv-player/) the URL of the flv and it should "stream". The only thing it won't be able to do is seek (seek to a position not yet downloaded).

You can stream the FLV, and allow seeking using HTTP by having PHP control the HTTP stream:

OmniX commented: Very useful and informative post, Thankyou! +3
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi, I'm making a site security tester which is basically a bot that scans a selected website for any php security holes such as sql injections then reports them to the user. I have managed to write the bot and all but the last piece left is the function that actually tests each individual page for security holes. The function that starts testing each individual page is as follows:

generate($url) {
$data=file_get_contents($url);
//now to do some tests on the page
}

As you can see, this function will be used on each and every valid url inside the website to perform tests on. But my question is, how do I test for php security holes and what security holes are possible?
I read something about if ;ls -la is placed in the url and not filtered it can display the contents of a web directory. But what would file_get_contents return if that is the case?

This is also an open source project so just let me know if you want the full code.

;ls -la is a linux shell command. The first part, ; is a command delimiter.

So if that were passed to the linux shell, it would first delimit any previous command, and then call the command ls -la

The -la option basically lists all files in the directory including hidden files (those preceded with .) and shows full information about them.

So ;ls -la would be an exploit against any php code that executes …

darkagn commented: very informative post +4
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

i guess you could use ctype_space() function for more details refer to php manual http://in.php.net/manual/en/function.ctype-space.php

ctype_space seems to check if the string is composed of all spaces.

I think the function to use would be ctype_graph.
http://in.php.net/manual/en/function.ctype-graph.php

This makes sure all characters are printable, and do not create whitespace.

So if the string contains space (\n) or tab (\n) or line breaks (\n) and (\r\n) on Win, then it will return false.

In addition to the regex examples posted:

if (preg_match('#\s+#', $username))
{
[error notification here]
}

You could also use strpos() and stristr().

eg:

if (strpos($string, ' ') !== false) {
// there is a space somewhere
}

http://in.php.net/manual/en/function.strpos.php

It would be faster then using regex.

darkagn commented: great tips +4
digital-ether 399 Nearly a Posting Virtuoso Team Colleague
newDiv.innerHTML = '<input type="file" name="' + divIDName + '" size="57"> <a href="#" onclick="removeAdditionalFile(this.parentNode, this.count)">Remove</a>';

this.count would refer to the count property of the link (a element).

I don't think this is what is intended. Maybe:

newDiv.innerHTML = '<input type="file" name="' + divIDName + '" size="57"> <a href="#" onclick="removeAdditionalFile(this.parentNode, '+count+')">Remove</a>';
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hello fellow developers

I have a site project I've just acquired for a quick repair and I have problem with the url string being truncated because of the "#".

What I mean by that is if I have a url string with a nave/value pair: deviceNane= AjaxText #2 only the AjaxTest part of the name would show as part of the url string. I tried to put the value in a single or double quotes but still will not work.

Is there a method that I can use to allow the name to be pass on clean?

Take a look at the window.location object:
https://developer.mozilla.org/en/DOM/window.location

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Ok. I have used exec() to run a php file. I know it curently runs. exec('php /var/www/html/public/TEST/SwiftSleep/run.php &') 1. How do i know that it runs?
2. How do i stop it?

Can i create a php file and run it on my localhost and see?

Thanks

What you want is called IPC (Inter Process Communication).
http://en.wikipedia.org/wiki/Inter-process_communication

This is why it is better to write a deamon (start a child process) using PHP itself without a system call (ie: exec()). That way, you can use the IPC provided by the system, that allows parent and child processes to talk to each other.

Since you're using exec(), you'll have to use another medium to communicate. This can either by files, or sockets or anything you can both read and write from.

The file is probably the easiest. Just have your /var/www/html/public/TEST/SwiftSleep/run.php write a file, and have your "parent" php script read from that file to know how the "child" is doing.

btw: starting a child process is quite simple:

You need the pcntl extension however.

eg:

// this forks the current process
// which means a child process is created, that is a clone of the current one
// so everything defined and executed in this process, will be cloned to child
$pid = pcntl_fork();

// the returned PID signifies which process we are in
// note that from now on everything will be run twice
// once in the parent process, …
nav33n commented: Your posts are always so informative. +10
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi digital,

Is there any examples to run a cron job under ubuntu 8 because, i can't do it, although i have tried a lot of different examples?

thanks

Are you trying to just input this yourself from the command line or want PHP to do it?

see: http://www.unixgeeks.org/security/newbie/unix/cron-1.html

Basically you need to use: crontab -e

This brings up the default editor, and allows you to edit your user's crontab file.

The syntax:

Now for the more complicated second part of a crontab file.
An entry in cron is made up of a series of fields, much like the /etc/passwd
file is, but in the crontab they are separated by a space. There are normally
seven fields in one entry. The fields are:

minute hour dom month dow user cmd

minute This controls what minute of the hour the command will run on,
and is between '0' and '59'
hour This controls what hour the command will run on, and is specified in
the 24 hour clock, values must be between 0 and 23 (0 is midnight)
dom This is the Day of Month, that you want the command run on, e.g. to
run a command on the 19th of each month, the dom would be 19.
month This is the month a specified command will run on, it may be specified
numerically (0-12), or as the name of the month (e.g. May)
dow This is the …

darkagn commented: Very good explanation of cron +3
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Just to clear things up:

Is there php function to remove the space inside the string? for example:
$abcd="this is a test"
I want to get the string:
$abcd="thisisatest"

How to do that? thanks.

str_replace() will remove *all* occurrence of whitespace.

$str = str_replace(' ', '', $str);

So it solves the problem in the original post.

The post:

Try this:
NOTE: this actually leaves one space between words. If you move the
$newstr = $newstr . substr($s, $i, 1);
after the while loop it will strip all spaces as you wanted.

function StripExtraSpace($s)
{
for($i = 0; $i < strlen($s); $i++)
{
$newstr = $newstr . substr($s, $i, 1);
if(substr($s, $i, 1) == ' ')
while(substr($s, $i + 1, 1) == ' ')
$i++;
}
return $newstr;
}

Offers a solution that removes excess whitespace.

So if you want to turn:

$str = "this     is      a     string     with      excess     whitespace";

into:

"this is a string with excess whitespace";

You could use the StripExtraSpace() function provided above.

For starters, functions in loops should be avoided whenever possible. e.g. for($i = 0; $i < strlen($s); $i++) also, you're doing a lot of extra work here.

I would suggest something like this:

<?php

$sTestString = 'This  is a stringwith    lots of 	odd spaces and tabs		
and some newlines too

lets see if this works.';

$sPattern = '/\s*/m'; 
$sReplace = '';

echo $sTestString .
nav33n commented: Good post.. +10
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Regular expressions are quite simple.

Instead of matching exact characters like in your str_replace() you match patterns.

The pattern is held in two delimiters, denoting the start and end of the pattern. The delimiter has to be non-alphanumeric.
After the end delimiter, you have the modifiers (flags).

So a regular expression could be:

|a|

That matches just the letter a. The delimiter is |.

Another example:

|ape|i

This matches the sequence of characters "ape". The "i" after the second delimiter is a modifier that means the match is case-insensitive. So "ape" can be in any case: eg: "aPE" would be a match.

There are special characters used to match patterns. The most used is the fullstop. "."

The fullstop matches any single character.

So:

|a.e|i

Would match "aPE" as well as "abe" etc.

The other two most used characters are * and +.

* means 0 or more of the character to the left of it.
+ means 1 or more of the character to the left of it.

eg:

|a.*e|i

this would match "appe" or even "ae" since we can match 0 or more of ".". Since . is any character, it can be 0 or more of any character between a and e.

This is just the fundamentals, Regex is very powerful. Take a look at:

http://www.regular-expressions.info/

it has a lot of information …

humbug commented: Good idea explaining the fundamentals +4
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Ok, I think I'm beginning to understand this better. Thanks a lot for the explanation darkagn. I really appreciate it ;)

Abstract classes can also be used to hide complex code, while still being extensible.

Say implementing the Animal class was quite involved and complex, now someone who didn't know about Animals wanted to use the features of Animals but didn't want to go into the gory details could use it to model a Reptile with limited knowledge. (A better example would be, if you wanted to download email, but didn't want to go into the details of the POP3 or IMAP protocol, you could use an abstract POP3 class)

A good model of relationships:
If Reptile extends Animal, then you know an Animal is more general then a Reptile. These make it easier to make sense of the relationships in a bunch of code.

A way of defining interfaces, guides or structure
If there is an Animal abstract class, then all types of animals must extend the animal class to also be animals. This gives a single interface within a PHP application. A real example would be a abstract Storage class providing an interface for Databases, Sessions, File storage etc. Down the chain, the Database class could be abstract also for the different Database types (mysql, sqlite, flat file, etc.). This provides a level of control, structure and order within the app and is also used as a base to implement other programming patterns …

darkagn commented: All good points :) +3
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi,
I want to search data using Ajax php without pressing on search button.

How to do that??

any script or link demo or sample code ???

i want do this search like orkut search means design ??

plz help me??

You'll need to know a bit of JavaScript.

Basically, on each type of a few characters into the search input, you send the search to the server, and load the results.

eg: HTML

<input id="search_input" />
<div id="results"></div>

eg: JS

<script>
window.onload = function() {
  var inputbox = document.getElementById('search_input');
  inputbox.onkeyup = function(e) {
    e = e || window.event;
    keycode = e.keyCode || e.which;
    if (keycode == 13 || this.value.length%3 == 0) {
      doSearch(this.value);
      return;
    }
  }
};

</script>

Explanation:

<input id="search_input" />

is our search inputbox. It is a DOM element, which allows JavaScript to attach event listeners to it.

window.onload = function() {
// ...
};

In the javascript we first attach an event listener to the window Object, to listen for the onload event. The onload event fires when the browser completely loads the page.

window.onload = function() {
  var inputbox = document.getElementById('search_input');
  inputbox.onkeyup = function(e) {
    // ...
  }
};

Then in the window onload, we attach an onkeyup event listener to the search inputbox. We do this after the window has loaded to make sure the inputbox has been loaded.

inputbox.onkeyup = function(e) {
    e = e || window.event;
    keycode = e.keyCode || e.which;
jrdark13 commented: great information +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

See also the <button> tag. It has better support for this as it allows a label different from the value attribute.

http://www.w3.org/TR/html401/interact/forms.html#h-17.5


eg:

<button name="action" value="update">Update Cart</button>
<button name="action" value="checkout">Checkout Now!</button>

With <input> you have to use the value attribute as the label. This makes the server side code dependent on a display item, rather then data/logic (Your model is dependent on the view if worded in the MVC pattern/paradigm) not the best thing.

eg:

If you wanted the checkout button to read "Checkout Now", you'd need to change the server side code to test the value to be "Checkout Now" if you use an <input>.
If you use <button>, you can rename the visual aspect, while keeping the controller logic the same.

ps: you could always make the dependency a variable that PHP will understand and write to HTML as well: eg:

define('checkout_label', 'Checkout Now');

if ($_POST['action'] = checkout_label) {
  require('checkout.php');
}

but I still think <button> is better.

peter_budo commented: Nice examples +10
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

i have passed multiple identical id values, and now i want to retrieve those corresponding id values in mysql. how do i retrieve them? the table that the ids were inserted is a join table named hrm1_employees with field names hrmemp1Id, empId, and hrm1Id. the field hrm1Id came from the table hrm1, and empId from table employees, each with ids corresponding to their fields (e.g. empId corresponds to the employees Fname, Lname, etc).

question is how do i retrieve the Fname and Lname and projtitle of the ids.
heres my code:

<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "smportal";


	//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
	//Select Database
mysql_select_db($dbname) or die(mysql_error());
$y=mysql_query("SELECT * FROM hrm1, employee, hrm1_employees WHERE hrm1.hrm1id = hrm1_employees.hrm1id and employee.empId = hrm1_employees.empId");

$display_string = "<table border='2' cellpadding='3'>";
$display_string .= "<tr>";
$display_string .= "<th>Project Title</th>";
$display_string .= "<th>Employees</th>";
    //loop here
	$display_string .= "<td>$row[projTitle]</td>";
		$display_string .= "<tr>";
   while($row = mysql_fetch_array($y))

    {

    //inside while



	$display_string .= "<td>$row[Fname]</td>";
		$display_string .= "</tr>";
	}
	echo $display_string;
	?>

this code is suppose to display the project title once, and the employees Fname multiple times. as the relationship of project to employees is one to many.
can't figure out the code >.< please help

p.s. i am able to pass the correct id properly, i just don't know how to retrieve them, which in this case, the code above is responsible for.

If I follow correctly, the result of the query should give something like:

ProjectTitle, Fname, Lname
-------------------------------
project1,
fortiz147 commented: thank you very much for your help! very nice professional approach to the problem! +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I want to know what are the usages of $_SERVER and $_ENV in php. Or for what they can be used.

Both $_SERVER and $_ENV give you information on the environment your PHP script is running in.

$_SERVER is an array of useful information about the server, and HTTP Request.

An example use is in constructing the full HTTP Request made to the server as this class does:
http://www.daniweb.com/code/snippet616.html

Another use would be to get the clients, IP address:

echo $_SERVER['REMOTE_ADDR'];

$_ENV contains information about the environment in which the PHP parser is running.
It would probably be more appropriate when running PHP as a shell script under the Command Line (CLI).

How they differ is in that $_SERVER presents information assuming PHP was invoked as a webpage, and thus has info on the HTTP request, and the server environment. (which is the most common use of PHP)
$_ENV is a bit more generic, and the information in it would be dependent on the shell that the PHP parser was executing under.

Try doing a var_dump($_SERVER) and a var_dump($_ENV); in your PHP script to see the actual values they contain when your script executes. If you have shell access to the server running your PHP then try executing the php script from the command line to see how it differs.

architact commented: Awesome, really Impressed with her knowledge. +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi!
It's really a silly question, but i've tried many ways to do it and it's still worthless.... :(
I have a form:

<form action="jobapp.php" method="POST" name="app">
	
	Please, enter your name:
	<input type="text" name="applicant" /><br />
	Please, enter your telephone number:
	<input type="text" name="telephone" /><br />
	Please, enter your e-mail address:
	<input type="text" name="email" />
	</form><br /><br />

and the awful problem is that i just can't make the entered values to be displayed.
I would really appreciate, if you could help me!!!! :$

In your PHP file jobapp.php, you will receive the values entered in the form in the variable $_POST, since the the form method is "POST".

Long explanation:
When a user submits the form, the browser will send a HTTP Request to your server, with the values of the form in the HTTP Request. The HTTP Request will be a POST request, in url encoded format. The PHP server on receiving this request will decode the url encoded values, and generate the PHP Array $_POST, which these values.

To view the POST data, just retrieve them from the $_POST array.

You can dump all the values of the $_POST array just to see whats happening:

var_dump($_POST);

or you can access an individual value:

echo $_POST['applicant'];
nav33n commented: very nice explanation! +8
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Just a note on this:

When you place user input into an SQL query, always make sure you escape it for SQL injections (used hack into your database). For Strings you can use mysql_real_escape_string() or mysql_escape_string() depending on support for it. If its an integer, then just use intval().

eg:

mysql_query("update table2 set col2 = ( Select col1 from table1 where col3 = '".mysql_real_escape_string($_POST['Tests'])."') where ID = '".intval($_POST['ID'])."'") or mysql_error();

In mysql, the Integer fields can be treated as strings, but for portability its good to not have qoutes around field values that are integers as it would most likely not work on other SQL databases.

Also, its good to optimize the queries. A simple optimization is to use the LIMIT keyword.

mysql_query("update table2 set col2 = ( Select col1 from table1 where col3 = '".mysql_real_escape_string($_POST['Tests'])."' LIMIT 1) where ID = ".intval($_POST['ID'])." LIMIT 1") or mysql_error();

On large datasets LIMIT can really speed up the query. What happens is the database does not have to go through its whole index, but instead stop on the first result that matches the WHERE portion of the query.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

A typo there:

if (expandable.style.display = 'none') {

should be:

if (expandable.style.display == 'none') {

Thanks for spotting that.

I didn't mention in my post, but the javascript should be executed after the DOM is loaded. This is normally implied if you're familiar with DOM scripting but it I can remember times when I'd spend hours trying to figure out what was going wrong and the case was that the DOM was not fully loaded. So here is what a full working example would look like.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<title>Expand a Table via DOM and Style property</title>
		<script type="text/javascript">
			window.onload = function() {
				var table = document.getElementById('expandable_table');
				if (table) {
					var trs = table.getElementsByTagName('tr');
					for(var i = 0; i < trs.length; i++) {
						var a = trs[i].getElementsByTagName('td')[0].getElementsByTagName('a')[0];
						a.onclick = function() {
							var span = this.parentNode.getElementsByTagName('span')[0];
							span.style.display = span.style.display == 'none' ? 'block' : 'none';
							this.firstChild.nodeValue = span.style.display == 'none' ? 'More' : 'Less';
						};
					}
				}
			};
		</script>
	</head>
	<body>
		
		<h2>Expandable Table</h2>
		<table id="expandable_table">
			<tbody>
				<tr><td>TD 1 <a href="#">More</a><span style="display:none;">TD 1 Extended Description</span></td></tr>
				<tr><td>TD 2 <a href="#">More</a><span style="display:none;">TD 2 Extended Description</span></td></tr>
				<tr><td>TD 3 <a href="#">More</a><span style="display:none;">TD 3 Extended Description</span></td></tr>
				<tr><td>TD 4 <a href="#">More</a><span style="display:none;">TD 4 Extended Description</span></td></tr>
			</tbody>
		</table>
		
	</body>
</html>
~s.o.s~ commented: The kind of effort put by you in helping out beginners is praiseworthy. +22
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

The function getvar() has the function trim(). trim() operates on a string, and thus will try to convert any parameter it receives to a string. If you therefore pass it an array, it will give you the array to string conversion error.

PHP will cast types depending on the context. If the context requires a string, then it casts the variable to a string. An example of this when you put together strings.

eg:

$age = 100; // int

// $age is cast to a string
$string = 'Jack is '.$age.' years old';

$age = '100'; // string

// age will be cast to an int
$string = 'Joe is '.($age - 1).' years old';

Even though 100 is an integer. It will be cast to a string due to the context it is used in (string concatenation). In the second example, $age will be cast to an int.

The solution to the problem is to make sure you don't pass anything but a string to getvar() or change getvar() to cater for arrays...

dottomm commented: Thanks +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

i have changed the code now so that it uses the path to the iage but the problem i am having now is that if the file extension is not the same then it will not overwrite the image. how can i get it to delete the image no matter if it is jpg, gif, png.

the code i am using now looks like this i have added a bit to delete both copies of the image (original and thumbnail).

$fileToRemove = '/home/acme/public_html/image/thumbs/thumb_image1';
				if (file_exists($fileToRemove)) {
   					// yes the file does exist
  					 unlink($fileToRemove);
				} else {
   						// the file is not found, do something about it???
				}
				
				$fileToRemove = '/home/acme/public_html/image/image1';
				if (file_exists($fileToRemove)) {
   					// yes the file does exist
  					 unlink($fileToRemove);
				} else {
   						// the file is not found, do something about it???
				}

i need some code to go on the end of the filetoremove line to it checks for all file extension or just delets it by name without the extionsion getting looked at.

The short way of doing this would be:

if (@unlink($fileToRemove)'.jpg' || @unlink($fileToRemove).'.png' || @unlink($fileToRemove).'.gif') {
// unlinked successfully
}

This just tries each one in succession and suppresses errors. This if the reason for the @ sign before the function calls.

It would probably be better to use a loop though, and check for file existence and permissions.

eg:

$exts = array('jpg', 'png', 'gif', 'jpeg');
foreach($exts as $ext) {

   if (file_exists($fileToRemove.'.'.$ext)) {
     if (!is_writable($fileToRemove.'.'.$ext) {
        @chmod(0777, $fileToRemove.'.'.$ext);
     }
     @unlink($fileToRemove);
   }

}

or something similar...

kevin wood commented: very helpful and knows what she is talking about +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

excellent.. looks very useful..

I did what you suggested and removed unneccesary <html> tags from the sub pages. I agree that this is definitly good practice - double code can't be good..

However, I think I have discovered the source of my problem here. It looks like the swfobject.js is causing IE to cancel viewing the pages. This is pretty crucial, since it is the script for the music player!

Debugging, it says :

Warning 5002 variable "key" already defined
The variable name was already used inside this function.

Warning 5006 exception handling is not supported in some browsers
Internet Explorer 5.0 and later implements exception handling, but Netscape 4.7 and earlier does not.

Warning 5002 variable "axo" already defined
The variable name was already used inside this function.

these errors are duplicated a couple of times, but all refer to line 8 in swfobject.js

A similar error is found (only when debugging in IE - again, firefox is fine) in the fade.js, which is a text effect (hover over red, then fades back to white) - it says :

Warning 5002 variable "i" already defined
The variable name was already used inside this function.

referring to lines 118 and 143.

The annoying thing is that these two scripts have been taken from reputable javascript source websites.

I could remove these scripts from the website, but this would be really detrimental to the design and sound of the site..

Any …

peter_budo commented: Nicely done +7
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

You can have JavaScript save cookies. This is done immediately, so page reloads are not needed.

Example JS:

/**
* Set a cookie
* @param string cookie name
* @param string cookie value
* @param string cookie expiration counter in days
* @param string cookie path
* @param string cookie domain
* @param bool secure?
*/
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) +
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

/**
* Get a cookie value
* @param string cookie name
*/
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

/**
* Remebers form inputs after you fill them in
* @param string ID …
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I don't think you can use is_int() since all HTTP data is considered strings. There is no type distinction in HTML FORMS or HTTP GET/POST responses.

You could check for range:

if ($var > 0 && $var < 100) {

}

Or you can use something like:

if (intval($var) > 0) {}

this would make strings equal to 0. So would work unless you also wanted to test specifically for 0.

if (intval($var) > 0 || $var === '0') {}

if anything, you could revert to using regex. But for simple tests I wouldn't invoke Regex as its a pretty heavy application for such a simple task.

I'm sure there is a simple solution to your problem.

OmniX commented: Thanks for the helpful advice =) +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Is there an error you're getting? I don't see any particular problem in the code.

Normally, you'd want to have a database do this job for you. It is much simpler than having to read/write from files.

For example, with a DB it is as simple as:

$result = $Db->Query("DELETE FROM `table` WHERE `column` = '".mysql_real_escape_string($_GET["file"])
."' LIMIT 1";

The database then does basically what you are doing with the files, on the disk or memory depending on the storage type being used. Databases are very efficient at this though by design.

Your code is very good for file updates as it is very memory efficient. If you are working with small files, you could save time by doing something like:

// retrieve file into a string
$txt = file_get_contents('toApprove.txt');
// replace the line with $_GET["file"], assuming line break is \n
$txt = str_replace(trim($_GET["file"])."\n", '', $txt);
// write the string back to the file
file_put_contents('toApprove.txt', $txt);

or

// retrieve the file into an array where each line is a value
$Array = file('toApprove.txt');
// assuming unique values, lets remove the Array key with value $_GET["file"]
unset($Array[array_search(trim($_GET["file"]), $Array)]);
// explode the array into string with line breaks seperation and put everthing back in the file
file_put_contents('toApprove.txt', implode("\n", $Array));

It is much simpler, however, is memory intensive if you have a large file since you will be saving the whole file contents to a variable, $txt (PHP memory).
file_get_contents() should be more efficient than using fopen() and fgets() …

nav33n commented: Nice info.. +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Is it possible to include the character < in a regular expression? I don't seem to be able to find a reference to it anywhere and am unable to build a regex with just this one character.

Yes, there is nothing special about the < character.

eg:

preg_match("/</", "<div>some text</div>", $matches);

Is there a specific way you're using <?

The most common use in PHP is:

preg_match("/<(.*?)>/", "<div>some text</div>", $matches);

which matches: <div> and </div>.

Taffd commented: Specific and to the point. Helped a lot. +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hey Ether
Thanks for the reply. I have already tried that. It works fine.
But i want to do with the usual PDF. Can u sugges how ?

I just successfully installed PDFlib on windows XP running WAMP. Here is the process:

Installing PDFlib on Apache/PHP running on Windows:

Download PDFLib from:
http://www.pdflib.com/download/pdflib-family/pdflib-7/

Here is the direct download for the currently latest version for windows:
http://www.pdflib.com/binaries/PDFlib/701/PDFlib-7.0.1p1-MSWin32-php.zip

Once you have finished downloading, extract the zip file.
In the folder "bind" choose your php version, and open that folder. (php4 or php5)

Inside that folder, you'll have PHP sub versions, choose your sub version. If you don't know the exact PHP version you'ure using, run a php page with <?php phpinfo(); ?> in it. The PHP version will be printed right at the top of the page.

Inside the sub version folder, you'll find the pdflib's .dll file for your php version.

Copy the .dll file and save the copy in your php extensions folder. This folder is defined in php.ini as "extension_dir". So if you don't know what it is on your machine, open php.ini and search for 'extension_dir'.
On my system is was: c://wamp/php/ext/

Now open php.ini and add the extension. The format for this is:

extension=file.dll

where file is the file name of the extension.

eg:

extension=libpdf_php.dll

Now you have to restart apache, and you should have pdflib installed. I tested this …

iamthwee commented: brilliant +12
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

try: http://www.fpdf.org/
doesn't need pdflib in php

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Thanks for the replies but unless there is some way of intercepting between when the customer hits the submit button ('Add to Cart') and when the page submits to itself there is no way of knowing if the reload is from the submit button or a new visitor. I see other web sites are linked to this forum so if you want to have a look at my site go to http://www.biodistributors.com.au/Testing/PriceListFiles/health.php and disable cookies and see what happens when you try to add items to the cart. The idea is that the "view cart' button doesn't show if the cart is empty. What I am developing now is to show the "view cart' button all the time and when a user who has disabled cookies hits it they get the explanation about cookies needing to be set. Before that the page will just reload unchanged.

Ric

You can tell a new visitor on that page because they will be sending a HTTP GET Request. Thus your $_GET will be populated instead of $_POST.

When the submit button is clicked, they you will have a HTTP POST Request. Thus you'll have $_POST populated.
You'll also have

$_POST['submit']; // = 'Add selected items to cart'

This is the value of the submit button.

If you set a cookie (say 'test') on every page like mentioned, then when you get to the point where the "Add to cart" button is clicked, you should either have:

// cookie …
stymiee commented: good post +8
iamthwee commented: excellent I found this really useful :) +11
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Have you included the MIME type header to the .php file so that its treated as xsl?

If not, in your .php file put:

header('Content-Type: text/xml');

see: http://www.dpawson.co.uk/xsl/sect2/mimetypes.html
for others.

make sure you place the header() call before any output is made, or else see ob_start() in the php.net manual. http://php.net/ob_start/

If you would rather use an xsl extension you can use mod_rewrite in apache to have the .xsl resource handled by your .php file.

Dsiembab commented: thanks +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

It is not 100% match for using OCR to read the image right? Plus the image is created which randomly content. Even the attacker collect more than 1000 of images that have been appear on the login, the next image will be probally different from the previous. I guess the robots aren't so effective after all now. Correct me if i am wrong...

The login form is just there for the browser. It is only a "template" to tell the browser how to make the next HTTP Request to the server.
A bot will not need the login form, just the correct details to make the valid HTTP Request.. It only needs to get the CAPTCHA image, see if it can guess it or not. If it thinks OCR has a match, it will then make a login attempt.
So, it is still affective if it downloads many images. If the server can serve 50 000 images a second, then the bot can make 500 login attempts a second based on the OCR being able to guess 1% of those.

dr4g commented: helpful input +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi there,

I've been using PHP and MySql for some time now but I am quite new to Javascript.
I would like to know how it is possible to insert data stored in a MySql database into Javascript code.
For exmple, I am working on a travel guide site and would like to have a Google map for each location that is featured. I want to store the map grid reference for each location in the database and insert that value dynamically into the Google Maps code when a specific location is requested by the user.

Anyone have any ideas how this can be achieved?

Many thanks,

Simon

Your can write some JavaScript variables into the JavaScript code embedded in the HTML Document:

Assume you have a db table called config with the columns: name, value.

<script>

var configs = {}; // config object

<?php

$array = $db->getResultArray('select name, value from configs'); // pseudo funciton that gets database results in an associative array
foreach($array as $name=>$value) {
echo "configs.$name = '$value'\r\n"; // configs.name = 'value';
}


?>

// the rest of your js

// example function
function getConfig(name) {
return configs[name];
}

</script>

The JS empbedded in your HTML document should look like:

<script>

var configs = {}; // config object

configs.name = 'value';
configs.name2 = 'value2';
// etc.. etc...

// the rest of your js

// example function
function getConfig(name) {
return configs[name];
}

</script>

The config object is just a …

~s.o.s~ commented: Nice +23
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I have a website that lists pdf files for downloading, with links to each file.

What I want to do now is design a search page that will look in the folder that contains these docs and search for docs that match a partial name.

I have created search pages for MySQL before - do I have to create a table with file names and links and then do a search of MySQL?

TIA,

jej1216

It is possible to search the directories for files using the PHP file functions like mentioned. See: http://www.php.net/manual/en/function.opendir.php

You'd get better performance by indexing the files in a db like you said, since searching database rows is much faster than scanning a directory, especially if you have many files.

iamthwee commented: Good point about the indexing. +11
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

hi all

I am new to php and curl.How can we create cookies using curl.What is the advantage of creating cookies this way,instead of creating from php's normal way (Setcookie());

Thanks to all

Hi,

CURL is used by your PHP server to make a Request to another Web Server.
Here your websever is acting as the HTTP Client (like your browser) initiating the HTTP Request to the remote server.

Setcookie() is a request to set a cookie sent from your web server to the HTTP Client (usually a browser) that made the initial HTTP Request.

How Setcookie() works:

To understand this you need to understand how cookies are implemented.

Since HTTP is stateless, Cookies were described in the HTTP Specifications as a way to save data between 2 HTTP Requests.

An example HTTP GET Request looks like this:

GET / HTTP/1.0
Host: www.example.com

This is a request for the index page on the domain: www.example.com

Lets say you have the PHP Script below on the index.php page on www.example.com.

<html><head><title>Example</title></head>
<body>
<?php

setCookie('test', 'Test Cookie');
echo 'Test: '.$COOKIE['test'];

?>
</body>
</html>

The HTTP Response can be something like:

HTTP/1.0 200 OK
LOCATION: www.example.com
Set-Cookie: test=Test Cookie
Connection: close

<html><head><title>Example</title></head>
<body>
Test: 
</body>
</html>

Note the HTTP Header: Set-Cookie: test=Test Cookie
This was generated by your webserver when it executed the function setCookie('test', 'Test Cookie');

Now when the web browser receives the HTTP Response from your server, …

Biiim commented: i learnt too +4
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

You really don't need to save anything in a cookie for this.

You can just pass on what the use has put in the form in the HTTP POST or GET and populate the form with this for the user.

It easiest if you use the same PHP script both for generating the form and processing the form. That way you don't have to pass your form fields via HTTP twice.

Simple example: (pseudo code)

$is_generate = false;

if (/* some validation failed */) {

$is_generate = true;
} 

if ($is_generate) { // generate form

echo '<form ... >';
echo '<input type="text" name="foo" value="'.clean($_POST['foo']).'" />';

echo '... etc. etc..';
echo '</form>';

} else { // process form


}

// your variable cleansing funtion
function clean($var) {
// do some sanitizing
return $clean_var;
}

NOtice the line:

echo '<input type="text" name="foo" value="'.clean($_POST['foo']).'" />';

Ive set the value="" to the HTTP POST param "foo" since that is what was passed last time the form was filled...


Edit:
The reason I have clean() function there is just to note that if you are going to print anything sent by the user, back to the browser, you will have to clean your variables with your own custom function.

usually to prevent cross-site scripting.. XSS.

Withought that lil bit it would look something like:

echo '<input type="text" name="foo" value="'.$_POST['foo'].'" />';
Spycat commented: Very well thought-out explanation +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi all,

I need to have a semi transparent picture hovering over a windows media player plugin video. How do i do this? Html preferably...

Thanks,
Max

Heres an example of how you will achieve this...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Image overlay over Windows Media Player Plugin</title>

<style type="text/css">
<!--

.wmp_wrap {
	/* position fixed allows you to */
	/* absolutely position child elements */
	/* relative to this element */
	position: fixed;
}

.wmp_overlay {
	/* positioning */
	z-index: 1000;
	position: absolute;
	top: 0px;
	left: 0px;
	display: block;
	/* dimensions */
	width: [width of embed];
	height: [height of embed];
	/* transparency */
	filter:alpha(opacity=100);
	opacity: 1;
	-moz-opacity:1;
}

.wmp_wrap embed {
	
}

-->
</style>


</head>

<body>

<div class="wmp_wrap">
<img class="wmp_overlay" src="ajaxchat_box_101.png" />
<embed ...>Some example Text. Replace with your WMP Plugin</embed>
</div>

</body>
</html>

What I did was create a DIV to wrap WMP and the IMAGE overlay.
The wrapper DIV is has the the position: fixed. This allows all child Nodes/Elements to be positioned absolutely, relative to this DIV.

Then just position your Image absolutely inside the wrapper DIV and it will overlay the <embed> (WMP) that is inside the wrapper also.

There are a few things that will cause problems with this:

1) You may need to use .png files (support 24-Bit Alpha transparency ie: layers) as .gif sucks at transparency. (Binary Transparency ie: single tranparent …

iamthwee commented: Nice explanation as always (iamthwee) +6
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi,

What you want to do is:

Open a directory handle and read each element in the directory.
When you read a directory, it returns all the elements in the directory.
Some of these are files, and some folders and it will also return two "virtual" folders "." and "..".

When you read a directory element usign readdir(/* opendir handle */) it will return the element name, such as the file name, or the directory name.

What you need is to get the file name, and create a link with it.

Example:

Here's an example page that should do what you want. In the example all files in the subdirectory "imgs" will be read and displayed by the php script.

/<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Show Images in Folder (simple gallery)</title>

<style type="text/css">

.img { 
	border: 1px solid #ccc;
	float: left;
	text-align: center;
	padding: 2px;
}

.img_label {
	border-bottom: 1px dotted #eee;
	display: block;
}

.sep {
	clear: both;
}

</style>

</head>

<body>

<?php

/**
* Read files in a directory
* @author digital-ether at fijiwebdesign.com
*
* @param string directory path
*/
function read_dir_elements($dir_path, $func) {
	if ($dh = opendir($dir_path)) {

		while ($el = readdir($dh)) {
			$path = $dir_path.'/'.$el;
	
			if (is_file($path)) {
				// execute callback function with the file path ($el) as a parameter
				call_user_func($func, $el);
			}

		}   
            
	   closedir($dh);

	} else {
		return false;
	}

	return
okparrothead commented: Very Helpful +1
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

In your code, try dumping the cotents of the array before you use array_filter().
EG:

var_dump($fee2_code);
$fee2_code = array_filter($fee2_code); //line 155

The error is because it isn't an array. Even though your HTML looks ok and it seem it should be an array.


It is difficult to understand what the callback is can you explain better than the PHP manual?

Note: I was looking at Example 2. array_filter() without callback.

The callback is a function that you define, that will be executed in another function.

If you were to implement callback functions in your own code, it could look something like:

/**
* Example of function using a callback. (same as array_filter except it will filter out empty strings also)
* @param array The array to filter
* @param function The callback function
*/
function my_array_filter($array, $callback = false) {

	if (!$callback) {
		$callback = 'trim'; // default callback function: trim()
	}

	$new_array = array(); // filtered array
	foreach($array as $index=>$value) {
		// execute the callback function passing it the argument: $value
		if (call_user_func($callback, $value)) {
			$new_array[$index] = $value;
		}
	}
	return $new_array;
}

/**
* Example of my_array_filter()
*/

$arr = array('hey', false, true, '0', ' ', '');

var_dump(my_array_filter($arr));
echo '<br />';
var_dump(array_filter($arr));

If you look at the function, my_array_filter, there is a line:

call_user_func($callback, $value)

call_user_function will execute a user defined function. Since this function name is passed as an argument in to a function, then it is called a callback.
It …

stymiee commented: excellent post - stymiee +2
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I have a php page with two hyperlinks. I one to send email to certain addresses and the other to also send emails to another address and also delete their records from the database.

I don't want a case where the user accidentally clicks on the link takes the wrong action.

i thougth about javascript confirm function. so i tried combining the javascript confirm function and php but i don't seem to get the two working.

i need the results from the confirm function which is either true or false so i can take appropriate action.

Is there an alternative?does php provide similar alert functions? i really need help.

Javascript is client side (executes on the browser) and PHP is server side (executes on the server).
The confirm box is a function on the browser, so you cannot create a browser confirm box with php unless you use PHP to write out some javascript that will be executed on the browser to display your cofnirm box. (see khanobly's reply)

The only way you can communicate with the php on the server side via javascript is to send the server a new HTTP request (a new page). (exception being xmlHTTPRequest).

In your case, the confirmation box should work just like a normal click on a link (you dont need the javascript to communicate with the php).

eg:

<a href="task.php?option=delete">Delete</a>

Lets say the above will invoke the php script task.php and let it know you want …

chrishea commented: Good answer. Clever use of Javascript to simplify the process. I've copied an extract into my personal Tricks and Tips file. +11
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

You don't even need the php part in <?php ?>.

Anywhere where you have PHP code instead of HTML, you should use the <? .... ?> to enclose the PHP code.

Also, the file extension should be .php (for example index.php).

Just a precaution:

using <? ?> will work for most servers but not all.

Few servers may have the shorthand support turned off. This also stops you from using code like:

<?= ...
<?= '$var ' . ( is_string($var) ? 'IS' : 'IS NOT' ) . ' a string.';

etc.

Another problem is if the server is set up to parse xml files then your <? will be treated as the beginning of <?xml .

So its considered proper form to use <?php ... ?> instead since it should always work on servers with php support.

If you have a script that has alot of shorthand php syntax, and find out it doesnt work on your server, or a server you supplied your php to, then you can use a regex expression to convert your shorthand to the regular syntax.

Example:

$shorthand = '<?php ?> <? echo "blabla"; ?> <?= ?>';
$longphp = preg_replace("/<\?([^p])/i", "<?php$1", $shorthand);
$longphp = preg_replace("/<\?php=/i", "<?php echo ", $longphp);
echo htmlentities($longphp);

This will convert the basic shorthand to regular.
Hope it helps someone. :rolleyes:

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi, i am a computer science final year student, i was thinking of creating an online voting/polling system,the system could include surveys as well. I really need some ideas in designing the system and any idea you send to me will be highly appreciated.

The best way to tackle this I believe is to download an open source voting/polling script, and take a look at how it functions. (search sourceforge.net, hostscripts.com, google)
Most the polling scripts will come with a administration panel (the good ones at least), I dont believe its complete withought it, so you'll have to also look at developing both the polling frontend, and an admin area to manage, create the polls.
Theres a lot of ways to actually go about doing the project, but if I were to do it, I'd first create a simple templating system (having your php logic seperated from your design makes it much less confusing), then develop the admin panel first (think of how the database will store all the results, and how the admin will create the forms), then go on to the actual forms that will be the frontend.

Though it sounds simple, a polling system can be a lot of work.
If you want to really go overboard, try searching the web for AJAX, and use it to validate, populate, submit forms on the poll frontend.
There arent many ajax based polling systems out there open source, (i checked) …