Sunday, May 29, 2016

PHP Tutorial 12

Logging the User In Out:
Index.php
<?php
require 'core.inc.php';
require 'connect.inc.php';

if (loggedin()) {
            echo 'You\'re logged in.<a href="logout.php">Log out</a>';
} else {
                        include 'loginform.inc.php';    
}

?>

Loginform.inc.php
<?php
if(isset($_POST['username']) && isset($_POST['password'])){
            $username=$_POST['username'];
            $password=$_POST['password'];
            $password2 = md5($password);
            if(!empty($username) && !empty($password)){
                        $query="SELECT id FROM users WHERE username='".$username."' AND password='".$password2."'";
                       
                        if($query_run = mysqli_query($mysql_conn,$query)){
                                    $query_num_rows=mysqli_num_rows($query_run);
                                    if($query_num_rows==0){
                                                echo 'Invalid username/password combination.';
                                    } else if($query_num_rows==1) {
                                                // echo 'OK';
                                      $user_id=mysqli_fetch_array($query_run);
                                       extract($user_id);
                                       $_SESSION['user_id']=$user_id;
                                       header('Location: Tutorial2.php');
                                    }
                        }
            } else {
                        echo 'You must supply a username and password';
            }
}
?>

<form action="<?php echo $current_file; ?>" method="POST">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Log in">
</form>

Core.inc.php
<?php
ob_start();
session_start();
$current_file = $_SERVER['SCRIPT_NAME'];
@$http_referer = $_SERVER['HTTP_REFERER'];
function loggedin(){
                if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id']))
                                return true;
                return false;
}
?>

Logout.php
<?php
require 'core.inc.php';
session_destroy();
header('Location: '.$http_referer);

?>

PHP Tutorial 11

Auto Suggest Application / AJAX /
index.html
<html>
<head>
<script type="text/javascript">
function findmatch(){
                if(window.XMLHttpRequest){
                                xmlhttp= new XMLHttpRequest();
                } else {
                                xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
                }
                xmlhttp.onreadystatechange=function(){
                                if(xmlhttp.readyState ==4 && xmlhttp.status==200){
                                                document.getElementById('results').innerHTML = xmlhttp.responseText;
                                }
                }
                xmlhttp.open('GET', 'search.inc.php?search_text='+document.search.search_text.value, true);
                xmlhttp.send();
}
</script>
</head>
<body>
<form id="search" name="search">
                Type a name:<br>
                <input type="text" name="search_text" onkeydown="findmatch();">
</form>
<div id="results"> </div>

</body>
</html>

Search.inc.php
<?php
if(isset($_GET['search_text'])){
                 $search_text=$_GET['search_text'];
}
if(!empty($search_text)){
                if(@mysql_connect('localhost', 'root', '')){
                                if(@mysql_select_db('a_database')){
                                                $query= "SELECT name FROM names WHERE name LIKE '".mysql_real_escape_string($search_text)."%'";
                                                $query_run=mysql_query($query);
                                                while($query_row=mysql_fetch_assoc($query_run)){
                                                                // echo $name=$query_row['name'].'<br>';
                                                                echo $name='<a href="anotherpage.php?search_text='.$query_row['name'].'">'.$query_row['name'].'</a><br>';

                                                }
                                }
                }
}
?>

POSTing Data / AJAX /
Index.php
<html>
<head>

<script type="text/javascript">
function insert(){
                // var text_value = document.getElementById('insert_text').value;
                // alert(text_value);
                if(window.XMLHttpRequest){
                                xmlhttp= new XMLHttpRequest();
                } else {
                                xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
                }
                xmlhttp.onreadystatechange=function(){
                                if(xmlhttp.readyState ==4 && xmlhttp.status==200){
                                                document.getElementById('message').innerHTML = xmlhttp.responseText;
                                }
                }
                parameters='text='+document.getElementById('insert_text').value;
                xmlhttp.open('POST', 'update.inc.php', true);
                xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                xmlhttp.send(parameters);
}
</script>

