PHP Tutorials – Hello :) https://blog.samyapp.com Wed, 20 Apr 2016 09:04:51 +0000 en-US hourly 1 https://wordpress.org/?v=4.8.7 102402223 Image Resizing with php https://blog.samyapp.com/image-resizing-with-php/ https://blog.samyapp.com/image-resizing-with-php/#respond Wed, 17 Sep 2008 16:23:58 +0000 https://blog.samyapp.com/?p=131 One of the great things about php is its built in support for the gd image library which makes creating thumbnails from images quite trivial, although you still need to calculate the correct dimensions if you want your thumbs to be resized proportionally. Here’s a function that takes a gd image, a maximum width and […]

The post Image Resizing with php appeared first on Hello :).

]]>
One of the great things about php is its built in support for the gd image library which makes creating thumbnails from images quite trivial, although you still need to calculate the correct dimensions if you want your thumbs to be resized proportionally.

Here’s a function that takes a gd image, a maximum width and / or maximum height and returns a new thumbnail image that fits into these sizes. The function can either scale the image proportionally so the whole image fits completely into the new size, or scale and crop the original so that the thumbnail is exactly the maximum width and height.


Download from GitHub.

If either the maximum width or maximum height is 0 or null then the function calculates these proportionally which is useful if you want all thumbnails a certain width and height and don’t care about the other dimension.

You can also specify an rgb background colour which will force the thumbnail to be exactly $max_width x $max_height with any space at the left and right (or top and bottom depending on whether the source image is portrait or landscape) filled in with the background colour.

I’ve written a couple of scripts to show usage of this function below – one creates thumbnails for every image in the same directory as the script, then generates html to show these. The other extracts images from a zip archive through a standard form upload and creates and returns a zip archive containing generated thumbnails.

You can copy and paste the code, or download the zip file containing all three scripts.

paGdThumbnail.php

<?php

function paGdThumbnail($image, $max_width, $max_height, $method = 'scale', $bgColour = null)
{
	// get the current dimensions of the image
	$src_width = imagesx($image);
	$src_height = imagesy($image);

	// if either max_width or max_height are 0 or null then calculate it proportionally
	if( !$max_width ){
		$max_width = $src_width / ($src_height / $max_height);
	}
	elseif( !$max_height ){
		$max_height = $src_height / ($src_width / $max_width);
	}

	// initialize some variables
	$thumb_x = $thumb_y = 0;	// offset into thumbination image

	// if scaling the image calculate the dest width and height
	$dx = $src_width / $max_width;
	$dy = $src_height / $max_height;
	if( $method == 'scale' ){
		$d = max($dx,$dy);
	}
	// otherwise assume cropping image
	else{
		$d = min($dx, $dy);
	}
	$new_width = $src_width / $d;
	$new_height = $src_height / $d;
	// sanity check to make sure neither is zero
	$new_width = max(1,$new_width);
	$new_height = max(1,$new_height);

	$thumb_width = min($max_width, $new_width);
	$thumb_height = min($max_height, $new_height);

	// if bgColour is an array of rgb values, then we will always create a thumbnail image of exactly
	// max_width x max_height
	if( is_array($bgColour) ){
		$thumb_width = $max_width;
		$thumb_height = $max_height;
		$thumb_x = ($thumb_width - $new_width) / 2;
		$thumb_y = ($thumb_height - $new_height) / 2;
	}
	else{
		$thumb_x = ($thumb_width - $new_width) / 2;
		$thumb_y = ($thumb_height - $new_height) / 2;
	}

	// create a new image to hold the thumbnail
	$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
	if( is_array($bgColour) ){
		$bg = imagecolorallocate($thumb, $bgColour[0], $bgColour[1], $bgColour[2]);
		imagefill($thumb,0,0,$bg);
	}

	// copy from the source to the thumbnail
	imagecopyresampled($thumb, $image, $thumb_x, $thumb_y, 0, 0, $new_width, $new_height, $src_width, $src_height);
	return $thumb;
}

