PHP – WebDevLounge http://webdevlounge.com Design, development, SEO and wordpress Thu, 30 Aug 2018 12:49:55 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.2 Stylesheet switcher with time! http://webdevlounge.com/stylesheet-switcher-with-time/ Tue, 31 Jul 2018 10:37:01 +0000 http://webdevlounge.com/?p=29

Hello everyone, I’m Adam Roberts – A designer and developer. Today I would like to show you a really simple and effective way of switching style sheets depending on what time it is.

After seeing a new article on Smashing Magazine this morning called, Style Switchers Contest Results, I immediately thought of new way around this. It is especially effective for night and day themes however it is your choice of what you do theme wise.

Ok so let’s begin. What we need is 3 themes, for example, morning.css, day.css and night.css. Before we apply our style switcher, you need to make sure that you have all three of these themes coded and functional.

It is preferred that each theme has it’s own style sheet as well. This way the switcher will function properly. Also please try and make it so you have just 1 index file. As usually, only images will change for a new theme.

We now need to rename your index.html to index.php, as we will be applying a little piece of PHP code for our switcher.

We will be switching the theme depending on the time of day. Which like I said above, it is effective for night and day themes. Here is what we do, and I will try and explain it the best I can.

In your index.php, you should have a piece of code such as,

<link rel=”stylesheet” type=”text/css” href=”” />

Now this is all what we are editing. Notice that I left the href empty. Now for the switcher…

<link rel=”stylesheet” type=”text/css” href=”
<?php
$hour = date(”H”);
if ($hour < 12) echo “morning.css”;
elseif ($hour < 20) echo “day.css”;
else if ($hour < 4) echo “night.css”;
?>”
/>

First we define the hour. The hour of day is determined by the user’s computer.

The rest is simple. If the hour is before 12 noon, then we will use the morning.css stylesheet, however if the hour is before 20:00 (8pm) then we will use the day.css, but if the hour is before 4 (4 am) we will use the night.css stylesheet.

So that says, between 4am and 12 noon we use the morning theme. Between 12 noon and 8pm we use the day theme. And finally between 8pm and 4am we use the night theme.

You can change the hours yourself easily. These figures that I have provided are configured for when the sun rises and falls in the United Kingdom. Other countries might be slightly different, so you change this as you please.

I hope you enjoyed this tutorial, I may eventually make 3 themes and give you a more detailed explanation in the future.

Edit: We need to give full credit to Harry Roberts for this solution!

]]>
AJAX: Auto Suggest http://webdevlounge.com/ajax-auto-suggest/ Thu, 06 Jul 2017 02:30:59 +0000 http://webdevlounge.com/?p=85

If your a web developer looking to add some extra functionality to your clients website and look good while your at it, then than an auto suggest search bar is something you might consider. Ever since ‘Google Suggest‘ rolled out the labs, hundreds of clones have sprung up on a variety of websites, each with a slight twist on the original. This article is going to show you how to make your own ‘auto suggest’ search bar in three easy steps.

This article assumes you have a solid grounding in HTML, CSS, Javascript and PHP. It is showing technique, not teaching you the language.

Step 1 – Good Form

The first step towards making our finished product is to develop the front-end of the site. This is basically going to consist of a HTML form containing an text input dialog, a submit button and a placeholder for our suggestions. With that in mind, lets look at the code:

<html>

<head><title>Auto Suggest</title></head>

<body>

<form action="#" ><input type="text" id="inputtext" />
<input type="submit" name="submit" value="Search" />
<div id="suggestions"> </div>
</form>

</body>

</html>

As you can see we have our text box labeled ‘inputtext<input type=”text” id=”inputtext” /> and our placeholder labeled ’suggestions’ <div id=”suggestions”> </div>. When we come to write the Javascript we can use these id’s to access them. That’s all that’s needed for now, so lets move on to step 2.

Step 2 – Script Me

Right now our page is static and ultimately useless. However, with a little Javascript magic it will start to come alive. Before we right the code, lets take a step back and think about what we need to do. Every time a letter is entered into our form we want to send a HTTP request to the server and check if the string in the form matches any of the results from a preset list. If it does we want to write the results to our web page. So the first thing we need check if a letter has been entered into our text box. To do this we can use the onkeyup attribute to call a Javascript method every time a new letter is entered. So our HTML now looks like this:

<form action="#" >

<input type="text" id="inputtext" onkeyup="suggest(this.value)" />

<input type="submit" name="submit" value="Search" />

<div id="suggestions"> </div>

</form>

So now, every time a letter is entered the Javascript function ‘suggest‘ is called, passing the value in  the text box as a parameter. That’s all well and good, but the suggest function doesn’t exist yet, so lets create it.

var xmlHttp;

function suggest(input) {
        xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Browser does not support HTTP Request");
        return;
    }
var url="suggest.php";
    url=url+"?query="+input;
    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
} 

function stateChanged() {
     if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
         document.getElementById("suggestions").innerHTML=xmlHttp.responseText ;
    }
 }