</head>
<body>
Insert: <input type="text" id="insert_text">
<input type="button" value ="Submit" onclick="insert();">
<div id="message"> </div>
</body>
</html>

Update.inc.php
<?php
// echo $_POST['text'];
@mysql_connect('localhost', 'root', '');
@mysql_select_db('a_database');
if(isset($_POST['text'])){
                $text = $_POST['text'];
                if(!empty($text)){
                                $query="INSERT INTO data VALUES('', '".mysql_real_escape_string($text)."')";
                                if($query_run=mysql_query($query)){
                                                echo 'Data inserted!';
                                } else {
                                                echo 'Failed';
                                }
                } else {
                                echo 'Please type something.';
                }
}
?>

Try, throw, catch
<?php
$age=16;
try{
                if($age>18) echo 'Old enough';
                else throw new Exception('Not old enough');
} catch(Exception $ex){
                echo 'Error: '.$ex->getMessage();
}

?>

Wednesday, May 25, 2016

PHP Tutorial 10

SELECT by example:
<form action ="Tutorial.php" method="GET">
                Choose a food type:
                                <select name="uh">
                                <option value="u">Unhealthy</option>
                                <option value="h">Healthy</option>
                                </select><br><br>
                                <input type="submit" value="Submit">
</form>

<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_pass='';
$mysql_db='a_database';

if(isset($_GET['uh']) && !empty($_GET['uh'])){
                $uh=strtolower($_GET['uh']);
               
                if($uh=='u' || $uh=='h') {
$query="SELECT `food`, `calories` FROM `food` WHERE `healthy_unhealthy`='".$uh."' ORDER BY `id` DESC";
                                              
                if(@mysql_connect($mysql_host, $mysql_user, $mysql_pass)){
                      if(@mysql_select_db($mysql_db)){
                                                                              
                        if($query_run=mysql_query($query)){
                                                                                              
                                    while($query_row = mysql_fetch_assoc($query_run)){
                                            $food = $query_row['food'];
                                            $calories=$query_row['calories'];
                             echo $food.' has '.$calories.' calories.<br>';
                               }
                } else {
                     echo 'Query failed';
         }
      }
    }
  } else {
     echo 'Must be u, or h.';
 }
}

?>

LIKE with a Search Engine Example:
<form action ="Tutorial.php" method="POST">
 Name: <input type="text" name="search_name"><input type="submit" value="Search">
</form>

<?php
require 'connect.inc.php';

if(isset($_POST['search_name'])){  
 $search_name = $_POST['search_name'];

 if(!empty($search_name)){
   $query = "SELECT name FROM names WHERE name LIKE '%".mysqli_real_escape_string($mysql_conn,$search_name)."%'";
   $query_run = mysqli_query($mysql_conn,$query); 

   if(mysqli_num_rows($query_run) == NULL){ 
    echo 'No result found'; 
   }else{
    echo 'Result found: <br>';
   while($query_row = mysqli_fetch_assoc($query_run)){ 
    echo $query_row['name'].'<br>'; 
   }
  }
}
}
?>
connect.inc.php
<?php
 $host = 'localhost';
 $name = 'root';
 $password = '';
 $database = 'a_database';   //your database name
 if(@mysqli_connect($host, $name, $password)) {
  $mysql_conn = @mysqli_connect($host, $name, $password);
  if(@mysqli_select_db($mysql_conn, $database)) {
  } else {
   die('Could not find database.');
  }
 } else {
  die('Could not connect.');
 }

?>


Tuesday, May 24, 2016

PHP Tutorial 9

