PHP

PHP

1.Introduction To PHP
2. Hello World With PHP
3. Variables
4. Arrays
5. If Statements
6. For And For Each Loops
7. While Loops
8. GET Variables
9. POST Variables
10. Sending An Email With PHP
11. Mini Project - A Contact Form
12. Getting Contents Of Other Scripts
13. Project - Weather Scraper



------------------------------
2.

<?php

echo "Hello World";


?>

-----------

3.

<?php

$name = "RJ";

echo "<p>My name is $name</p>";

$string1 = "<p>This is the first part";

$string2 = "of a sentence</p>";

echo $string1." ".$string2;

$myNumber = 45;

$calculation = $myNumber * 31 / 97 + 4;

echo "The result of the calculation is ".$calculation;

$myBool = false;

echo "<p>This statement is true? ".$myBool."</p>";

$variableName = "name";

echo $$variableName;

?>

-----------------

4.

<?php

$myArray = array("Rob", "Kirsten", "Tommy", "Ralphie");

$myArray[] = "Katie";

print_r($myArray);

echo $myArray[3];

echo "<br><br>";

$anotherArray[0] = "pizza";

$anotherArray[1] = "yoghurt";

$anotherArray[5] = "coffee";

$anotherArray["myFavouriteFood"] = "ice cream";

print_r($anotherArray);

echo "<br><br>";

$thirdArray = array(
 
    "France" => "French",
    "USA" => "English",
    "Germany" => "German");

unset($thirdArray["France"]);

print_r($thirdArray);

echo sizeof($thirdArray);



?>
--------------
5.

<?php

$user = "andy";

if ($user == "rob") {
 
    echo "Hello Rob!";
 
} else {
 
    echo "I don't know you";
 
}

echo "<br><br>";

$age = 16;

if ($age >= 18 || $user == "rob") {
 
    echo "You may proceed...";
 
} else {
 
    echo "You are too young, sorry!";
 
}

?>

------------

6.

<?php

$family = array("Rob", "Kirsten", "Tommy", "Ralphie");

foreach ($family as $key => $value) {
 
    $family[$key] = $value." Percival";
 
    echo "Array item ".$key." is ".$value."<br>";
 
}



for ($i = 0; $i < sizeof($family); $i++) {
 
    echo $family[$i]."<br>";
 
}



for ($i = 10; $i >= 0; $i--) {
 
    echo $i."<br>";
 
}


?>

--------------------

7.
<?php

    $family = array("Rob", "Kirsten", "Tommy", "Ralphie");

    $i = 0;

    while ($i < sizeof($family)) {
     
        echo $family[$i]."<br>";
     
        $i++;
     
    }




    $i = 1;

    while ($i <= 10) {
     
        $j = $i * 5;
     
        echo $j."<br>";
     
        $i++;
     
    }

?>
-----------------
8.
<?php

    if(is_numeric($_GET['number']) && $_GET['number'] > 0 && $_GET['number'] == round($_GET['number'], 0)){
     
        $i = 2;
     
        $isPrime = true;
     
        while ($i < $_GET['number']) {
         
            if ($_GET['number'] % $i == 0) {
             
                // Number is not prime!
             
                $isPrime = false;
             
            }

            $i++;
         
        }
     
        if ($isPrime) {
         
            echo "<p>".$i." is a prime number!</p>";
         
        } else {
         
            echo "<p>".$i." is not prime.</p>";
         
        }
     
    } else if ($_GET) {
     
        // User has submitted something which is not a positive whole number
     
        echo "<p>Please enter a positive whole number.</p>";
     
    }

?>

<p>Please enter a whole number.</p>

<form>

    <input name="number" type="text">
 
    <input type="submit" value="Go!">
 
</form>
-----------
9.
<?php

    if ($_POST) {
     
        $family = array("Rob", "Kirsten", "Tommy", "Ralphie");
     
        $isKnown = false;
     
        foreach ($family as $value) {
         
            if ($value == $_POST['name']) {
             
                $isKnown = true;
             
            }
         
        }
     
        if ($isKnown) {
         
            echo "Hi there ".$_POST['name']."!";
         
        } else {
         
            echo "I don't know you.";
         
        }   
     
    }