function GetXmlHttpObject() {
    var xmlHttp=null;
    try{
        xmlHttp=new XMLHttpRequest();
    }catch (e){
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e){
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

Don’t be scared! Although it looks a lot it is in fact very simple. the GetXmlHttpObject() is our standard function to create an XMLHTTPRequest object that works across all browsers and the stateChanged() function simply receives text from the server and places it in our ‘suggestions‘ placeholder. The suggest function itself is also very simple to understand. Basically, it creates a new XMLHttpRequest object and stores in the variable xmlHttp. After some basic error checking, we tell our application to run the stateChanged() function when there is a change of state. The URL is then created from the text inputted in our text box and the HTTP request is opened and sent with this URL. Now we have all the client side code completed and functioning, the last thing we need to do is write our PHP file.

Step 3 – Server Side

All we need the server to do is check to see whether the query sent matches anything stored in a file, database or anything we want. In this example we are going to just fill an array with countries from around the world and then see if the query matches them. We can do this as follows:

<?php

$countries[] = "Afghanistan";
$countries[] = "Albania";
$countries[] = "Algeria";
$countries[] = "Azerbaijan";
$countries[] = "Bahrain";
$countries[] = "Barbados ";
$countries[] = "Belgium";
$countries[] = "Canada ";
$countries[] = "Chile";
$countries[] = "China";
$countries[] = "Egypt";
$countries[] = "Germany";
$countries[] = "India";
$countries[] = "Iraq";
$countries[] = "Ireland";
$countries[] = "Mexico";
$countries[] = "Pakistan";
$countries[] = "Poland";
$countries[] = "Sri Lanka";
$countries[] = "Sudan";
$countries[] = "Thailand";
$countries[] = "United Kingdom";
$countries[] = "United States of America";
$countries[] = "Zimbabwe";

$query=$_GET["query"];

if (strlen($query) > 0) {
    $suggestions="";
    for($i=0; $i<count($countries); $i++) {
            if (strtolower($query)==strtolower(substr($countries[$i],0,strlen($query)))) {
            if ($suggestions=="")
                $suggestions=$countries[$i];
            } else {
                $suggestions=$suggestions.", ".$countries[$i];
            }
        }
    }
}

echo $suggestions;

?>

All this does is populates an array with a variety of countries (of course, in a real world application this would be populated from a database or text file) then gets the query that was passed to it. The code following this simply checks to see whether the query passed matches anything in the array and adds it to the ‘suggestions‘ string. At the end of the script the suggestions are outputted and received by the Javascript.

Finished… nearly

So now we have a fully functioning auto-suggest feature. Right now it looks a little bland but with a little CSS and imagination we can create something that really looks the part. By slight modifying the code and adding some styling I came up with this example. Give it a try yourself and post your results in the comments, we would love to see them!

]]>
Using PHP includes to easily edit your site’s static content! http://webdevlounge.com/using-php-includes-to-easily-edit-your-sites-static-content/ Thu, 06 Mar 2014 16:48:43 +0000 http://webdevlounge.com/?p=49 Hey, in the following article I’ll show you how to add PHP includes to a static multi-page site, like a personal site or a portfolio, to help edit the site more easily.

For this article, I’ve presented a simple web page layout below. The template contains a header, a navigation, a place for the main content, a static sidebar, and a footer. If I were to add a link to the navigation, I would have to manually go through every page in the site and add a new list item.

However, if I switched to using PHP includes, I would only have to edit one file, which when edited automatically changes on every page. This helps when you need to change the link to a CSS file, add a couple of list items to a navigation bar, change your sidebar, etc.

So how do I do this? It may look a bit complicated but it’s actually only a few steps and you need to know absolutely no HTML or PHP. Here’s a nice little list for you:

  • First, you have to change all of your site files from the .htm or .html extension to the .php extension. This can be done on your local computer or on your server, using an FTP program.
  • Then, figure out what sections of the site are repeated and unchanged page-to-page. In the site template above they will be the header, the navigation, the sidebar, and the footer.
  • Next, create separate files for each of these sections, for example header.php or footer.php, and add the code for each one in the correct file.
  • Finally, take all of your old files and replace the previous sections of hard code with this line of PHP: <?php require('header.php');?> This line of PHP code includes the chosen PHP file into the HTML code. All you have to do is copy the code above and replace the “header.php” with the name of your specific includes.

Once you’re done, your pages’ code should now have a layout similar to this:

As an extra addition, I’ll show you how to hide/show/change certain sections depending on the URL that you’re located at.

Edit: I’ve added a nice little .zip file that shows you a super-simple example on how to use these PHP includes on your site.

You can edit the above code adding lines for each thing you want as a condition, just changing the “index.php” segment to whatever your page url is called (like about.php, etc.) or the required include (like sidebarcontent.php, etc.). Have fun!

Once you’re done, you’ll have a nice easily-editable site. Enjoy!

]]>
Tutorials, Tips and Resources for PHP http://webdevlounge.com/tutorials-tips-and-resources-for-php/ Mon, 08 Mar 2010 08:30:35 +0000 http://webdevlounge.com/?p=69