The post Image Resizing with php appeared first on Hello :).

]]>
https://blog.samyapp.com/image-resizing-with-php/feed/ 0 131
A Simple PHP Contact Form https://blog.samyapp.com/a-simple-php-contact-form/ https://blog.samyapp.com/a-simple-php-contact-form/#comments Tue, 16 Sep 2008 17:47:20 +0000 https://blog.samyapp.com/?p=122 This is a simple php contact form / feedback form script I through together as an introduction to php for a friend. Rather than write a tutorial I’ve heavily commented the code. Hope its useful to somebody. WARNING – This was written a long time ago, and does not reflect current PHP best practice! [crayon-5bf331bc092bc612942321/] […]

The post A Simple PHP Contact Form appeared first on Hello :).

]]>
This is a simple php contact form / feedback form script I through together as an introduction to php for a friend.

Rather than write a tutorial I’ve heavily commented the code. Hope its useful to somebody.

WARNING – This was written a long time ago, and does not reflect current PHP best practice!

<?php

/*
    Turn on php's error / warning reporting system to show EVERY error message, 
    notice and warning. This is helpful for debugging scripts. see www.php.net/error_reporting

    On an active website you might turn this down or off so that if an error occurs
    you don't give the visitor any information about how your site works that might
    be of use to an attacker.
*/
    
error_reporting( E_ALL);

/*

 A simple php contact form

 This script displays an html page containing a form and when that form is submitted
 the script processes the submitted values and sends them as an email.

 It's a pretty simple script, but introduces a lot of the commonly used topics in php.

 I'd recommend skimming over the w3schools tutorials on php before trying to understand this,
 or flipping between this and them. http://w3schools.com/php/default.asp

 ps, this stuff in between the slash-asterisk....asterisk-slash is a comment

 You can also have single line comments that begin with // 

 So its basically the same as java for comments

 Also it makes it easier to edit / view php code if the text editor you use has syntax highlighting 
 (using different colours for variable names, comments, etc.)

 I use htmlkit (the free version 292) http://www.chami.com/html-kit/download/ 
 but have heard good things about notepad++ http://notepad-plus.sourceforge.net/uk/site.htm

 If you want an easy to setup php / apache / mysql package try http://www.en.wampserver.com/
*/

// first initialize some variables that will be used to hold the values in
// the contact form. Doing this enables us to redisplay the values the user
// enters in case they leave some fields blank and we ask them to complete
// everything...
// Note that all variable names in php begin with the dollar sign $
// see http://uk2.php.net/language.variables for more info about variables in php

// the email address the submission will be sent to
// put your own address here
// the example.com domain name is reserved specifically for use in tutorials and examples
// like this one.
$my_email = 'youremailhere@example.com';

$name = '';    // will just hold the person's name
$subject = 'Hello';    // will hold the subject of their email. We give a default value of "Hello"
$email = "";    // the email address
$message = "";    // their message
// note above that php can either use two double quotes or two single quotes to enclose a string
// the difference is that strings using double quotes can contain other variables
// eg. if we had $somestring = "$subject World"; (using the $subject variable above, then
// $somestring would contain 'Hello World'. 

$submitted = false;    // we will set this to "true" if the user successfully submits the form

$errors = array();    // create an empty array to hold any error messages we may want

/*
 Here we check if the user has submitted the form.
 http://www.w3schools.com/php/php_post.asp and http://www.w3schools.com/php/php_get.asp 
 provide a bit of info on what the GET and POST methods are used for.

 These are a simple but *extremely* important concept for php programming as they are how scripts 
 get input / data from the user.
*/