?>



<form method="post">

    <p>What is your name?</p>
 
    <p><input type="text" name="name"></p>
 
    <p><input type="submit" value="Submit"></p>


</form>
-----------------------
10.
<?php

    $emailTo = "";

    $subject = "I hope this works!";

    $body = "I think you're great!";

    $headers = "From: rob@robpercival.co.uk";

    if (mail($emailTo, $subject, $body, $headers)) {
        
        echo "The email was sent successfully";
        
    } else {
        
        echo "The email could not be sent.";
        
    }


?>

----------------
11.
<?php

    $error = ""; $successMessage = "";

    if ($_POST) {
        
        if (!$_POST["email"]) {
            
            $error .= "An email address is required.<br>";
            
        }
        
        if (!$_POST["content"]) {
            
            $error .= "The content field is required.<br>";
            
        }
        
        if (!$_POST["subject"]) {
            
            $error .= "The subject is required.<br>";
            
        }
        
        if ($_POST['email'] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {
            
            $error .= "The email address is invalid.<br>";
            
        }
        
        if ($error != "") {
            
            $error = '<div class="alert alert-danger" role="alert"><p>There were error(s) in your form:</p>' . $error . '</div>';
            
        } else {
            
            $emailTo = "me@mydomain.com";
            
            $subject = $_POST['subject'];
            
            $content = $_POST['content'];
            
            $headers = "From: ".$_POST['email'];
            
            if (mail($emailTo, $subject, $content, $headers)) {
                
                $successMessage = '<div class="alert alert-success" role="alert">Your message was sent, we\'ll get back to you ASAP!</div>';
                
                
            } else {
                
                $error = '<div class="alert alert-danger" role="alert"><p><strong>Your message couldn\'t be sent - please try again later</div>';
                
                
            }
            
        }
        
        
        
    }

?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags always come first -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">
  </head>
  <body>
      
      <div class="container">
      
    <h1>Get in touch!</h1>
      
      <div id="error"><? echo $error.$successMessage; ?></div>
      
      <form method="post">
  <fieldset class="form-group">
    <label for="email">Email address</label>
    <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
    <small class="text-muted">We'll never share your email with anyone else.</small>
  </fieldset>
  <fieldset class="form-group">
    <label for="subject">Subject</label>
    <input type="text" class="form-control" id="subject" name="subject" >
  </fieldset>
  <fieldset class="form-group">
    <label for="exampleTextarea">What would you like to ask us?</label>
    <textarea class="form-control" id="content" name="content" rows="3"></textarea>
  </fieldset>
  <button type="submit" id="submit" class="btn btn-primary">Submit</button>
</form>
          
        </div>

    <!-- jQuery first, then Bootstrap JS. -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
          
          
    <script type="text/javascript">
          
          $("form").submit(function(e) {
              
              var error = "";
              
              if ($("#email").val() == "") {
                  
                  error += "The email field is required.<br>"
                  
              }
              
              if ($("#subject").val() == "") {
                  
                  error += "The subject field is required.<br>"
                  
              }
              
              if ($("#content").val() == "") {
                  
                  error += "The content field is required.<br>"
                  
              }
              
              if (error != "") {
                  
                 $("#error").html('<div class="alert alert-danger" role="alert"><p><strong>There were error(s) in your form:</strong></p>' + error + '</div>');
                  
                  return false;
                  
              } else {
                  
                  return true;
                  
              }
          })
          
    </script>
          
  </body>
</html>
-------------------
12.
<?php

    include("includedfile.php");
    
    echo file_get_contents("https://www.ecowebhosting.co.uk");

?>
-------------
13.
<?php
    
    $weather = "";
    $error = "";
    
    if ($_GET['city']) {
        
        $city = str_replace(' ', '', $_GET['city']);
        
        $file_headers = @get_headers("http://www.weather-forecast.com/locations/".$city."/forecasts/latest");
        
        
        if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    
            $error = "That city could not be found.";

        } else {
        
        $forecastPage = file_get_contents("http://www.weather-forecast.com/locations/".$city."/forecasts/latest");
        
        $pageArray = explode('3 Day Weather Forecast Summary:</b><span class="read-more-small"><span class="read-more-content"> <span class="phrase">', $forecastPage);
            
        if (sizeof($pageArray) > 1) {
        
                $secondPageArray = explode('</span></span></span>', $pageArray[1]);
            
                if (sizeof($secondPageArray) > 1) {

                    $weather = $secondPageArray[0];
                    
                } else {
                    
                    $error = "That city could not be found.";
                    
                }
            
            } else {
            
                $error = "That city could not be found.";
            
            }
        
        }
        
    }