The TTR is a series of posts which we will try to do each week on a subject like PHP, JS, CSS and or HTML. This will cover 10 to 20 links in each category; tutorials, tips and resources. If you want to suggest some please just contact us or leave a comment!

Tutorials

  • Build A Photo Gallery Using CakePHP And Flickr.

    Johnathan Snook explains how to build a photo gallery using CakePHP and Flickr. He uses Javascript for lightbox effects too. If you want a simple and fast gallery on your webpages then, this is what you need.

  • Uploading Videos To Youtube

    Carl Evans takes you through the process to upload videos to youtube with the help of youtube, google API and zend framework.

  • Posting Form Data with cURL

    Forms can be submitted to other websites with execution of this simple script explained by Third_Degree. I can already imagine a lot of automation.

  • Store Images in MySQL with PHP

    vBulletin, a popular forum softwares uses MySQL to store images. Jordan (Author) illustrates advantages/disadvantages and the the complete process of using PHP to store images.

  • Getting Started with OpenID and PHP

    OpenID is a way to minimize the process of registering at different websites. The author explains the use of OpenID, the benefits and the steps to build login forms powered by OpenID.

  • Drawing with PHP / Drawing Graphs with PHP

    GD Library is a poweful image manipulation library. The author explains how to dynamically draw images / draw graphics with the power of PHP arrays and GD library.

  • Display Images Stored in MySQL

    You had already stored images in MySQL database with the help of above tutorial now, Jaan explains how to display those images on webpages.

  • PayPal Payments Using IPN

    Learn how to accept PayPal Payments using the easy-to-use PayPal IPN.

  • Generate PDFs with PHP

    Icarus from Sitepoint explains how to use PHP to generate PDFs. A popular example of this will be webhosting billing systems which generates printable PDF version of the invoices.

  • Understanding the Life of a Session

    Adam from TalkPHP elaborates the security issues involved with using sessions. A must-read for a beginner.

Tips

  1. Single-quotes uses period (.) for concatenation with variables which takes less processing time as compared to variables which are blended in double-quotes.
  2. A IRC channel exists for PHP support #php on freenode. Don’t ask to ask.
  3. cURL library is faster than fopen function for opening web-pages.
  4. substr() can be used to truncate long text.
    substr('This is a very long line which will be truncated to 10 characters', 0 , 10');
  5. ucwords() can be used to titleize a text. It capitalizes the first character of every word.
    ucwords('please make me a title');
    output: Please Make Me A Title
  6. money_format function returns formatted version of the number relevant to localization.
    setlocale(LC_MONETARY, 'en_US'); // Localization USA
    echo money_format('%i', '100') ; // Print the number with the currency code wrapped before number.
    // Output: USD 100
  7. array_sum function can be used to sum the numbers in an array. -1 loop.
    $cost = array(50, 100, 35.45, 500, 485, 68.75, 4298, 237823, 5.4, 574); // Make sure the numbers are integer
    $final_cost =  array_sum($cost); // Sum the numbers in $cost
    echo $final_cost; // Output final cost
  8. There are default functions to validate datatypes.
  9. is_array
  10. is_int
  11. is_bool
  12. is_object
  13. and many more..
  14. Xdebug generates formatted version of PHP warnings,errors,notices and var_dump.
  15. Comment your code in all circumstances. Comment your loops and control structures.
    /**
     * Validate Form
     */
    if(count($_POST) == 5) { // The form is completely filled in..
    echo 'Thank you for your message';
    }
    else { // The form has not been completely filled in..
     redirect(''); // Redirect to form again
    exit(); // Exit the webpage, no further processing.
    }

Resources

  • PHP Desktop Programming

    Want to develop desktop programs with PHP? Use PHP-GTK. PHP-GTK Version 2.0.1 was released few months ago.

  • Quick Access to Functions Documentation with Shortwaveapp

    Add shortwaveapp bookmarklet to your browser and use “php functionname” on the javascript popup to quickly access the function documentation.

  • PHP Editors Review

    Popular text editors reviewed by php-editors.com team.

  • PHP Forum

    A home for PHP developers. TalkPHP contains articles written by experienced developers, php general discussions and php help sections with a pinch of humour.

  • PHP : Home

    PHP.net is the best resource for all-things-php. I recommend everyone to check php official documentation first because they’re clearly written with comments from experienced developers providing variety of solutions.

  • MySQL : Home

    Just like PHP Home, MySQL Home has extremely well importance. It has an extensive documentation with all kinds of technicial details required by any developer. Kudos amd thanks to the documentation team.

  • PHPMailer

    PHPMailer provides an alternative route to php mail function with powerful functions such as attachments, multiple contacts, smtp options, html/text format content for the email and etc. Do checkout!

  • PHP Frameworks Comparison

    PHP Frameworks are a hot thing in the world of PHP. There are a different kind of frameworks with different kind of working style. The chart just highlights the features and doesn’t indicate which is the best or which is the worst framework.

  • PHP Classes

    PHP Classes has every kind of classes available for free download from AJAX to XML classes. Do check it out.

  • Regexlib

    Regexlib is a library of regular expression with common expressions for emails, domains, ip, phone numbers and etc.. It’s a time-saver resource.

]]>