Posts Tagged ‘page’

how to get all links from a web page

Monday, October 26th, 2009

A question that gets asked all the time on forums is “How do I get all links on a web page” inside of <a> tags, so here’s some code with full commenting for each line

 * @author Jay Gilford

// regular expression pattern to match all links on a page
$pattern = '%]+href="(?P[^"]+)"[^>*]*>(?P[^< ]+)%si';

// Webpage URL to get links from
$url = '';

// Fetch contents of whole page
$page_content = file_get_contents($url);

// Get all matches of links and put them into the $matches variable
preg_match_all($pattern, $page_content, $matches);

// Variable to hold all of our urls and their text
$urls = array();

// Loop through each array item
foreach($matches['url'] as $k=>$v) {
    // combine the url and text into it's own key for ease of access
    $urls[$k] = array('url' => $v,'text' => $matches['text'][$k]);

// For display purposes only to show the contents of $urls
echo print_r($urls, true);

If you have any questions regarding this feel free to contact me. Details can be found on the about page

how to process a form with php using one page

Tuesday, June 24th, 2008

Many first time coders in PHP tend to use a form on one page, and a PHP script on a completely different page in order to process it. This is highly irritating since you need to make two pages instead of one, and also, if there is an error you have to redirect back to the original page whilst jumping through hoops to send the data back to the original page.

There is however a rather simple way to do this. First you need to create your (X)HTML document. Below, I’ve created a simple example form using XHTML 1.1

As you can see, it has a single text box and a submit button, with ID’s Name and Submit respectively. Also note the action="". This will automatically make your page post the data to the same page. Many people include the

which is discouraged, since it can lead to XSS Attacks, and since it is not required, it’s just asking for trouble.

OK, onto the PHP code. Here’s some simple PHP, which will check if the form has been posted, by checking if the $_POST['Submit'] is set

	$_POST['Name'] = strip_tags($_POST['Name']);
	$contentdiv = '
Your name is '.$_POST['Name'].'
'; }else{ $contentdiv = '
Please enter your name below
'; } ?>

As you can see, I’ve added the content output I wish to be displayed into a simple <div>. All that is left now is to add some PHP code to the XHTML code to echo out the $content, and save as a .php file and it will all be finished

The PHP code is simply <?php echo $contentdiv; ?> and is added between the <body> and the <form> tags.

You can try out this code by clicking here, or download the script using the button below

Form processor download