?>


<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags always come first -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

      <title>Weather Scraper</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">
      
      <style type="text/css">
      
      html { 
          background: url(background.jpeg) no-repeat center center fixed; 
          -webkit-background-size: cover;
          -moz-background-size: cover;
          -o-background-size: cover;
          background-size: cover;
          }
        
          body {
              
              background: none;
              
          }
          
          .container {
              
              text-align: center;
              margin-top: 100px;
              width: 450px;
              
          }
          
          input {
              
              margin: 20px 0;
              
          }
          
          #weather {
              
              margin-top:15px;
              
          }
         
      </style>
      
  </head>
  <body>
    
      <div class="container">
      
          <h1>What's The Weather?</h1>
          
          
          
          <form>
  <fieldset class="form-group">
    <label for="city">Enter the name of a city.</label>
    <input type="text" class="form-control" name="city" id="city" placeholder="Eg. London, Tokyo" value = "<?php echo $_GET['city']; ?>">
  </fieldset>
  
  <button type="submit" class="btn btn-primary">Submit</button>
</form>
      
          <div id="weather"><?php 
              
              if ($weather) {
                  
                  echo '<div class="alert alert-success" role="alert">
  '.$weather.'
</div>';
                  
              } else if ($error) {
                  
                  echo '<div class="alert alert-danger" role="alert">
  '.$error.'
</div>';
                  
              }
              
              ?></div>
      </div>

    <!-- jQuery first, then Bootstrap JS. -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
  </body>
</html>
-----------------

configuration setting

error_reporting = E_ALL
display_errors = On

------------

<?php

    session_start();

    $error = ""; 

    if (array_key_exists("logout", $_GET)) {
     
        unset($_SESSION);
        setcookie("id", "", time() - 60*60);
        $_COOKIE["id"] = "";
     
    } else if ((array_key_exists("id", $_SESSION) AND $_SESSION['id']) OR (array_key_exists("id", $_COOKIE) AND $_COOKIE['id'])) {
     
        header("Location: loggedinpage.php");
     
    }

    if (array_key_exists("submit", $_POST)) {
     
        $link = mysqli_connect("localhost", "cl29-secretdi", "D-fnT^Hbz", "cl29-secretdi");
     
        if (mysqli_connect_error()) {
         
            die ("Database Connection Error");
         
        }
     
     
     
        if (!$_POST['email']) {
         
            $error .= "An email address is required<br>";
         
        }
     
        if (!$_POST['password']) {
         
            $error .= "A password is required<br>";
         
        }
     
        if ($error != "") {
         
            $error = "<p>There were error(s) in your form:</p>".$error;
         
        } else {
         
            if ($_POST['signUp'] == '1') {
         
                $query = "SELECT id FROM `users` WHERE email = '".mysqli_real_escape_string($link, $_POST['email'])."' LIMIT 1";

                $result = mysqli_query($link, $query);

                if (mysqli_num_rows($result) > 0) {

                    $error = "That email address is taken.";

                } else {

                    $query = "INSERT INTO `users` (`email`, `password`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."', '".mysqli_real_escape_string($link, $_POST['password'])."')";

                    if (!mysqli_query($link, $query)) {

                        $error = "<p>Could not sign you up - please try again later.</p>";

                    } else {

                        $query = "UPDATE `users` SET password = '".md5(md5(mysqli_insert_id($link)).$_POST['password'])."' WHERE id = ".mysqli_insert_id($link)." LIMIT 1";

                        mysqli_query($link, $query);

                        $_SESSION['id'] = mysqli_insert_id($link);

                        if ($_POST['stayLoggedIn'] == '1') {

                            setcookie("id", mysqli_insert_id($link), time() + 60*60*24*365);

                        }

                        header("Location: loggedinpage.php");

                    }

                }
             
            } else {
                 
                    $query = "SELECT * FROM `users` WHERE email = '".mysqli_real_escape_string($link, $_POST['email'])."'";
             
                    $result = mysqli_query($link, $query);
             
                    $row = mysqli_fetch_array($result);
             
                    if (isset($row)) {
                     
                        $hashedPassword = md5(md5($row['id']).$_POST['password']);
                     
                        if ($hashedPassword == $row['password']) {
                         
                            $_SESSION['id'] = $row['id'];
                         
                            if ($_POST['stayLoggedIn'] == '1') {

                                setcookie("id", $row['id'], time() + 60*60*24*365);

                            }

                            header("Location: loggedinpage.php");
                             
                        } else {
                         
                            $error = "That email/password combination could not be found.";
                         
                        }
                     
                    } else {
                     
                        $error = "That email/password combination could not be found.";
                     
                    }
                 
                }
         
        }
     
     
    }


