Local Tech Repair: PHP

Pages

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, February 29, 2012

Range Switch Statements in PHP

For those that are wondering how to use a switch statement to check the ranges of number in php here you go.

there are different ways of checking ranges you can either use a if statement. Though a if statement gets extremely blocky over many different checks.

I prefer using switches to check my ranges. Here is an example of how to do that.



function formid($start) {
$start = (int)$start;
switch ($start) {
case ($start < (int)3):
return 1;
break;
case ($start < (int)7):
return 2;
break;
case ($start > (int)7):
return 2;
break;
default:
return 0;
break;
}

$num = 3;
echo formid($num); // this will return 2




So you don't have to do it the hard way with all those if statements you can just use a switch.

I hope you liked this little article

Local Tech Repair Admin

Sunday, November 6, 2011

Creating a PHP Page From Another PHP Page

Some times it is good to know how to create other PHP pages from with in a PHP script. This can especially be helpful in a configuration file for setting up a program.

creating files should not be hard to do if you know how to use fopen, fwrite functions in PHP. Though for those that are starting out in programming in PHP escape characters are sometimes tricky.

Lets look at a simple example. Lets say we need our install script to take the mysql server host, username, password, and the prefix for the tables that it creates. Though you need to keep this information so that the server can remember to how to connect to the mysql server. An easy way is creating a php script that is used to connect to the mysql server. So this is an example of how a script may look
Configure.php:

$db_name = "localtechrepair";
$username = "localtechrepairuser";
$password = "samplepassword";
$host = "localhost";
$prefix = "LTC_";

/*
* **********************************************************
* Creats a file with stored info for database connection
* **********************************************************
*/
$filename = "connect.php";
$filenamehandle = fopen($filename, 'w') or die("can't create connection file please make sure you have write permissions");
$connectdata = "
";
if (fwrite($filenamehandle, $connectdata)) {echo "Created Connect file...";} else {echo "Error: Can't Create connect.php file"; exit;}
fclose($filenamehandle);



What this does is allow your program to remember all the information that the user put in while and writing it to a file. once this script runs it will create a fully functional php connection script that you can include in your other scripts so that you don't have to write it on all your scripts which would take a lot of extra editing.

For those that are new to escape characters the \ before the $ or " means that it is supposed to be text not a variable. we do this instead of using ' single quote because we want variables in the print out. Using escape character also help with not having to break this text up in in many different appending text variables.

If you have any suggestions or find a mistake please comment.
Local Tech Repair Admin

Saturday, January 29, 2011

Checking form submit with php

so one thing that took me a while to figure out is how to have php check the form submissions in the same page but only if the form was submitted. another thing was if something was wrong being able to have php give default values that where already submitted if there was a problem. so better than me talking let me show you code.

but let me explain what this form is in the first place. this is a medical history form for dogs. this shows when their last medical test for certain things where done on.
---------form.php-------------------
<?
include ("header.php");
include "../connect.php";
?>
<td class="left_content"><div align="center"><strong>Here are some Use full links</strong></div><br />
<?include ("../leftside.php");?>




</td>
<td class="body_content"><strong><h4 id="title"> Medical Record </h4></strong>
<?php
if ($_POST['submit'] == "Update") { // this checks to see if the submitted form name is Update
$name = $_POST['pName'];
$DHLPP = $_POST["DHLPP"];
$Rabies = $_POST["Rabies"];
$Bordatella = $_POST["Bordatella"];
$heartworm = $_POST["heartworm"];
$worming= $_POST["worming"];
$flea= $_POST["flea"];
$Fixed= $_POST["Fixed"];
$pinHips= $_POST["pinHips"];
$OFA= $_POST["OFA"];
$Eye= $_POST["Eye"];
$wellness= $_POST["wellness"];
$sql = "SELECT * FROM Medical where dogName = '$name'";
$results=mysql_query($sql) or die (mysql_error());
$row= mysql_fetch_array($results);
$numrow = mysql_num_rows($results);
while ($row= mysql_fetch_array($results)){
$id = $row['ID'];
}
if ($numrow == 1) {
$sql = "UPDATE Medical SET dogName = '$name', DHLPP = '$DHLPP', Rabies = '$Rabies',
Bordatella = '$Bordatella', heartworm = '$heartworm', worming = '$worming',
flea = '$flea', Fixed = '$Fixed', pinHips = '$pinHips', OFA = '$OFA', Eye = '$Eye',
wellness = '$wellness'
WHERE dogName = '$name'";
$result = mysql_query($sql) or die (mysql_error());
if ($result) { echo "updated"; }
$date = date('Y-m-d');
$sql="INSERT INTO MedicalHistory (dogName, DHLPP, Rabies, Bordatella, heartworm, worming, flea, Fixed, pinHips, OFA, Eye, wellness, dateadd)
VALUES ('$name','$DHLPP','$Rabies','$Bordatella','$heartworm','$worming','$flea','$Fixed','$pinHips','$OFA','$Eye','$wellness','$date')";
$result = mysql_query($sql) or die (mysql_error());
} else {
$name = $_POST['pName'];
$DHLPP = $_POST["DHLPP"];
$Rabies = $_POST["Rabies"];
$Bordatella = $_POST["Bordatella"];
$heartworm = $_POST["heartworm"];
$worming= $_POST["worming"];
$flea= $_POST["flea"];
$Fixed= $_POST["Fixed"];
$pinHips= $_POST["pinHips"];
$OFA= $_POST["OFA"];
$Eye= $_POST["Eye"];
$wellness= $_POST["wellness"];
$sql="INSERT INTO Medical (dogName, DHLPP, Rabies, Bordatella, heartworm, worming, flea, Fixed, pinHips, OFA, Eye, wellness)
VALUES ('$name','$DHLPP','$Rabies','$Bordatella','$heartworm','$worming','$flea','$Fixed','$pinHips','$OFA','$Eye','$wellness')";
$result = mysql_query($sql) or die (mysql_error());
if ($result) { echo "inserted"; }

$date = date('Y-m-d');
$sql="INSERT INTO MedicalHistory (dogName, DHLPP, Rabies, Bordatella, heartworm, worming, flea, Fixed, pinHips, OFA, Eye, wellness, dateadd)
VALUES ('$name','$DHLPP','$Rabies','$Bordatella','$heartworm','$worming','$flea','$Fixed','$pinHips','$OFA','$Eye','$wellness','$date')";
$result = mysql_query($sql) or die (mysql_error());

}

} else {if ($_POST['submit'] == "Delete Dog") {
$name = $_POST['pName'];

$sql = "DELETE FROM Medical WHERE dogName = '$name'";
$result = mysql_query($sql) or die (mysql_error());
if ($result) {echo "Deleted Dog";}
}
}
$name = $_POST['pName'];
$sql = "SELECT * FROM Medical where dogName = '$name'";
$results=mysql_query($sql) or die (mysql_error());

$row= mysql_fetch_array($results);

$DHLPP = $row["DHLPP"];
$Rabies = $row["Rabies"];
$Bordatella = $row["Bordatella"];
$heartworm = $row["heartworm"];
$worming= $row["worming"];
$flea= $row["flea"];
$Fixed= $row["Fixed"];
$pinHips= $row["pinHips"];
$OFA= $row["OFA"];
$Eye= $row["Eye"];
$wellness= $row["wellness"];

?>
<form method="POST" action="">
<?php
$query = "SELECT * FROM Dogs";
$arr = mysql_query($query);


echo "<select name='pName'>";
echo "<option value=" . $name . ">" . $name . "</option>";
while ($row = mysql_fetch_array($arr)) {
$title = $row["Name"];

if ($title != $name) {
echo "<option value=" . $title . ">" . $title . "</option>";
}
}
echo "</select>";
?>
<br />
<input type="submit" value="Change Dogs">
</form>

<form method="POST" action="">
<table>
<tr>
<td colspan="2">
<input type="hidden" name="pName" value="<?php print $name; ?>"/>

</td>
</tr>
<tr>
<td>DHLPP</td>
<td><input type="date" name="DHLPP" value="<?php if ($DHLPP != "0000-00-00"){print $DHLPP; } ?>" />(Ex: YYYY-MM-DD)</td>
</tr>
<tr>
<td>Rabies</td>
<td><input type="date" name="Rabies" value="<?php if ($Rabies != "0000-00-00"){print $Rabies;} ?>" />(Ex: YYYY-MM-DD)</td>
</tr>
<tr>
<td>Bordatella</td>
<td><input type="date" name="Bordatella" value="<?php if ($Bordatella != "0000-00-00"){ print $Bordatella;} ?>" />(Ex: YYYY-MM-DD)</td>
</tr>
<tr>
<td>heartworm</td>
<td><input type="date" name="heartworm" value="<?php if ($heartworm != "0000-00-00"){ print $heartworm;} ?>" />(Ex: YYYY-MM-DD)</td>
</tr>
<tr>
<td>worming</td>
<td><input type="date" name="worming" value="<?php if ($worming != "0000-00-00"){ print $worming;} ?>" />(Ex: YYYY-MM-DD)</td>
</tr>
<tr>
<td>flea</td>
<td><input type="date" name="flea" value="<?php if ($flea != "0000-00-00"){ print $flea;} ?>" />(Ex: YYYY-MM-DD)</td>
</tr>
<tr>
<td>Fixed</td>
<td><input type="date" name ="Fixed" value="<?php if ($Fixed != "0000-00-00"){ print $Fixed; } ?>" />(Ex: YYYY-MM-DD)</td>
</tr>
<tr>
<td>pinHips</td>
<td><input type="date" name="pinHips" value="<?php if ($pinHips != "0000-00-00"){ print $pinHips;} ?>" />(Ex: YYYY-MM-DD)</td>
</tr>
<tr>
<td>OFA</td>
<td><input type="date" name="OFA" value="<?php if ($OFA != "0000-00-00"){ print $OFA;} ?>" />(Ex: YYYY-MM-DD)</td>
</tr>
<tr>
<td>Eye</td>
<td><input type="date" name="Eye" value="<?php if ($Eye != "0000-00-00"){ print $Eye; } ?>" />(Ex: YYYY-MM-DD)</td>
</tr>
<tr>
<td>Wellness</td>
<td><input type="date" name="wellness" value="<?php if ($wellness != "0000-00-00"){ print $wellness;} ?>" />(Ex: YYYY-MM-DD)</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Update" />
<input type="submit" name="submit" value="Delete Dog" />
</td>
</tr>
</table>
</form>




<?php

$ip = $_SERVER['REMOTE_ADDR'];
$username = $_COOKIE['Username'];
$date = date('Y-m-d H:i:s');
$sql = "insert into loginHistory (ip, username, datetime) VALUES ('$ip','$username','$date')";
$result=mysql_query($sql);
?>

</td>
<?
include ("../footer.php");
?>
---------------------------------


let me explain this in more detail

when a form is either submitted or not it will run this
<tr>
<td>Wellness</td>
<td><input type="date" name="wellness" value="<?php if ($wellness != "0000-00-00"){ print $wellness;} ?>" />(Ex: YYYY-MM-DD)</td>
</tr>
this is date input type which is a standard coming in html5 that makes sure that before someone submits a form it makes sure that it is a date. though if the browser is not html5 compatible then it will treat it like a text input.
the php in this is checking if the variable $wellness does not not equal 0000-00-00 which is a default input in a mysql database for a date type if the input is blank.

so basicly if it equals anything but 0000-00-00 it will print the variable $wellness in the value. so if $wellness = 2010-01-01 then the input in html will look more like
      <td><input type="date" name="wellness" value="2010-01-01" />(Ex: YYYY-MM-DD)</td>

if your wanting to check each input then you can with in the
if ($_POST['submit'] == "Update") {
you can have separate if statements for each input

so if i wanted to check if the date was exactly 10 characters long then i would run a if statment like this

if (strlen($wellness) != 10 ) {
throw some kind of error
}

the possibilities are endless this is just one thing i have done when i was trying to make my input form more dynamic and not having to have multiple pages.

also if your using a GET statement you can do the same thing. the key is that the input needs to have a name of submit and the value can be checked that way.

i hope you enjoyed this little php and html from local tech repair
if you have comments or other ideas i would love to hear them.
thanks for reading,
josh (Local Tech Repair)

Wednesday, January 26, 2011

keep track of who access your site.

if you have a login based site and your wanting to keep track of who logs in and where they are login in from. here is a simple script that helps you do this.
you can also use this for users to be able to see where they have logged in from so they know if someone else is login in using their name.

------------script--------
<?php
include "../connect.php";   //brings in connection information
$ip = $_SERVER['REMOTE_ADDR'];  // grabs the users IP address
$username = $_COOKIE['Username'];  // checks for the username probably be smarter to use a session so the cookie does not get deleted
$date = date('Y-m-d H:i:s');  // grabes the server time
$sql = "insert into loginHistory (ip, username, datetime) VALUES ('$ip','$username','$date')"; // insert query
$result=mysql_query($sql); // finally inserts it.
?>
-------------------------------


from here if you wanted you display it in different manners how ever you want to.

for instance below you could do...


--------------script2------------------
include ("../connect.php");
// Build SQL Query
$sql = 'SELECT * FROM `loginHistory` ORDER BY `id` DESC LIMIT 0, 20 ';
$numresults=mysql_query($sql);
$count = 1 + $s ;
print " <table border='1' cellspacing='3' cellpadding='2'>";
// now you can display the results returned
print "<tr><td>Count</td><td>IP Address</td><td>User</td><td>Date and Time</td></tr>";
while ($row= mysql_fetch_array($numresults)) {
$title = $row["IP"];
$title2 = $row["username"];
$title3 = $row["datetime"];
print "<tr><td>";
echo "$count";
print "</td><td>";
echo "$title";
print "</td><td>";
echo " $title2" ;
print "</td><td>";
echo " $title3" ;
print "</td></tr>";
$count++ ;
}
print "</table>";

?>
--------------------------------------------------------
what this does is create a table and then fill it with a count, ip address, username, and date time that they last checked the page.

warning if you have a lot of members this script can put a lot of stress on your system because this will log each time the user loads a page or what ever page you put this on... if you put this on the login you will not have that problem though. it will only log once.

Creating a Login System Part 2

So i am going to continue the login system that i had started in the part one of this series.
and you can find that here
http://localtechrepair.blogspot.com/2011/01/creating-login-page-part-1-website.html

so now that we have added members to our database we can login as them

lets post some code to look at.

first we will start with the login screen and then from there what we use to check the login credentials. login will be our index page.

---------------index.php------------------

<?php
if( isset( $_COOKIE['Username'] ) )
{
if( isset( $_COOKIE['Passhash'] ) )
{

$user = $_COOKIE['Username'];
$pass = $_COOKIE['Passhash'];
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$user = ereg_replace("[^A-Za-z0-9]", "", $user );
$pass = ereg_replace("[^A-Za-z0-9]", "", $pass );
include_once "connect.php";
$sql="SELECT * FROM members WHERE username='$user' and password='$pass'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){
// Register $myusername, $mypassword and redirect to file "Home.php"
session_register("myusername");
header("location:home.php");
}}}
$title = "local tech repair";
include ("header.php");
?>
<td class="left_content"><div align="center"><strong>Here are some useful links</strong></div><br />


<?include "leftside.php";?>


</td>
<td class="body_content"><strong><h4></h4></strong>

<form name="form1" method="post" action="./checklogin.php">
<td>
<table border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<center><strong><h1></h1></strong></center>
<p>Study</p>
<tr>
<td colspan="2"><strong>Member Login </strong></td>
</tr>
<tr>
<td>Username:</td>

<td><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password:</td>

<td><input name="mypassword" type=PASSWORD id="mypassword"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
<p>
Are you a corban student and want to join. <a href="register.php">click here and join</a>
</p>
<p>
<!-- Lost your password? click <a href="recovery.php">here</a> -->
</p>
</td>
</form>



</td>
<?
include ("footer.php");
?>

---------------------------------------------
-----------checklogin.php--------------

<?
// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$date_of_expiry = time() + 86400 ;
setcookie( "Username", "$myusername", $date_of_expiry );


ob_start();
$tbl_name="members"; // Table name

include("connect.php"); //connect to database

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
// this only allows alpha numeric passwords.
$myusername = ereg_replace("[^A-Za-z0-9]", "", $myusername );
$mypassword = ereg_replace("[^A-Za-z0-9]", "", $mypassword );
// encrypts with sha512 bit + salt to help protect against rainbow table cracking.
$salt = "website";
$encrypted_mypassword=hash('sha512', $salt.$mypassword);
setcookie( "Passhash", "$encrypted_mypassword", $date_of_expiry);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$encrypted_mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){
$query3 = "SELECT * FROM members WHERE username='$myusername' and password='$encrypted_mypassword' and privlege='Admin'";
$result3=mysql_query($query3);
$count2=mysql_num_rows($result3);
if ($count2==1){
setcookie('Admincookie', 'admin395', $date_of_expiry);
}
// Register $myusername, $mypassword and redirect to file "Home.php"
session_register("myusername");
header("location:home.php");
}
else {

// else if fales it will go back to the login page.
header("location:index.php");
}