MD5 Encryption
<?php
/*
$string ='password';
$string_hash = md5($string);
echo $string_hash;
*/
if(isset($_POST['user_password']) && !empty($_POST['user_password'])){
            $user_password = md5($_POST['user_password']);
           
            $filename = 'hash.txt';
            $handle = fopen($filename, 'r');
            $file_password=fread($handle, filesize($filename));
           
            if($user_password==$file_password){
                        echo 'Password ok!';
            } else {
                        echo 'Incorrect password.';
            }
} else {
            echo 'Please enter a password';
}
?>
<form action ="some2.php" method="POST">
Password: <input type="text" name="user_password"><br><br>
<input type="submit" value="Submit">
</form>

Sending an Email
<?php
$to='alex@phpacademy.org';
$subject ='This is an email';
$body='This is a test email'."\n\n".'Hope you got it.';
$headers='From: Zoljargal <someone@phpacademy.org>';

if(mail($to, $subject, $body, $headers)){
            echo 'Email has been sent to '.$to;
} else {
            echo 'There was an error sending the email.';
}
?>

Creating a Simple Contact Form
<?php
if(isset($_POST['contact_name']) && isset($_POST['contact_email']) && isset($_POST['contact_text'])){
            $c_name = $_POST['contact_name'];
            $c_email = $_POST['contact_email'];
            $c_text = $_POST['contact_text'];
            if(!empty($c_name) && !empty($c_email) && !empty($c_text)){
                        if(strlen($c_name)>25 || strlen($c_email)>50 || strlen($c_text)>1000){
                                    echo 'Sorry, maxLength for each field has been exceeded.';
                        } else {
                                                $to='ub_edu@yahoo.com';
                                                $subject ='Contact form submitted.';
                                                $body=$c_name."\n\n".$c_text;
                                                $headers='From: '.$c_email;

                                                if(mail($to, $subject, $body, $headers)){
                                                            echo 'Email has been sent to '.$to;
                                                } else {
                                                            echo 'There was an error sending the email.';
                                                }
                                    }
            } else {
                        echo 'All fields are required.';
            }
}
?>
<form action = "some2.php" method="POST">
Name:<br><input type="text" name="contact_name" maxlength="25"><br><br>
Email address:<br><input type="text" name="contact_email" maxlength="50"><br><br>
Message:<br>
<textarea  name="contact_text" rows="6" cols="30" maxlength="1000"></textarea><br><br>
<input type="submit" value="Submit">
</form>

Reading a Simple XML File
<?php
$xml = simplexml_load_file('names.xml');
// echo $xml->producer[1]->name.' is '.$xml->producer[1]->age;
foreach($xml->producer as $producer){
echo $producer->name.'('.$producer->age.')<br>';
foreach($producer->show as $show){
echo $show->showname.' on '.$show->showdate.'<br>';
}
}

?>

Sunday, May 15, 2016

PHP Tutorial 8

File Handling: Listing files
<?php

$directory = 'files';
if( $handle = opendir($directory.'/')){
            echo 'Looking inside '.$directory.'<br>';
            while($file = readdir($handle)){
                        if($file!='.' && $file!='..')
                        echo '<a href="'.$directory.'/'.$file.'">'.$file.'</a><br>';
            }
}

?>

File Handling: Checking if a file exists
<?php
$filename = 'file.txt';
if(file_exists($filename)){
            echo 'File already exists.';
} else {
            $handle = fopen($filename, 'w');
            fwrite($handle, 'Nothing');
            fclose($handle);
}

?>

File Handling: Deleting and Renaming files
<?php
$filename = 'filetodelete.txt';
if(unlink($filename)){
            echo 'File <strong>'.$filename.'</strong> has been deleted.';
} else {
            echo 'File cannot be deleted.';
}
?>

<?php
$filename = 'filetorename.txt';
$rand = rand(10000, 99999);
if(rename($filename, $rand.'.txt')){
            echo 'File <strong>'.$filename.'</strong> has been renamed to <strong>'.$rand.'.txt</strong>';
} else {
            echo 'Error renaming';
}
?>
Uploading Files:
<?php
if(isset($_POST['submit'])){
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$location = 'uploads/';   
   
if(isset($name)&&!empty($name)){
    if(move_uploaded_file($tmp_name, $location.$name)){
        echo 'Successfully the (<strong>'.$name.'</strong>) file uploaded!';
    }else{
        echo 'There was an error uploading the file.';
       
    }
        
  }else{
      echo 'Please choose a file';
  }

}
?>