// if the user has submitted the form (by pressing the "Send" submit button, then the value
// of this button will be in the $_POST array with the key / name 'send'
//
// php arrays are similar to java hashmaps, but with a much simpler syntax to use them.
// see the php manual http://uk3.php.net/manual/en/language.types.array.php or 
// w3schools http://www.w3schools.com/php/php_arrays.asp
// php array article for why it is written $arrayname['keyname']
if( isset( $_POST['send'] ) ){  // isset is a function that tests if a variable is "set", that is "defined"

    // get the form values for each variable we want
    // the trim() function just removes any extra white space (spaces, tabs, etc) from the variable
    $name = trim( $_POST['name'] );
    $subject = trim( $_POST['subject'] );
    $email = trim( $_POST['email'] );
    $message = trim( $_POST['message'] );

    // check that the user has filled in everything by ensuring they have at least typed *something* in
    // each field. The minimum required length is hard-coded below.

    // check the name is at least 2 characters long.
    // strlen() is a function that checks the length of a string,
    if( strlen($name) < 2 ){
        // name too short, lets inform the user.
        // in php you assign something to the end of an array
        // by using the [] empty square brackets 
        $errors[] = 'You must enter your name';
    }

    // check the length of the subject and message
    if( strlen($subject) < 2 ){
        $errors[] = 'Please enter a subject for your message';
    }
    if( strlen($message) < 5 ){
        $errors[] = "You haven't written a message :(";
    }

    // we should do some better validation of the email address to make sure it is a real
     // one but here i'm just using a simple regular expression to check it looks sorta ok
    // regular expressions are very useful and powerful but take a while to get your head around
    // the pattern below basically matches any string that: see http://uk3.php.net/manual/en/book.pcre.php for info on regular expressions

    // i) begins with one or more of the letters a-z, the numbers 0-9, _ . or -
    // ii) followed by the @ sign
    // iii) followed by one or more letters, numbers _ . or -
    // iv) followed by another ., followed by one or more letters
    // eg. someone   @   example  .com
    //     (i)  (ii)   (iii)    (iv)

    if( !preg_match('/^[a-z0-9_.-]+@[a-z0-9_.-]+.[a-z]+/i', $email) ){
        $errors[] = "How can I reply to you if you don't give me a valid email address?????";
    }

    /* one last but important step is to check the user submitted values aren't a spammer
      trying to hijack our form to send spam emails on their behalf. This isn't something
        I'm going to go into in any detail here, but is important to know about:
     
        for more information see: 
            http://www.thesitewizard.com/php/protect-script-from-email-injection.shtml
            http://www.phpit.net/article/php-security-3-example-exploits/

        We use a simple regular expression to only allow the letters a-z, numbers 0-9 and
        a few bits of punctuation in our email address, name and subject fields.
        Basically we don't let the user submit anything that might be dodgy, although this
        does mean we can't have submissions using characters that aren't in the english language.
        Which might suck a bit.
    */
    $testRegEx = '/^[a-z0-9!"():;@#/\.,<>_ -]*$/i';
    if( !preg_match($testRegEx, $name) || !preg_match($testRegEx, $email) || !preg_match($testRegEx,$subject) ){
        $errors[] = 'Your name, email address or subject contained invalid characters. Please re-enter.';
    }

    // if we have found any errors then we don't want to send the email
    // we can tell if there are any errors by checking the number of entries in
    // our $errors array.
    // In php you check the size / number of items in an array using the count() function
    if( count( $errors ) == 0){

        // no errors, send the email using php's mail($to, $subject, $message, $headers) function
        // first we create two more strings $full_subject and $full_message which
        // will contain slightly modified versions of the original

        // we prepend 'Contact form submission' to the user's subject, so when it shows up in our
        // email client we know it came from our form
        // Notice that php concatenates strings using the period . not a + like in java.
        $full_subject = 'Contact form submission: ' . $subject;

        $full_message = "$name sent the following message at " . date('H:i:s') . ' on ' . date('l jS F Y'). " from ip address {$_SERVER['REMOTE_ADDR']}nn";
        $full_message .=$message;

        // ok should probably explain what the two lines above do :0)
        // "$name sent..." places the contents of the $name variable into the string
        // date('H:i:s') gets the current time in the format 12:01:54 (hours:minutes:seconds)
        // date('l jS F Y') gets the current date in the format "wednesday 16th July 2008"
        // see www.php.net/date for more info (and note that you can access php info quickly at
        // php.net by placing what you are looking for after the domain name, eg. php.net/arrays php.net/strings

        // the {$_SERVER['REMOTE_ADDR']} imbeds the ip address of the current user into the string as well.
        // $_SERVER is an array containing info from the server. array entries can be embedded in strings by
        // surrounding them with curly brackets {...}

        $full_email = "$name <$email>";

        // the $headers parameter to the mail() command adds some important headers to the email, such as from and reply-to addresses.
        $headers = "From: $full_emailrnReply-To: $full_emailrnErrors-To: $my_email";

        // on your home pc, the mail function may not be able to work ok and will output an error.
        if( mail($my_email, $full_subject, $full_message, $headers) ){
            $submitted = true;    // we use this variable later to decide whether to show the form or a thank-you message
        }
        else{    // if mail() failed then we have a server configuration error...
            $errors[] = 'Sorry, due to server issues your message could not be sent. Please try talking to me instead :p';
        }

    }
}