ob_end_flush();
?>

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

so i will explain a little bit what this does.

first the index page just is a normal form asking for your user name and password the user types that in then submits the form

it then goes to the checklogin.php from there it saves the username to a cookie for later use.
it then strips all the mysql escape characters and strips any slashes from both username and password that the user submitted. the password then is hashed in to a sha2 512 bit hash with a salt added at the beginning. you can also add a the random salt if you like. i do that on my own websites.
the database is then queried to see if their is a match for the username and passwords hash. if there is 1 then the script continues and checks to see if they are admin user or not and also continues to start a session for them and then direct them to the home page. if they fail and there is no user it will redirect them to the login page.


i hope these scripts help you start making your own pages. you can do a lot more with these scripts but this is a start.

Tuesday, January 4, 2011

Creating a Login System Part 1, Website Series Part 1

This is a first part of a series of releases on building a website using PHP and MySQL. I will be going through simple ways coding what can be done. i will try to explain everything that is going on with a script so that you can learn it and understand each part of it. This is for beginners to intermediate level programmers. If you are an expert please post in comments with corrections and other helpful hints and please use sources or code examples.

first we will need to create a database and table for member IDs, their passwords, and for their password salt, and for their privilege level. I will explain the later 2 later in this tutorial.
i will be using PHPmyadmin to create the database and table
so
steps