<form action="newboston.php" method="POST" enctype="multipart/form-data">
   
    <input type="file" name="file" /><br/><br/>
    <input type="submit" name="submit" value="Upload"/>
</form>



PHP Tutorial 7

Writing to a File
<?php
$handle=fopen('names.txt', 'w');
fwrite($handle, 'Alex'. "\n");
fwrite($handle, 'Zoloo');
fclose($handle);
echo 'Written';
?>

Reading a File
<?php
if(isset($_POST['name'])){
$name = $_POST['name'];
if(!empty($name)){
$handle = fopen('names.txt', 'a');
fwrite($handle, $name."\n");
fclose($handle);

$count = 1;
echo 'Current names in file: ';
$readin = file('names.txt');
$readin_count = count($readin);
foreach($readin as $fname){
echo trim($fname);
if($count< $readin_count){
echo ', ';
}
$count++;
}
} else {
echo 'Please type a name.';
}
}
?>
<form action = "some2.php" method="POST">
Name:<br>
<input type="text" name="name">
<input type="submit" name="Submit">
</form>

Appending a File
<?php
if(isset($_POST['name'])){
$name = $_POST['name'];
if(!empty($name)){
$handle = fopen('names.txt', 'a');
fwrite($handle, $name."\n");
fclose($handle);
} else {
echo 'Please type a name.';
}
}
?>
<form action = "some2.php" method="POST">
Name:<br>
<input type="text" name="name">
<input type="submit" name="Submit">
</form>

The explode Function with File Handling Example
<?php
$filename = 'names.txt';
$handle = fopen($filename, 'r');
// echo fread($handle, filesize($filename));
$datain = fread($handle, filesize($filename));
$names_array = explode(',', $datain);
foreach($names_array as $name){
echo $name.'<br>';
}
?>


The implode Function with File Handling Example
<?php
$names_array = array('Alex', 'Billy', 'Dale');
$string = implode('-', $names_array);
echo $string;

?>

Friday, May 13, 2016

PHP Tutorial 6

Using the Header to Force Page Redirect 

<?php ob_start() ?>

<h1> My Page </h1>
This is my page.

<?php
// ob_start
$redirect_page = 'http://www.google.com';
$redirect = false;
if($redirect == true){
header('Location: '.$redirect_page);
}

ob_end_flush();

?>

Setting PHP Sessions
set.php
<?php
// Session
session_start();
$_SESSION['username']='alex';
?>

view.php
<?php
// Session
session_start();
if(isset($_SESSION['username'])){
echo 'Welcome, '.$_SESSION['username'];
} else {
echo 'Please log in!';
}

?>

Unsetting PHP Sessions
unset.php
<?php
// Session
session_start();

unset($_SESSION['username']);

// session_destroy();
?>

Creating Cookies with PHP
set.php
<?php
// Cookie
setcookie('username', 'alex', 1);
?>

view.php
<?php
echo $_COOKIE['username'];
?>


Thursday, May 12, 2016

PHP Tutorial 5

Working with $_GET Variables
<?php
// GET
if(isset($_GET['day']) && isset($_GET['date']) && isset($_GET['year'])){
$day = $_GET['day'];
$date = $_GET['date'];
$year = $_GET['year'];
if(!empty($day) && !empty($date) && !empty($year)){
echo 'It is '.$day. ' '.$date.' '.$year;
} else {
echo 'Fill in all fields';
}
}
?>
<form action = "some2.php" method ="GET">
Day: <br><input type="text" name="day"><br>
Date: <br><input type="text" name="date"><br>
Year: <br><input type="text" name="year"><br><br>
<input type="submit" value="Submit">

