Category: Web Programming

Javascript innerHTML

Using Javascript, you can change the content of a certain tag just through basic javascript browser functions. This can be useful for navigation systems, content on a page to display, etc.

Here is an example:

[code lang=”html”]

[/code]

This is a basic javascript function to set the innerHTML of one id to the innerHTML of another. Now lets make the html in the body of the page.

[code lang=”html”]

Click here to change the content!

Content #1.

[/code]

When you click the link the content will change to #2.

Here is a good example for using navigation bars:

[code lang=”html”]

Link 1 | Link 2 | Link 3

Navigation details displayed here…

[/code]

You can view a live working version of these here!

Filed under: Web Programming

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: , , , , ,

Javascript onfocus in Forms

A nice feature to use with javascript in your forms, is a way to show the currently selected field. When a viewer is in a particular input field it will select that field however you would like – i.e. A border or background color change.

Here is a basic html/js for changing the border:

[code lang=”html”]


[/code]

onfocus: The input changes to a 2px size border on the focus.

onblur: The input changes back to default – 1px size border.

That is how you can simply change the border. However you may want to change other features, or maybe many features at once. For this I recommend using “this.className”. That way you can specify a new class all together and change many appearances.

[code lang=”html”]


[/code]

Now when it is selected it will change background color, border, and font weight. You can specify any style changes in the classes in css.

You can see functional examples of these here.

Filed under: 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: ,

Using HTML Meta tags

Meta HTML tags can be very helpful for gaining some search engine rank and promoting your website better. However, these simple tags are not going to drive your website immediately to the top of the lists.

Meta tags are basically information located in the head of your webpage(s). This content is not visible to the viewer, however does communicate with the browser.

Some of the most common meta tags include:

  • Description
  • Keywords
  • Character Set
  • Author
  • Robots

Here is an example for meta tags of a website about fast cars:

[code lang=”html”]



[/code]

The robots tag is used to tell whether or not a page should be indexed by search engines. For example, if you don’t want your page to be indexed use the following code:

[code lang=”html”]

Page Not Indexed


[/code]

The meta tags are supported by all major browsers out there. These can help your website with it’s niche and search engine listings.

Filed under: HTMLTagged 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: , ,

Mysql Database Connect

To connect to a Mysql database you need a few things first.

Of course you need to have the database created with a name you make up as well as the username and password of the mysql account that can connect to that database. This is very simple if you are using web managing software such as Cpanel or DirectAdmin. Under the Mysql databases area you can do all of this quickly.

For many websites mysql connections are included in a common file such as “config.php”. Here is how a basic mysql connection looks:

[code lang=”php”]
$host = “localhost”;
$db_username = “USERNAME”;
$db_password = “PASSWORD”;
$db_name = “DATABASE”;

mysql_connect($host,$db_username,$db_password) or die(mysql_error());

// should there be any errors, we will receive them before reaching any further
// we have connected to the mysql server successfully, now let’s get into the database

mysql_select_db($db_name) or die(mysql_error());

// if the following returns no errors, you are now connected to your mysql database
[/code]

$host – The host that you are connecting to. Usually set to “localhost”.
$db_username – The username of the account that connects to the database specified.
$db_password – The password of the account that connects to the database specified.
$db_name – The name of the database you are connecting to. This is shown in your domain managing area.

This code will connect to a mysql database and if there are any errors reported it will end php and display the errors.

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