naming the database

Naming the table and how many rows. we need 5 rows
ID is just a number we associate them in the database. also ID is A_I which means auto increment and it is also our primary key.

We now have our database so we can now start working on the pages. 
lets first make sure we can create a new member.
this is a simple form to add a member to the table
-----------addmember.php---------
<?php
$title = "Add Member";
include('header.php');
?>

<td class="left_content">
<?include "leftside.php";?>
</td>


<td class="body_content"><div align="center"><strong>Add a new member for login</strong></div> <br />
<br />


<form method="post" action="checkaddmember.php">
<table>
<tr><td align="left">Username</td>
<td><input type="text" id="username" name="username" size="20"></td>
</tr>
<tr><td align="left">Password</td>
<td><input type="PASSWORD" id="password" name="password" size="20"></td>
</tr>
<tr>
<td align="left">
Email:
</td>
<td>
<input name="email" size="25">
</td>
</tr>
<tr><td align="left">Type</td>
<td><select name="privlege">
<option value="user">User</option>
<option value="Admin">Admin</option>
<option value="Moderator">Moderator</option>
</select></td>
</tr>
<tr><td colspan="2">
<p align="center">
<input type="submit" name="Submit" />
</tr>
</table>
</form>
</td>
<?
include('footer.php');
?>



----------------connect.php-----------------------
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="blogspot_database"; // Database name

mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
?>

-------------checkaddmember.php-----------------------
<?
$title = "check";
include ("header.php");
?>
<td class="left_content"><div align="center"><strong>Here are some Use full links</strong></div><br />
<?include ("leftside.php");?>
</td>
<td class="body_content"><strong><h4></h4></strong>
<?php

include('connect.php');

$mypassword=$_POST[password];
$salt = "website";
$encrypted_mypassword=hash('sha512', $salt.$mypassword);
$Name = $_POST[username];
$user = mysql_query("SELECT * FROM members WHERE (username='$Name')");
$exp = "^[a-z'0-9]+([._-][a-z'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";


if ($_POST[username] != "") {
if ($_POST[password] != "") {
if ($_POST[email] != "") {
if (mysql_num_rows($user) == 0) {
if (preg_match('~@(corban.edu|)$~', $_POST['email'])) {
if (mysql_num_rows($email2) == 0) {

$sqlquery = "INSERT INTO members (username, password, privlege)
VALUES('$_POST[username]','$encrypted_mypassword','$_POST[privlege]')";
$results = mysql_query($sqlquery);

mysql_close();
print "<p><p>Thanks again for registering and i hope you have a wonderful time.</p>";

?>
<form name="form1" method="post" action="/checklogin.php">
<table border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="2"><strong>Member Login </strong></td>
</tr>
<tr>
<td>Username:</td>

<td><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password:</td>

<td><input name="mypassword" type=PASSWORD id="mypassword"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</form>
<?

} else {
echo "Email already exists try using <a href='recovery.php'>recovery</a>";
}
} else {

echo "bad email address! Please use a corban.edu email address.";

}} else {
echo "<p> User Already Exists</p>";
}} else {
print "Please Put in an email";
}} else {
print "Please enter a Password";
}} else {
print "Need Please go back and put in an username";
}
?>

</td>
<?
include ("footer.php");
?>
------------------------------------------------------------

Sense i am running out of time on this I will finish this in part 2

More Resources:

Thursday, September 30, 2010

000webhost and gzip compression

so i figured i write something on how to enable compression of your php files and your css files with the 000webhost provider.

what you will need to do is create .htaccess file.


in that file you will need to write

php_flag zlib.output_compression On
and save it to your /public_html/ folder


this will compress all your php files

for your scrypt.css you will need to change it to a .php file and add at the beginning

Sry i can't figure out how to add code to blogspot with out it messing things up
 
and make sure to change your .css extension in your header in your php files.

this will help speed up your website by compressing the data so that the visitors will have to download less.

this will not help speed up your photos or compress them. so still use a small photo format and use thumbs where ever posible to help speed up your website.

also some news is google is developing a photo format that they hope to take on jpg and png for web photo format

it is called right now WebP

for more information on that you can check out

http://news.cnet.com/8301-30685_3-20018146-264.html