</form>

Working with $_POST Variables
<?php
// POST
$match='pass123';
if(isset($_POST['password'])){
$password = $_POST['password'];
if(!empty($password)){
if($password == $match){
echo 'That is correct!';
} else {
echo 'That is incorrect!';
} else {
echo  'Please enter a password!';
}
}
}
?>
<form action = "some2.php" method ="POST">
Day: <br><input type="password" name="password"><br><br>
<input type="submit" value="Submit">

</form>

Using htmlentities for Security
$day = htmlentities($_GET['day']);
$date = htmlentities($_GET['date']);

$year = htmlentities($_GET['year']);

PHP Tutorial 4

Getting visitors IP Address
<?php
// Getting visitors IP Address
$ip_address = $_SERVER['REMOTE_ADDR'];
$ipblocked = array('127.0.0.1', '100.100.100.100');
foreach($ipblocked as $ip){
if($ip == $ip_address){
die('Your IP address '. $ip_address. ' has been blocked' );
}
}
?>
 Better way to get visitors IP
<?php
// Better way to get visitors IP
$http_ip = $_SERVER['HTTP_CLIENT_IP'];
$httpxforwardedfor=$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote_addr = $_SERVER['REMOTE_ADDR'];

if(!empty($http_ip)){
$ip = $http_ip;
} else if(!empty($httpxforwardedfor)){
$ip = $http_ip;
} else {
$ip = $remote_addr;
}
echo $ip;
?>
Detect Browser
<?php
// DETECT BRowser
$browser = get_browser(null, true);
// echo $browser['browser'];
$browser = strtolower($browser['browser']);

if($browser !='chrome'){
echo 'You\'re not using Google Chrome. Please do!';
}
?>



Wednesday, May 11, 2016

PHP Tutorial 3

1: WORD CENSORING
<?php
$find = array('alex', 'billy', 'dale');
$replace=array('a**x', 'b***y', 'd**e');

if(isset($_POST['userinput']) && !empty($_POST['userinput'])){
$user_input=$_POST['userinput'];
// $user_input_lc = strtolower($user_input);
$user_input_new = str_ireplace($find, $replace, $user_input);
echo $user_input_new;
}

?>
<hr>
<form action="some2.php" method="POST">
<textarea name="userinput" rows="6" cols="30"><?php echo $user_input; ?></textarea><br><br>
<input type="submit" value="Submit">
</form>

2: Creating a Find and Replace Application
<?php
// Creating a Find and Replace Application

$offset = 0;

if(isset($_POST['text']) && isset($_POST['searchfor']) && isset($_POST['replacewith'])){

$text = $_POST['text'];
$search = $_POST['searchfor'];
$replace = $_POST['replacewith'];
$searchlength = strlen($search);

if(!empty($text) && !empty($search) && !empty($replace)){

while($strpos = strpos($text, $search, $offset)){
// echo $strpos.'<br>';
// echo $offset=$strpos+$searchlength.'<br>';
$offset = $strpos + $searchlength;
$text = substr_replace($text, $replace, $strpos, $searchlength);
}
echo $text;
} else {
echo 'Please fill in all fields';
}
}

?>
<form action="some2.php" method="POST">
<textarea  name="text" rows = "6" cols="30"></textarea><br><br>
Search for:<br>
<input type="text" name="searchfor"><br><br>
Replace with:<br>
<input type="text" name="replacewith"><br><br>
<input type="submit" value="Find and Replace">

</form>

3. RANDOM NUMBER
<?php
$rand = rand();
$max = getrandmax();
echo 'Some Random: '.$rand.'/'.$max;

if(isset($_POST['roll'])){
$rand = rand(1, 10);
echo '<br>You rolled a '.$rand;
}
?>
<form action = "some2.php" method="POST">
<input type="submit" name="roll" value="Roll dice.">

</form>