Tag: PHP

PHP Validate Email Address

When a user submits their email address in a form, you want to be sure it is a real email address. We will use the function preg_match() to see if it matches our regex for emails.

[code lang=”php”]

[/code]

You can submit the email to this function using something like this:

[code lang=”php”]

[/code]

It is that simple! 🙂 Enjoy.

Filed under: Web ProgrammingTagged with: , ,

PHP Get File Size of Remote File

Previously in a post I made for uploading a file from URL we wanted to include a file size check to make sure the file wasn’t too big before we upload it. Here I’ll show you how to get the remote file’s size and other information before doing other functions with it.

We’ll do this through a simple form. By default a form will encode all characters and convert spaces to “+” so we will leave the enctype undefined.

Then we just need the text input named “url” which I gave a default value “Enter URL Here…” and the Javascript-related attribute – onfocus. So when you focus on the text input it will change from the default value to blank.

Finally of course, we include the submit input named “submit” with the value “Submit.” We will use this value to check that the  form was submitted.

[codesyntax lang=”html4strict” title=”HTML Form”]
<form action=”getinfo.php” method=”post”>
<input type=”text” name=”url” size=”40″ value=”Enter URL Here…” onfocus=”if(this.value == ‘Enter URL Here…’) this.value = ”;” /> <input type=”submit” name=”submit” value=”Submit” />
</form>
[/codesyntax]

This HTML form will submit the entered url to getinfo.php.

We are going to the function fopen() to get the information we need from the remote file. There is one thing to be aware of using fopen() to retrieve this data. You need to be sure the fopen wrappers is enabled in your php.ini. This can not be changed using ini_set().

We are going to create a variable “contents” and add each line of the file to it as we read it. Then we will use the function mb_strlen() to get the file size of the variable. Normally we would use strlen(), however that will only read one character as one byte. That doesn’t really give you the most accurate reading if you have special characters in the file which are more than one byte.

By default the function fgets() reads each line of a file 1024 bytes at a time. The function runs until either the specified length is reached (1024 bytes) or to the end of the file. It is more resource efficient to specify a read length:

“Until PHP 4.3.0, omitting it would assume 1024 as the line length. If the majority of the lines in the file are all larger than 8KB, it is more resource efficient for your script to specify the maximum line length.”php.net

getinfo.php

[codesyntax lang=”php” title=”getinfo.php Source Code”]
<?php
// getinfo.php

if($_POST[“submit”]){
// Form is submitted.

// Check the fopen wrapper settings in php.ini
if (ini_get(“allow_url_fopen”) == 1) {

// Open the file.
$file = fopen(trim($_POST[“url”]), “r”);

if($file){
// We got the file.

$contents = “”;
while($line = fgets($file,1024)){
// Write each line to the string contents a kilobyte at a time.
$contents .= $line;
}

$filesize = mb_strlen($contents,”8bit”);
$kb = $filesize / 1024; // Returns the file size in kilobytes
echo “<strong>File Size</strong>:  “.$filesize.” bytes or “.$kb.” kilobytes.”;

} else {

echo “Remote file not found.”;

}

} else {

echo “Fopen wrappers not enabled.”;

}

}

?>
[/codesyntax]

The page will display the file size in bytes and kilobytes, as so:
File Size: 1024 bytes or 1 kilobytes.

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , , ,

PHP Image Verification in Forms

One of the most common ways to stop bots and spammers from generating spam in people’s websites is using some form of image verification. This can be done very easily with just PHP and Sessions. Using image verification acts as a human detector, to make sure the viewer of that page is not a bot of some kind. Bots can cause damage to your server by overloading it with spammed content and flooding your boards with unwanted links and text.

Let’s say we have a form that submits a few fields and possibly a file:

[code lang=”html”]

Field 1:
Field 2:
File:

[/code]

Now, this form will submit three variables: field1, field2, and the file.

This form does not have any image verification added in. So any bot could simply process this page over and over to flood the server with crap. 🙁 So we are going to add a simple image verification to the form. To do this we make image.php:

[code lang=”php”]

[/code]

Now we must add the field to our form:

[code lang=”html”]
Verification: &amp;nbsp;

[/code]

Notice I used the class “imgverification.” We must add this to our <head> tags of the page:

[code lang=”html”]

[/code]

We must also make sure we include our session_start() on all pages we use session variables on. So on our form page, the image page, and submit page.

Now when the form is submitted to submit.php we check the submitted input for $_POST[“verification”] to $_SESSION[“md5_image_verification”].

[code lang=”php”]

[/code]

function simple_image($width,$height){
$image = imagecreate($width,$height);

$alphanum = “ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789”;
$rand = strtoupper(substr(str_shuffle($alphanum),0,6));
$_SESSION[‘simp_image_verification’] = $rand;
$_SESSION[‘md5_simp_image_verification’] = md5($rand);

$bgColor = imagecolorallocate($image, 231,231,231);
$textColor = imagecolorallocate($image, 0,0,0);
$textSize = imagefontheight(1);
imagestring ($image, 5, 8, 2, $_SESSION[‘simp_image_verification’], $textColor);
header(“Expires: Mon, 26 Jul 1997 05:00:00 GMT”);
header(“Last-Modified: ” . gmdate(“D, d M Y H:i:s”) . ” GMT”);
header(“Cache-Control: no-store, no-cache, must-revalidate”);
header(“Cache-Control: post-check=0, pre-check=0”, false);
header(“Pragma: no-cache”);
header(‘Content-type: image/jpeg’);
imagejpeg($image);
imagedestroy($image);
return true;
}

Filed under: TutorialsTagged with: , , ,

PHP Upload file from URL

Let’s say you have a form on a page with the input for URL to a file so you can upload it to your server. You can do this using PHP functions.

Here is an example of a form to upload:

[code lang=”html”]

Enter URL:

[/code]

Now on upload.php we need to have PHP run an upload of the file based on the entered URL. Here is how it will look.

The form above submitted two variables, the url text, and the submit button (value “submit”). So when we start the PHP code, we check it was submitted with the submit button.

We trim the url submitted through the form using the function trim() for the url to be accessed then create a filename using the function basename(). We then check that the url exists after having these functions applied to it. This is what we are going to submit to upload.

$file = Opening the url submitted with read-only permissions. This is defined with the “rb.”

[code lang=”php”]
$file = fopen($url,”rb”);
[/code]

Once we have opened the file we create a random number. This is going to be added to the file’s name when we upload it so that no two files have the same name. This is done very simply with the function rand(). Simply set the minimum and maximum for random numbers.

$newfile = Open the new file we are creating on our server. This actually creates the file on the server in the folder $directory with the random number ($rand) and the file’s name ($filename). This is done with writing permissions so that we can write the data from the url file to this one.

[code lang=”php”]
$rand = rand(1000,9999); // random number 4 digits long
$filename = $rand . basename($url); // places random number in front of the url’s base name
$newfile = fopen($directory . $filename, “wb”);
[/code]

If this new file can be created, we start writing the data to the file. To do this we use the function feof(). So if the new file exists now, while we haven’t reached the end of the url file, we write this content to the one on our server. This sounds a little confusing but it is quite easy.

Code:

[code lang=”php”]
if($newfile){
while(!feof($file)){

// Write the url file to the directory.
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}

}
[/code]

This script basically says write the data of the url file up until we reach 8kb, to the new file we created on the server. You can adjust the maximum size in kb by changing the “8” to whatever you wish. Once it reaches the end of the file, it will stop writing.

Now let’s say we want to check for filetypes. No one wants people uploading unsafe filetypes to their server. This is a serious problem if you do not check the filetypes being uploaded. So once we establish that the file exists through the URL we are going to check its extension to match ones we allow.

$valid_exts = An array of the valid extensions we allow the user to upload. (i.e. image files).

[code lang=”php”]
$valid_exts = array(“jpg”,”jpeg”,”gif”,”png”);
[/code]