?>

<div id="error"><?php echo $error; ?></div>

<form method="post">

    <input type="email" name="email" placeholder="Your Email">
 
    <input type="password" name="password" placeholder="Password">
 
    <input type="checkbox" name="stayLoggedIn" value=1>
 
    <input type="hidden" name="signUp" value="1">
     
    <input type="submit" name="submit" value="Sign Up!">

</form>

<form method="post">

    <input type="email" name="email" placeholder="Your Email">
 
    <input type="password" name="password" placeholder="Password">
 
    <input type="checkbox" name="stayLoggedIn" value=1>
 
    <input type="hidden" name="signUp" value="0">
     
    <input type="submit" name="submit" value="Log In!">

</form>

----------------------

connection

<?php

    $link = mysqli_connect("localhost", "cl29-secretdi", "D-fnT^Hbz", "cl29-secretdi");
     
        if (mysqli_connect_error()) {
         
            die ("Database Connection Error");
         
        }

?>

------------------

header

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags always come first -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">
   
      <style type="text/css">
       
      .container {
   
            text-align: center;
            width: 400px;
      }
       
      #homePageContainer {
           
            margin-top: 150px;
       
      }
       
          #containerLoggedInPage {
           
              margin-top: 60px;
           
          }
       
       
      html {
       
          background: url(background.jpg) no-repeat center center fixed;
          -webkit-background-size: cover;
          -moz-background-size: cover;
          -o-background-size: cover;
          background-size: cover;
       
          }
       
          body {
           
              background: none;
              color: #FFF;
           
          }
       
          #logInForm {
           
              display:none;
           
          }
       
          .toggleForms {
           
              font-weight: bold;
           
          }
       
          #diary {
           
              width: 100%;
              height: 100%;
           
          }
       
      </style>
  </head>
  <body>
------------

footer

    <!-- jQuery first, then Bootstrap JS. -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
   
      <script type="text/javascript">
   
        $(".toggleForms").click(function() {
         
            $("#signUpForm").toggle();
            $("#logInForm").toggle();
         
         
        });
       
          $('#diary').bind('input propertychange', function() {

                $.ajax({
                  method: "POST",
                  url: "updatedatabase.php",
                  data: { content: $("#diary").val() }
                });

        });
   
   
      </script>
   
  </body>
</html>

--------------
logginedpage

<?php

    session_start();

    if (array_key_exists("id", $_COOKIE)) {
     
        $_SESSION['id'] = $_COOKIE['id'];
     
    }

    if (array_key_exists("id", $_SESSION)) {
     
        echo "<p>Logged In! <a href='index.php?logout=1'>Log out</a></p>";
     
    } else {
     
        header("Location: index.php");
     
    }


?>

-------------------

update database

<?php

    session_start();

    if (array_key_exists("content", $_POST)) {
     
        include("connection.php");
     
        $query = "UPDATE `users` SET `diary` = '".mysqli_real_escape_string($link, $_POST['content'])."' WHERE id = ".mysqli_real_escape_string($link, $_SESSION['id'])." LIMIT 1";
     
        mysqli_query($link, $query);
     
    }

?>

-----------------


No comments:

Post a Comment