/*
 thats's most of the code, now we come out of php mode and add
 an html page containing a simple form.

 we mix a bit of php with it to check:
 1) has the form been submitted? if so then just display a message, no form
 2) if displaying the form, are there any errors? if so, display them
 3) we output / echo / print any values the user has already submitted for the form
 4) we echo the uri of this script into the form's action="" parameter so that the form
    submits back to this page

 A couple of notes about a couple of functions used below:

 htmlspecialchars() takes a string and returns the same string with any characters that have special meaning in
 html converted to display properly.

 nl2br() Converts any newline characters in the string to html <br /> line break tags (because html just treats newlines as
 spaces.

 echo is a php function that prints the values of its parameters to the screen. You could also use print()

*/
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<?php

// if the form has been successfully submitted, just display a message showing what was sent:
if( $submitted ){

?>
    <h1>Thank You!</h1>
    <p>Thank you for contacting us. The following message was sent from <?php echo htmlspecialchars($name)?>, <?php echo htmlspecialchars($email)?>:</p>
    <p>Subject: <?php echo htmlspecialchars($subject)?></p>
    <p>Message: <?php echo nl2br(htmlspecialchars($message))?></p>
<?php

}
else{ // otherwise display the form

?>
    <h1>Contact Us :)</h1>
<?php
    if( count( $errors ) ){
?>
    <div style="font-weight: bold; color: red;">
        <h2>Please correct the following errors and resubmit the form:</h2>
<?php
        foreach( $errors as $error ){
            echo '<p>' . htmlspecialchars($error) . '</p>';
        }
?>
    </div>
<?php

    }    // end of test for error messages

?>
    <form action="<?php echo $_SERVER['SCRIPT_NAME']?>" method="post">
        <br />
        Your Name: <input type="text" name="name" value="<?php echo htmlspecialchars($name)?>" />
        <br />
        Your Email: <input type="text" name="email" value="<?php echo htmlspecialchars($email)?>" />
        <br />
        Subject: <input type="text" name="subject" value="<?php echo htmlspecialchars($subject)?>" />
        <br />
        Message: <textarea name="message" cols="60" rows="20"><?php echo htmlspecialchars($message)?></textarea>
        <br />
        <input type="submit" name="send" value="Send Message" />
    </form>

<?php

}    // end of the if statement that checks if the form has been successfully submitted

?>

</body>
</html>

Feel free to send me some feedback on this if you found it useful :0)

The post A Simple PHP Contact Form appeared first on Hello :).

]]>
https://blog.samyapp.com/a-simple-php-contact-form/feed/ 1 122