$ext = We find the extension of the file by using the function explode(). This function splits the url into an array based on a seperator, in this case the seperator is a period “.” to find the trailing extension. We then set this to all lowercase because that is what our valid extensions are in. Also, we use the end() function to this array because it is possible the url has more than one period in it. We want to make sure we get JUST the extension on the end.

[code lang=”php”]
$ext = end(explode(“.”,strtolower(basename($url))));
[/code]

Here is the complete code:

Upload.php

[codesyntax lang=”php” title=”upload.php PHP Source Code”]<?php
// UPLOAD.PHP
if($_POST[“submit”]){
$url = trim($_POST[“url”]);
if($url){
$file = fopen($url,”rb”);
if($file){
$directory = “./downloads/”; // Directory to upload files to.
$valid_exts = array(“jpg”,”jpeg”,”gif”,”png”); // default image only extensions
$ext = end(explode(“.”,strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$rand = rand(1000,9999);
$filename = $rand . basename($url);
$newfile = fopen($directory . $filename, “wb”); // creating new file on local server
if($newfile){
while(!feof($file)){
// Write the url file to the directory.
fwrite($newfile,fread($file,1024 * 8),1024 * 8); // write the file to the new directory at a rate of 8kb/sec. until we reach the end.
}
echo ‘File uploaded successfully! You can access the file here:’.”\n”;
echo ”.$directory.$filename.”;
} else { echo ‘Could not establish new file (‘.$directory.$filename.’) on local server. Be sure to CHMOD your directory to 777.’; }
} else { echo ‘Invalid file type. Please try another file.’; }
} else { echo ‘Could not locate the file: ‘.$url.”; }
} else { echo ‘Invalid URL entered. Please try again.’; }
}
?>

[/codesyntax]

When the form is submitted, PHP uploads the file to the directory – $directory – which is set to “./downloads/” by default. The function !feof() reads as – before reaching the end of a file. So while it hasn’t reached the end, write to $directory. Once the function returns false (when we have reached the end of the file) it will stop. The path to the file is given as “$directory.$filename.”

I have made a script for uploading multiple files from a URL or your computer’s HDD viewable here:

https://bgallz.dev/1345/php-upload-multiple-files-url/

Enjoy!

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , , , , ,

PHP Mail (Send Email)

If you have a contact us page or something that sends an email with the use of php, it will use the “mail()” function of PHP. Here is the function:

[code lang=”php”]mail(‘Send To’,’Email Title’,’Email Message’,’Headers’,’Parameters’);[/code]

Send To = Who the email is being sent to.
Email Title = Title of the email, appears in inbox.
Email Message = The body text of the message sent.
Headers = Specifies additional headers, like From, Cc, and Bcc.
Parameters = Specifies additional parameters.

Here is an example:

[code lang=”php”]

[/code]

You have to be careful with the mail function and using headers/parameters. These are often ways of hackers sending faulty information to the script which can allow for header infections, etc. Always be sure to clean your variables you are sending to the function.

Here is a good way to check an email with preg_match:

[code lang=”php”]
function check_email($str){
if(preg_match(“/^[a-z0-9&\’\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is”, $str)) {
$email = trim($str);
return $email;
}
}
[/code]

Enjoy!

Filed under: PHP, Web ProgrammingTagged with: ,

Uploading Files with PHP

With many forms you may want to include some sort of upload of a file. There are many functions for files in PHP that you can use to do this.

Some things you may want to consider when uploading a file to your server:

  • File extension – what type of file is being uploaded.
  • File size – How big is the file, should the be a limit?
  • What to do on a successful upload.

Here is a basic form uploading to the file “upload.php”.

[code lang=”html”]


[/code]

Now on upload.php we need to have code that reacts to this form being submitted, other wise nothing will happen obviously.

[code lang=”php”][/code]

That would be our code for upload.php. When the form is submitted it will execute that code and perform the upload as long as it passes the tests.

You  can specify any directory, extensions, filesize limit you want of course. Enjoy.

Filed under: Scripts, TutorialsTagged with: , ,

Using PHP with Email Activation

Let’s say you have a website with registration. However, you want to have all registered users verify their email address to their account before being able to use all the functions of your site. To do this we can use PHP and simply create an activation code for each user when they register.

Let’s make a simple HTML form that submits a username, password, and email address.

[codesyntax lang=”html4strict” title=”Registration Sample Form”]
<table width=”100%” align=”center” border=”0″ cellpadding=”2″ cellspacing=”0″>
<tr>
<td align=”left”>Username:</td>
<td align=”left”><input type=”text” name=”username” size=”25″ /></td>
</tr>
<tr>
<td align=”left”>Password:</td>
<td align=”left”><input type=”password” name=”password” size=”25″ /></td>
</tr>
<tr>
<td align=”left”>Email Address:</td>
<td align=”left”><input type=”text” name=”email” size=”25″ /></td>
</tr>
<tr>
<td align=”left” colspan=”2″><input type=”submit” name=”submit” value=”Submit” /> <input type=”reset” name=”reset” value=”Reset” /></td>
</tr>
</table>
[/codesyntax]

You would probably want to add a password confirm input or whatever else inputs you want in your registration. This is just for the purpose of submitting the value of the username, password, and email address to our function which will email the user based on the submitted email and include the username and password.

In your registration code you can make an activation code by the following:

[codesyntax lang=”php” title=”Generate Activation Code Function”]
<?php
function generateCode(){
$codelength = 20; // How long you want the activation code to be.
$characters = “abcdefghijklmnopqrstuvwxyz1234567890”; // All accepted characters.
$activatecode = “”;
for($i=0;$i&lt;=$codelength;$i++){
$activatecode .= substr(str_shuffle($characters),0,1);
}
return $activatecode;
}

$userActivationCode = generateCode();
?>
[/codesyntax]

Along with your registration code when you submit the user’s data to your mysql database you would include this in there. We must be connected to a mysql database in order to alter a table (in this case “users”). You can see how to connect to a Mysql database here! You will need to create a column in your users table for both the activation code and their activated status. Like so:

[code lang=”php”]
<?php
$createcolumn = mysql_query(“ALTER TABLE `users` ADD COLUMN activatecode VARCHAR(20)”);
$createcolumn = mysql_query(“ALTER TABLE `users` ADD COLUMN activatestatus INT(5) DEFAULT 0″);
?>
[/code]

The activatestatus column is used to check if their account is activated or not. Now, let’s make it so they have to click this link in their email after they have registered.

Upon registration we will send an email to them with this code in it.

[codesyntax lang=”php” title=”Send Activation Email Function”]
<?php
function sendActivationEmail($email,$username,$password,$actcode){
// Let’s make sure the email address is valid.
if(preg_match(“/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/”, $email)){

// Clean up the username and password.
$username = trim(addslashes($username));
$password = trim(addslashes($password));

if($username && $password){
// Now let’s send the email to them!

mail($email,”Welcome to mysite.com!” Thank you for registering! Below are your account details as well as your activation link needed to complete registration.\n\n
Username: $username\n
Password: $password\n\n
Your activation link:\n http://mysite.com/?actcode=$actcode\n\n
Thank you and welcome to the site!”);
// You can edit the details of the email however you wish of course.

return “Your activation email has been sent to the email specified.”;
} else {
return “Please enter a username and password.”;
}
} else {
return “Invalid email address entered.”;
}
}

// To send the email we define it as $sendEmail with the parameters of our submitted email, username, and password.
$sendEmail = sendActivationEmail($_POST[“email”],$_POST[“username”],$_POST[“password”], $userActivationCode);
?>
[/codesyntax]

This $sendEmail contains the returned value from our sendActivationEmail() function. So apon submitting the registration form this function is called, and stores the returned value in this variable. To display the result of this function you would simply echo or print the variable.

Example:

[code]
<?php
// Once the registration form has been submitted and we called our sendActivationEmail() function.
if(!empty($sendEmail)){ echo $sendEmail; }
?>
[/code]

Now, this function uses four variables that are pre-defined. The $actcode comes from the function we created called “generateCode”. The username, password, and email variables are coming from a form the user submits to register.

Okay, now we have sent them their email with the link. So when they click the link, what happens? Well we need to make this code. What we will do is execute a sql query to update their row in the table and set activatestatus = 1.

[codesyntax lang=”php” title=”Index.php Activate User PHP”]
<?php
if(isset($_GET[“actcode”])){

// Clean the activate code.
$activatecode = trim(addslashes($_GET[“actcode”]));

// Check for their row with that specified activate code.
$sql = mysql_query(“SELECT id FROM users WHERE activatecode = “.$activatecode.” AND activatestatus = ‘0’ LIMIT 1″);

if(mysql_num_rows($sql) > 0){
// Code exists and they aren’t active, let’s make them active.
$update = mysql_query(“UPDATE users SET activatestatus = ‘1’ WHERE activatecode = “.$activatecode.””);
echo “Your account has been activated!”;
} else {
// Code not found.
echo “Invalid activation code.”;
}
}
?>
[/codesyntax]

Now that the user’s activate status has been updated to “1” we can check this column when logging the user in. So when the user goes to enter their login details (username and password) we will simply add a “WHERE username = ‘$username’ AND password = ‘$password’ AND activatestatus = ‘1’“. This will ensure no unactivated accounts may login.

And there you have it. Email activation is quite useful. Enjoy.

Filed under: TutorialsTagged with: , ,

PHP preg_replace

Preg_replace in PHP uses regular expressions to replace matches in the subject with the given replacement. The syntax of preg_replace is as follows:

[code lang=”php”]
preg_replace(pattern,replacement,subject [,limit]);
[/code]

A good example of using preg_replace is with simple bbcode and smilies. However with more complex bbcode there are other ways that would proove to be much easier and more useful. Let’s say you want to replace smiley code with the image of your smilies.  Here is how you would do it with preg_replace:

[code lang=”php”]
$str = $_POST[“textbox”];

$smiliesFind = array(
‘/:\)/’,
‘/:P/’,
);

$smiliesReplace = array(
‘,
‘,
);

print preg_replace($bbcodeFind,$bbcodeReplace,$str);[/code]

This will take all of those matches in the input $_POST[‘textbox’] and replace it with the HTML code of the smiley’s image. Now, why does the find code use slashes like this?

When using regular expressions you need a syntax. The slashes provide that regular expression and the backslashes are needed to escape the parts that could be mistaken as something else in the preg_replace.  This goes for anything you want to escape when executing php code.

We can use preg_replace for some bbcode as well:

[code lang=”php”]
$bbcodeFind = array(
‘/\[color\=(.*?)\](.*?)\[\/color\]/is’,
‘/\[b\](.*?)\[\/b\]/is’,
‘/\[i\](.*?)\[\/i\]/is’,
);

$bbcodeReplace = array(
$2‘,
$1‘,
$1‘,
);

print preg_replace($bbcodeFind,$bbcodeReplace,$str);
[/code]

You can see the use of “(.*?)” in the find array. This will apply the code to any text found inside the tags we supply. This is how it would appear:

Green text!
Bold text!
Italic text!

Filed under: PHP, Web ProgrammingTagged with: ,

PHP Classes and Functions

A great way to organize your tons of functions you will most likely have on your website is by using classes. Classes can be used to hold many functions that you group together – usually by their purpose on the website.

For example, you would probably have functions for executing sql queries in a class of something like “sql”.

Here is how a class is shown in PHP:

[code lang=”php”]

[/code]

A class is created with “class” then space, the name of the class, and brackets (opening and closing).

Let’s say you created this class and you want to execute a function out of this class in your php page. To start a class on your page you have to give the class a variable, like so:

[code lang=”php”]
$sql = new sql();

// Execute function.
$sql->doSql(“SELECT * FROM tbl WHERE id = ‘5’”);
[/code]

This will set $sql as the variable for class “sql”. Executing the functions in a class are just the variable plus the arrow and the function.Continue reading

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , ,