Thu, 2 May 2024


Category: PHP Examples


How to remove symbols which are not digits from a string?

In order to do this you may use the following regular expression: <?php .... $strOutput = ereg_replace("[^[:digit:]]", "", $strInput); ... ?> In this case for example if Input is 43~34^67, the output will be: 433467
Mon, 28 March 2022

How to access information in the request header directly?

$headers = getallheaders(); foreach ($headers as $name => $content) { echo \"headers[$name] = $content<br>\\n\"; }
Mon, 14 March 2022

How to pass an argument to a function by reference in PHP?

<?php function SomeFunction(& $SomeArgument) { $SomeArgument=$SomeArgument+5; } $TestVar=10; SomeFunction($TestVar); echo $TestVar; // will print 15 !! ?>
Wed, 9 February 2022

How to check in PHP if a variable is a database result?

The special PHP function is_resource helps to do this. So to check if a variable is a database result you may do the following: <?php if(is_resource($myVar)) { ... } ?>
Sat, 5 February 2022

How to ensure that a PHP file can not be executed directly but just included?

This technique could be useful if you have some files to be included, and you wish to prevent that they are executed directly by placing their address in the web ...
Sat, 8 January 2022

How to access Microsoft SQL Server from PHP?

On Windows machines, you can simply use the included ODBC support and the correct ODBC driver. On Unix machines, you can use the Sybase-CT driver to access Microsoft SQL Servers ...
Tue, 28 December 2021

How to make PHP cookies independant of the users clocks set right?

You may use the following approach: <?php $value=(time+1800)+"|"+$YourData; SetCookie("YourCookie",$value); ?> ... <?php list($ExpTime,$YourVariable)=explode("|","YourCookie",2); if($ExpTime<time()){ ... } else{ ... } ?>
Thu, 23 December 2021

PHP vs. Perl?

(taken from PHP manual) The biggest advantage of PHP over Perl is that PHP was designed for scripting for the web where Perl was designed to do a lot more and ...
Wed, 22 December 2021

How to use call_user_func in PHP to call a function?

<?php function SimpleTest($x) { echo "Hallo ".$x; } call_user_func('SimpleTest',"netart"); ?>
Sun, 12 December 2021

How to get the content of a web page into a single string?

<?php ... $strHTML=join('',file('http://www.netartmedia.net')); ... ?>
Tue, 7 December 2021

What is a variable variable in PHP?

What is a variable variable in PHP?

A variable variable looks like : $$variable If for example $variable="netart"; and $anton="media"; then $$variable will contain the value "media" Example of calling variable functions <?php $variable="netart"; ${$variable.'_media'}(); ?> will call the function netart_media()
Sat, 4 December 2021

How to set explicitly the type of a PHP variable?

You can do this by using the special PHP function settype, the syntax is settype(string var, string type). Type could be "integer", "double", "string", "array" or "object" Be aware ...
Wed, 17 November 2021

How to change the root directory?

There is a special function for this in PHP called chroot. The syntax of this function is as follows: int chroot (string strNewDirectory) Be aware that if the directory change was not successful ...
Tue, 16 November 2021

How to get the list of available databases on your MySQL server?

<?php // Connect to the database $svrConn = @mysql_connect(\"localhost\", \"root\", \"\") or die(\"Couldn\'t connect to database server\"); $myDatabases = mysql_list_dbs($svrConn); $i = 0; while($row = mysql_fetch_object($myDatabases)) { ...
Wed, 13 October 2021

How to define variable-level constants?

<?php define(\"CONS_1\", \"this is a test\"); ?>
Sat, 28 August 2021

Do the FTP extension for PHP comes as standard with all versions of PHP?

The FTP extension for PHP comes as standard with all Windows binary versions of PHP, however if you\'ve got PHP installed on a Linux/Unix server then you’ll need to make ...
Mon, 23 August 2021

PHP free example: How to pad a string with another string?

PHP free example: How to pad a string with another string?

You may use the special PHP function str_pad <?php echo str_pad("Marco", 10, ">", STR_PAD_LEFT); ?> will display: >>>>>Marco
Tue, 17 August 2021

How to reverse a string?

You may use the special PHP function strrev <?php $myText="ALLEGRO"; echo strrev($myText); ?> will display: ORGELLA
Sun, 15 August 2021

How to unset a global variable inside of a PHP function?

In order to do this the $GLOBALS array should be used, for example: <?php function MyFunction() { unset($GLOBALS["myVar"]); } $myVar="value"; MyFunction(); ?>
Tue, 10 August 2021

How to write a function which ckecks if a specified file exists?

<? function FileExist($filename) { if(file_exists($filename)) { return false; ...
Sat, 7 August 2021

How to know when the data in MySQL table was last updated?

<?php ... $dataArray = mysql_fetch_array(mysql_query("show table status from databasename like ‘tablename’")); echo $dataArray["Update_time"]; ... ?>
Tue, 3 August 2021

How to destroy the variables associated with a session in 4.0.6 and below?

In order to destroy the variables associated with a session in 4.0.6 and below, you should use the special function session_unregister, for example: <?php session_start(); session_unregister($userName, "userName"); session_destroy(); unset($userName); ... ?>
Sun, 1 August 2021

How to get the length of a string in PHP?

$string_length=strlen($string);
Sat, 31 July 2021

How to destroy the current session and any variables associated with it?

In order to destroy the current session and any variables associated with it, you should use the special function called session_destroy() <?php ... session_destroy(); ... ?>
Fri, 30 July 2021

How to display the date in an appropriate format using PHP?

You should use the special date function in PHP. Take a look at the example <?php echo date("D M d"); ?> will ...
Fri, 16 July 2021

How to strip the PHP and HTML tags from a string?

To do this, you may use the strip_tags function. For example: <?php $stripped_content = strip_tags($html_content); ?>
Fri, 16 July 2021

How to open a zip file and read its contents?

resource zip_open ( string filename) The idea of the zip_open() function is to load in a zip file and interate through its contents <?php $zp = zip_open(\"/myfiles/blah.zip\"); while($zipFile = zip_read($zip)) { ...
Wed, 16 June 2021

How to remove the duplicate values from a PHP array?

<?php $arr=array("netart","media","netart"); $newArray=array_unique($arr); foreach($newArray as $strItem) { echo $strItem."<br>"; } ?>
Sat, 29 May 2021

How to check if a function has already been defined?

Use: bool function_exists ( string function_name)
Wed, 26 May 2021

How to read a folder content?

<?php $folder=dir("."); while($folderEntry=$folder->read()) { echo $folderEntry."<br>"; } $folder->close(); ?>
Mon, 24 May 2021

Example of calling variable functions

<?php $variable="netart"; ${$variable.'_media'}(); ?> will call the function netart_media()
Thu, 6 May 2021

How to create a simple WAP page using PHP?

<? header(\"Content-Type: text/vnd.wap.wml\"); echo \"<?xml version=\\\"1.0\\\"?>\"; echo \"<!DOCTYPE wml PUBLIC \\\"-//WAPFORUM//DTD WML 1.1//EN\\\" \\\"http://www.wapforum.org/DTD/wml_1.1.xml\\\">\"; ?> <wml> <card id=\"hello\"> <p>Today is <? echo date(\"m/d/Y\"); ?> </p> </card> </wml>
Fri, 30 April 2021

How to get the IP address of the visitor with PHP?

This will show the IP address of the visitor. <?php echo $_SERVER['REMOTE_ADDR']; ?>
Sat, 17 April 2021

How to force the execution of PHP scripts in HTML files?

To do this, you just need to modify .htaccess . You need to put the following line: AddType application/x-httpd-php .html .htm and then you don't need to rename your php files to ...
Wed, 17 March 2021

PHP vs. Cold Fusion?

(taken from PHP manual) PHP is commonly said to be faster and more efficient for complex programming tasks and trying out new ideas. PHP is generally referred to as more stable ...
Fri, 12 March 2021

How to wrap a string to a given number of characters?

For this purpose you may use the wordwrap function which is available from PHP 4.0.2 <?php $myString="long teeeeeeeext"; echo (wordwrap( ...
Sat, 6 March 2021

How to get all the keys of an PHP array?

<?php $arr=array(2=>"netart"),5=>"media"; array_keys($arr); //will return array(2,5) ?>
Sat, 27 February 2021

How to get the number of affected rows in previous MySQL operation?

You have to use the mysql_affected_rows() function, for example on delete command, in order to get the numbe rof the delted rows you need to do the following: <?php ... mysql_query("DELETE FROM ...
Mon, 22 February 2021

How to define an own error handling function for PHP to use instead of its default?

string set_error_handler ( string error_handler) Example: <?php function my_error_handler ($errno, $errstr, $errfile, $errline, $errcontent) { echo \"<font color=\'red\'><b>An Error Occured!</b></font><br>\"; echo \"<b>Error Number:</b> $errno<br>\"; echo \"<b>Error Description:</b> $errstr<br>\"; echo \"<b>Error In File:</b> ...
Fri, 5 February 2021

How to write to a file using PHP?

You may take a look at the sample function below which does this. <? function WriteToFile($strFilename, $strText) { if($fp = @fopen($strFilename,"w ")) ...
Mon, 1 February 2021

Is it possible in PHP to preserve the object methods when serializing the object?

No, unfortunately this is not possible. That means that whenever you serialize an object with the PHP function serialize, its methods will be lost (and you'll not be able to restore ...
Fri, 15 January 2021

How to disable error reporting on a single expression?

You can do this by preceeding the line with the source code by @ @$fp = fopen($YourFile,'r'); In this case PHP will not report an error if for example the ...
Tue, 12 January 2021

Can I access Microsoft Access databases?

Yes. You already have all the tools you need if you are running entirely under Windows 9x/Me, or NT/2000, where you can use ODBC and Microsoft\'s ODBC drivers for Microsoft ...
Tue, 5 January 2021

How to check if a specified filename is a directory?

For this purpose you may use the special php function, called is_dir, for example: <?php if(is_dir($YourFileName)) { ... } else { ... } ?>
Sat, 2 January 2021

How to check if a particular value exist in a specified array?

$arr=array("duron","celeron","xeon"); if(in_array("celeron",$arr)) { echo "celeron is present"; } ?>
Tue, 22 December 2020

How to calculate the similarity between two texts in percents?

In PHP this is very easy because there is a special function called similar_text which could be used. <?php $percentMatch=0; similar_text("take","toke",&$percentMatch); echo $percentMatch; ?>
Tue, 1 December 2020

How to tokenize a string?

You may use the special PHP function strtok <?php $myText="online pharmacy web solution"; $strToken=strtok($myText," "); while($strToken) { echo $strToken."<br>"; $strToken=strtok(" "); } ?>
Sat, 28 November 2020

How to automatically detect the links in a text with PHP regular expression?

<? $strText = 'this is a test http://www.netartmedia.net asda'; $strText = preg_replace( '/(http|ftp)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/i', '<a href="\0">\4</a>', $strText ); ...
Sun, 15 November 2020

How to connect to MS SQL Server with PHP and execute sql queries?

The FreeTDS library provides rich functionality for working with MS SQL Server databases. This library makes the work with MS SQL Server databases such easier as with every MySQL database. <?php --- $num= ...
Tue, 3 November 2020

How to use the parse_url function to parse an URL?

<?php $myDomain = parse_url(\"http://www.netartmedia.net/php.html#examples\"); echo \"Domain: \" . $myDomain[\"host\"] . \"<br>\"; echo \"Query String: \" . $myDomain[\"query\"] . \"<br>\"; echo \"Anchor: \" . $myDomain[\"fragment\"] . \"<br>\"; ?>
Sun, 25 October 2020

How do I create arrays in a HTML <form>?

To get your <form> result sent as an array to your PHP script you name the <input>, <select> or <textarea> elements like this: <input name=\"catlist[]\"> <input name=\"catlist[]\"> <input name=\"catlist[]\"> <input name=\"catlist[]\"> Treat the received ...
Fri, 23 October 2020

How to count all the values of an array using the array_count_values PHP function?

<?php $arr=array("netart","france","paris","netart","paris"); array_count_values($arr); // will return array("netart"=>2,"paris"=>2,"france"=>1) ?>
Fri, 16 October 2020

How to make the first character in a string uppercase?

You may use the special PHP function ucfirst. <?php $myText="i have a car"; echo ucfirst($myText); ?> will display: I have a car
Thu, 15 October 2020

How to get the number of fields in a MySQL result?

There is a special function in PHP, mysql_num_fields, which allows to do this. The syntax is as follows: int mysql_num_fields ( resource result)
Sat, 3 October 2020

How to dump information for a PHP variable?

In order to do this, you may use the special php function called var_dump. Take a look at the following example: <?php $myVar=array(array(array("x","y"),"z")); echo var_dump($myVar); ?>
Wed, 30 September 2020

How to set up a function which will be called at the end of the execution of the PHP script?

Be aware that this function will be called even id the connection with the client has been aborted or timed out and in fact that's why this approach could be ...
Sun, 13 September 2020

How to create a SESSION variable?

The sessions in PHP are very useful to pass data through the pages, (as http is stateless protocol). At every session is associated a unique session ID which can be ...
Wed, 19 August 2020

How to list all available server variables with PHP?

foreach ( $_SERVER as $key=>$value ) { echo ' $_SERVER[\''.$key.'\'] = \''.$value.'\'; }
Mon, 10 August 2020

How to translate certain characters in a string to other specified characters?

You may use the special PHP function strtr <?php $myText="rsédfà"; $newText=strtr($myText,"éà","ea"); echo $newText; ?> will display: rsedfa
Sat, 8 August 2020

How to get information about the installed modules on your machine?

<?php phpinfo(INFO_MODULES); ?>
Fri, 7 August 2020

How to know from where the visitor came to your web site?

This will show the URL address from which the visitor came from <?php echo $_SERVER['HTTP_REFERER']; ?>
Mon, 3 August 2020

How to strip the whitespaces at the beginning and the end of a string?

You may use the special PHP function trim. <?php $myText=" car "; echo trim($myText); ?> will display: "car"
Thu, 30 July 2020

How to write a regular expression which validates an email address?

To do this, you may use the following php function: <?php function IsValid($strEmail) { if(eregi("^[a-z0-9._-]+@[a-z0-9._-]+.[a-z]{2,4}$", strEmail)) { return true; } else { return false; } } ?>
Sun, 26 July 2020

How to check for special symbols in the user input?

You may use the following regular expression: /^[a-zA-Z0-9_\-+ \t\/@%\.]+$/ For example: return (preg_match('/^[a-zA-Z0-9_\-+ \t\/@%\.]+$/', $str);
Sat, 18 July 2020

How to get a line from file pointer and strip the HTML tags in single instruction?

In PHP there is a function very similar to fgets which is not very well known, the fgetss function. The only difference between fgetss and fgets is that fgetss strip ...
Thu, 16 July 2020

How can I pick one or several random values contained in a PHP array?

You may use the array_rand function which is available from PHP version 4.0.0. <?php $arr=array("netart","france","paris","media"); $arr_random=array_rand($arr,2); echo $arr[$arr_random[0]]."<br>".$arr[$arr_random[1]]; ?>
Fri, 10 July 2020

How to get all the POST method variables are available?

foreach ($_POST as $var => $value) { echo \"$var = $value<br>\\n\"; }
Mon, 15 June 2020

How to remove the file extension from a file name using PHP?

function RemoveExtension($strName) { $ext = strrchr($strName, '.'); if($ext !== false) { ...
Sat, 6 June 2020

How to delete an entire MySQL database?

The mysql_drop_db should be used for this purpose. The function syntax is as follows: bool mysql_drop_db ( string database_name) the function returns TRUE on success, FALSE on failure.
Wed, 6 May 2020

How to count the number of substring occurencies?

You may use the special PHP function substr_count <?php $myText=" the car is red "; echo substr_count($myText,"is"); ?> will display: 2
Wed, 15 April 2020



See All Scripts




Subscribe for our newsletter

Receive the latest blog posts direct in your mailbox