Category Archives: PHP

(PHP) Eloquent doodles for Laravel

// Get model by primary key
$myModel = MyModel::find($id);

//Where can use short syntax for equal comparison.
$myModels = MyModel::where('someAttribute', '=', 'someValue')->get();
$myModels = MyModel::where('someAttribute', 'someValue')->get();

// Delete models
$affectedRows = MyModel::where('someAttribute', 'someValue')->delete();

// Select distinct
$distincts = MyModel::distinct()->select('someAttribute')->where('someAttribute', 'someValue')->get();

// Select with Limit and offset
$myModels = MyModel::limit(30)->get();
$myModels = MyModel::limit(30)->offset(30)->get();

Different ways of getting a single model and checking if it’s there.


// 1
$model= MyModel::where('someAttribute', $someValue)->get();

if (!$model->isEmpty()) {
    $firstModel= $model->first()
}


// 2
try {
    $model= MyModel::where('someAttribute', $someValue)->firstOrFail();
    // Do stuff with model
} catch (ErrorException $e) {
    // Do stuff if it doesn't exist.
}


// 3
$models = MyModel::where('someAttribute', $someValue)->get(); // Collection of models
$models = MyModel::where('someAttribute', $someValue)->first(); // Single model or null

if (count($models)) {
    //Collection: to get the first item
    $users->first().
    
    //if you used first() just use the $models
}

(PHP) simple picture/file upload script

Here is a simple tutorial script that uploads a file to a folder on the server. In this example it is assumed that the file is an image and it will be outputted on screen in an img-tag. But the file uploading mechanics works for any file type.

<?php
if(isset($_POST['submit']))
{
    $temp_name = $_FILES["file"]["tmp_name"]; // get the temporary filename/path on the server
    $name = $_FILES["file"]["name"]; // get the filename of the actual file
 
    // print the array (for reference)
    print_r($_FILES);
         
    // Create uploads folder if it doesn't exist.
    if (!file_exists("uploads")) {
        mkdir("uploads", 0755);
        chmod("uploads", 0755); // Set read and write permissions of folder, needed on some servers
    }
         
    // Move file from temp to uploads folder
    move_uploaded_file($temp_name, "uploads/$name");
    chmod("uploads/$name", 0644); // Set read and write permissions if file
 
}
?> 
     
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="submit"/>
</form>

(PHP) Simple gallery with thumbnail generation

This is an enhanced version of this

It’s a VERY simple php gallery. You could develop it in any direction. This one only supports jpg, but that could be augmented as well.
Here’s what it does:

  • Allows the user to choose an image and enter a title (or caption).
  • Uploads the image to a folder on the server.
  • Creates a thumbnail
  • Enters the filename and caption in a MySQL database.
  • Output all the images.

Continue reading

(PHP) Simple e-mail contact form.

A simple contact form, just for reference. Will add more info later on…

<?php
if (isset($_POST['submit'])) {

	$name = $_POST['name']; //name of sender
	$email = $_POST['email']; //e-mail of sender
	$email = stripslashes($email);
	
	$subject = $_POST['subject']; //e-mail subject 
	$subject = str_replace(array("\r\n","\r","\n"), "", $subject); //remove any linebreaks to keep from code injections

	$message = $_POST['message']; // e-mail message
	$message = str_replace(array("\r\n", "\r"), "\n", $message); // fix line-breaks
	$message = stripslashes($message);

	//headers
	$headers = "From:$name<$email>\r\n";
	$headers .= "Return-path: <$email>\r\n";
	$headers .= "Content-type: text/plain; charset=UTF-8\r\n";
	$headers .= "Content-Transfer-Encoding: 8bit\r\n";
	
	$to = 'myadress@mydomain.com'; //recipients e-mail adress

	//validate email and name variables
	if (!filter_var($email, FILTER_VALIDATE_EMAIL))
	{
		echo 'not a valid e-mail adress';
		die();
	}
	if (preg_match('/[^a-z åäöÅÄÖüÜ _-]/i', $name))
	{
		echo 'not a valid name format';
		die();
	}

	//send the email
	$send = mail($to, $subject, $message, $headers);
	if ($send)
		echo 'email sent';
	else
		echo 'something went wrong, email not sent';
}
?>

<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8">
</head>
<body>
	<form action="" method="post">
		name:<br>
		<input type="text" name="name"/>
		<br>email:<br>
		<input type="text" name="email"/>
		<br>subject:<br>
		<input type="text" name="subject"/>
		<br>message:<br>
		<textarea name="message"/></textarea>
		<br>
		<input type="submit" name="submit"/>
	</form>
</body>
</html>

Convert MySQL timestamp to PHP date

If you save your date in the format of timestamp in your MySQL database, and want to output it like this:

$result = mysql_query("SELECT * FROM articles");
$row = mysql_fetch_array($result);
$date = $row['timestamp'];
echo $date;

Your date come out looking something like this: 2011-01-30 20:54:12
So it’s formated like YYYY-MM-DD HH:MM:SS

But what if you want it to display, say like this: Sunday, January 30th, 8:54pm
Normally you would use the date function and pass it a format string and a timestamp. Like this:

$result = mysql_query("SELECT * FROM articles");
$row = mysql_fetch_array($result);
$date = $row['timestamp'];
echo date("l, F jS, g:ia", $date);

But that will give you an error, since the second argument of the date function expects a UNIX timestamp (which is the number of seconds passed since 1970-01-01 00:00:00 until a given date).

In our example the variable $date holds a string that looks like this ‘2011-01-30 20:54:12‘. The date function doesn’t know what to do with that information. So we need to convert the date string to a UNIX timestamp.

Luckily there’s a function called strtotime(), that will take care of this for us.

$result = mysql_query("SELECT * FROM articles");
$row = mysql_fetch_array($result);
$date = $row['timestamp'];
$date = strtotime($date);
echo date("l, F jS, g:ia", $date);

After running the $date variable through the strtotime function (on line 4) it will hold the value 1296420852. The date function will now return the date of this timestamp – in the format we passed in the first argument.

Check out the date function on php.net to learn more about how to format the date string.

(PHP) How to make a simple gallery

This is just a VERY basic gallery that you can modify to suit your needs. For example you could add columns in the database and store more info about the images (date, size, tags etc.). You could very easily make the output use Lightbox or similar images viewers. And you could of course do a very solid file validation check.

Just to make it clear, I’m not doing any mime verification or size checking of the images, no login or session check (which would be used for uploading or deleting images) and no fancy presentation of the images. This is just a rudimentary , minimal gallery for you to get started. Think of it as a sponge cake base recipe.

Here’s what it does:

  • Allows the user to choose an image and enter a title (or caption).
  • Uploads the image to a folder on the server.
  • Enters the filename and caption in a MySQL database.
  • Output all the images.

I have chosen to break this up in four files, to keep it separated nice and clean. This solution will need a MySQL database. (if you need info on that, follow some tutorial like this).

Also, you need to create a folder, with appropriate read/write-rules, named “images” in the same folder as these scripts.

First off… The MySQL database table should look something like this:

CREATE TABLE IF NOT EXISTS 'gallery' (
  'id' int(11) NOT NULL AUTO_INCREMENT,
  'filename' varchar(128) NOT NULL,
  'title' varchar(1024) NOT NULL,
  PRIMARY KEY ('id')
) ENGINE= InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

And here’s the form (the ul-list is just to display the form in a somewhat non-horrible fashion):
gallery_form.php

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<style type="text/css">
	li {
		list-style: none;
	}
</style>

</head>

<body>

<form action="gallery_process.php" method="post" enctype="multipart/form-data">
<ul>
	<li>
    	Choose image
    </li>
	<li>
		<input type="file" name="file" id="file" />
	</li>
	<li>
    	Add title
    </li>
	<li>
		<input type="text" name="title" id="title" />
	</li>
	<li>
		<input type="submit" name="submit" />
	</li>
</ul>
</form>

</body>
</html>

Here’s the process that will save the image and update the database.
gallery_process.php

<?php
// This is just my database connection.
include 'includes/db_connect.php';

// Gather the information sent by the form
$temp_filename = $_FILES["file"]["tmp_name"];
$filename = $_FILES["file"]["name"];
$title = $_POST['title'];

/* Split the filename at every dot, take the last part and put it in $ext
(this will be the file extension) */
$splits = explode(".", $filename);
$index = count($splits) - 1;
$ext  = '.'.$splits[$index];

// Here's an alternative, more slick way of finding the file extension
// $ext = '.'.pathinfo($filename, PATHINFO_EXTENSION);

/* To get away from any pesky non-standard character problems, weird or duplicate
filenames I swap the filename for an 8-digit number. The loop will check if
an image of that name exists and add 1 to the number until the filename is unique. */
$new_filename_basenumber = 10000000;
$new_filename = $new_filename_basenumber.$ext;

while (file_exists("images/$new_filename")) {
	$new_filename_basenumber++;
	$new_filename = $new_filename_basenumber.$ext;
}

// Move the file to the server and give it the generated name.
move_uploaded_file($temp_filename, "images/$new_filename");

// Enter all information to the database and head over to the output
mysqli_query($link, "INSERT INTO gallery (filename, title) VALUES ('$new_filename', '$title')");
header("Location: gallery_output.php");
?> 

Here’s the output:
gallery_output.php

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
// Database connection
include 'includes/db_connect.php';

// Get all data from the database table
$result = mysqli_query($link, "SELECT * FROM gallery");

// Go through the table and output all images.
while ($row = mysql_fetch_array($result)) {
	$filename = $row['filename'];
	$title = $row['title'];
	$id = $row['id'];

	/* If a post is missing the physical image file, delete it from the database
	this is to keep redundant data to a minimum */
	if (!file_exists("images/$filename")) {
		mysqli_query($link, "DELETE FROM gallery WHERE id='$id'");
	}
	else {
		echo '
		<p>
		<a href="images/'.$filename.'" title="'.$title.'" >
			<img src="images/'.$filename.'" title="'.$title.'" width="100"/>
		</a>
		<a href="gallery_delete.php?id='.$id.'" onclick="return confirm(\'Are you sure you wish to delete the image?\')">Delete Image</a>
		</p>';
	}
}
?>

<p><a href="gallery_form.php?">Add new image</a></p>
</body>
</html>

And last the delete image process:
gallery_delete.php 

<?php
// Connect to database
include 'includes/db_connect.php';
// Get the database id of the post to delete
$id = $_GET['id'];

// First get the data and find the filename
$result = mysqli_query($link, "SELECT * FROM gallery WHERE id='$id'");
$row = mysqli_fetch_array($result);

$filename = $row['filename'];

// Then delete the file and the database post.
if (file_exists("images/$filename")) {
    unlink("images/$filename");
	mysqli_query($link, "DELETE FROM gallery WHERE id='$id'");
}

// And head back to the output page
header("Location: gallery_output.php");
?>