Short Tag – Web Development Blog

Entries Tagged ‘PHP’

PHP str_replace

PHP’s str_replace function will replace every occurrence of the selected string with another string.

echo str_replace("car", "bike", "That car is red!");

The code above displays the text: That bike is red!
Function parameters:
str_replace(searched_string, replacement_string, target_string, count)
searched_string – the string that will be replaced
replacement_string – the string that will be used to replace the searched string
target_string – the string [...]

PHP constants

The constants in PHP (and in any other programming language) are used to store data.
So, what’s the difference between variables and constants?
They both store data, but a variable can be modified anywhere in the code, and a constant cannot be modified. You can try to modify it, PHP won’t return any error, but it won’t [...]

CGI script and PHP

CGI it’s not a programming language. CGI(Common Gateway Interface) it’s just an interface between the http server and the software residing on the host machine.
You can write CGI script using a variety of programming languages: PHP, PERL, C, C++, etc.
Why use CGI scripts?
CGI scripts are very useful when you need to combine PHP with other [...]

[PHP] Get file and directory list from a folder

If you need to get the list of files and directories from a folder you should use this piece of code:

$mydir = opendir("directory");

while($entryName = readdir($mydir)) {
$dirArray[] = $entryName;


Now $dirArray contains a list of all files and folders in the given directory. This array contains even the two pointers each directory has: ‘.’ (current directory) and [...]

file_get_contents() timeout in PHP

Though file_get_contents is not so advanced as CURL we can use it in lots of situations. In case you use file_get_contents and you need to set for how long to try to make connection you can use stream context.
First we create the stream context:
$sc = stream_context_create(array( ‘http’ => array( [...]

Datediff function in PHP (similar to VB)

A function that calculates the difference between 2 dates.  It is very similar to the datediff function available in Visual Basic.

function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {

if (!$using_timestamps) {

$datefrom = strtotime($datefrom, 0);

$dateto = strtotime($dateto, 0);


$difference = $dateto – $datefrom; // Difference in seconds

switch($interval) {

case ‘yyyy’: // Number of full years

$years_difference = floor($difference / 31536000);

if [...]

Check if String is AlphaNumeric in PHP

function isAlphaNumeric($text)
if(ereg(‘[^A-Za-z0-9]‘, $text))
return false;
else return true;

We check if a String is alphanumeric, if a string contains only characters and numbers, useful for validating usernames.