file_put_contents() for PHP4!

July 30th, 2007 by Quatrux

When I was using PHP4 for my web stuff, I wrote a quite good function for usage with PHP4, as a lot of you know on PHP5 a very handy function file_put_contents(); exist, but not in PHP4, but if you want to use it on PHP4, due to your server still has it running, which in my opinion is still quite normal, I will share another of my functions, I just browsed around my sources which usually never is finished and found it, so thought to share, it is in my opinion quite different when the one offered on the PEAR package, but it does the same, just is a little bit expanded.. I will explain a little! Firstly I named it put_file_contents(); to avoid the risk of duplication, but for instance, just do a check with the simple function function_exists(); Moreover, I recommend to include your functions only once, I mean use include_once() and/or require_once() ;)

  1. function put_file_contents($file, $data, $mode = ‘a’, $path = ‘0′, $y = ) {
  2.         /* check if file exists and atempt to Create it */
  3.         if (!file_exists($file) && !touch($file)) {
  4.                 user_error(‘put_file_contents() Can not create the file’, E_USER_WARNING);
  5.                 return FALSE;
  6.         /* check if Directory exists */
  7.         } elseif (is_dir($file)) {
  8.                 user_error(‘put_file_contents() Can not write to a directory’, E_USER_WARNING);
  9.                 return FALSE;
  10.         /* check if file is regular */
  11.         } elseif (is_file($file)) {
  12.                 /* check the Flags */
  13.                 if (!strpos(‘**|a|w|t|’, ‘|’.$mode.‘|’)) {
  14.                         $mode = ‘a’;
  15.                 /* Change Owner if required */
  16.                 } elseif ($mode == ‘t’ AND !qcreate_file($file)) {
  17.                         user_error(‘put_file_contents() Can not change file owner’, E_USER_WARNING);
  18.                         return FALSE;
  19.                 }
  20.                 /* check if file is writabl/stronge otherwise try to change permsissions */
  21.                 if (!is_writable($file) && (!chmod($file, 0666) OR !qftp_chmod($file))) {
  22.                         user_error(‘put_file_contents() Can not write to file, permission denied’, E_USER_WARNING);
  23.                         return FALSE;
  24.                 /* Change Data Array to String */
  25.                 } elseif (is_array($data)) {
  26.                         $data = implode($y, $data);
  27.                 /* Check Input Data */
  28.                 } elseif (!is_scalar($data)) {
  29.                         user_error(‘put_file_contents() The 2nd parameter should be either a string or an array’, E_USER_WARNING);
  30.                         return FALSE;
  31.                 }
  32.                 /* Open and Store Data to File */
  33.                 if (($fo = fopen($file, $mode, $path)) === FALSE) {
  34.                         user_error(‘put_file_contents() Failed to open stream: Unknown reason’, E_USER_WARNING);
  35.                         return FALSE;
  36.                 }
  37.                 if (fputs($fo, $data) === FALSE) {
  38.                         user_error(‘put_file_contents() Failed to write to file: Unknown reason’, E_USER_WARNING);
  39.                         return FALSE;
  40.                 }
  41.                 /* Close Handle */
  42.                 fclose($fo);
  43.                 return TRUE;
  44.         } else {
  45.                 user_error(‘put_file_contents() Can not continue: Not a file’, E_USER_WARNING);
  46.                 return FALSE;
  47.         }
  48. }

As you can see, several times more of my stupid custom functions were used, you can remove them, but I will still share them, even though I don’t think they are useful.. I just tried to paste them, but I saw even more custom things :D So I think I will only leave and idea and not an actually working code.

Posted in PHP | 1 Comment »

PHP Designer 2007

June 3rd, 2007 by Quatrux

I wrote to the author of this software, which now is commercial, but doesn’t cost a lot a feature I want to see in PHP Designer, because without it, it really annoyed me and I was searching for alternative PHP IDE and was unhappy, due to most of those free ones sucked and others were costing to much.. So in the version of 5.3.2 in the changelog I saw my wanted feature.. Before that it could open last opened file or no files or all recent opened files, but it sucked, I wanted to open all the files which were opened before I closed the program, so it now does it and all I can say is that PHP Designer 2007 is one of the best IDE for PHP!

Get PHP Designer 2007

Posted in MySQL, PHP, Windows | No Comments »

Want to delete a PHP Session?

March 15th, 2007 by Quatrux

A lot of PHP novice programmers which don’t want to understand how the sessions work in the beginning, usually doesn’t delete a session the right way, so I wanted to post an example PHP script session_delete(); which deletes everything as needed.

  1. function session_delete($sname = ‘Current User’) {
  2.         # Set Session Name to a Variable
  3.         $name = session_name();
  4.         /* Empty the Cookie from Session */
  5.         if (!headers_sent() ) { setcookie($name,"",0,"/"); }
  6.         /* Remove the Cookie Value */
  7.         unset($_COOKIE[$name]);
  8.         /* Remove all the Info from the Super Global */
  9.         $_SESSION = array();
  10.         /* Free all session variables */
  11.         session_unset();
  12.         /* Destroy all data registered to a session */
  13.         if (session_destroy() === FALSE) {
  14.                 return FALSE;
  15.         } else {
  16.                 return TRUE;
  17.         }       
  18. }

Posted in PHP | No Comments »

What is the difference between ["PHP_SELF"], ["SCRIPT_NAME"] and ["REQUEST_URI"]?

March 15th, 2007 by Quatrux

What is the difference between ‘PHP_SELF’, ‘SCRIPT_NAME’ and ‘REQUEST_URI’ in the superglobal $_SERVER[] or also known as $HTTP_SERVER_VARS which is deprecated since PHP 4.1.0 and isn’t really a superglobal, but anyway, what is the difference? On different support channels and forums people ask this question and I tried to search google and didn’t find an answer, so I thought to write it here.

$_SERVER['PHP_SELF'];

The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar.

  • http://example.com/ — – — /index.php
  • http://example.com/test/index.php — – — /test/index.php
  • http://example.com/index.php?q=submit — – — /index.php
  • http://example.com/index.php/test/ — – — /index.php/test

So actually it returns the path to the current filename typed in the url without the QUERY_STRING, but when we us index.php/test/download/ it shows the path to ../test/download/ as we want it to do that, because usually using PHP_SELF is very useful with submitting forms, so having the PATH_INFO included in the PHP_SELF is a good idea and if you don’t want it, just use SCRIPT_NAME which will always show the executing file.

$_SERVER['SCRIPT_NAME'];

Contains the current script’s path. This is useful for pages which need to point to themselves.

  • http://example.com/ — – — /index.php
  • http://example.com/test/index.php — – — /test/index.php
  • http://example.com/index.php?q=submit — – — /index.php
  • http://example.com/index.php/test/ — – — /index.php/

So it is similar to PHP_SELF, just the PATH_INFO isn’t included, so you just point to the current filename executing. Note; that SCRIPT_FILENAME actually is the same, but it also returns the server root and acts the same as $_SERVER['DOCUMENT_ROOT']; . ” . $_SERVER['SCRIPT_NAME'];

$_SERVER['REQUEST_URI'];

The URI which was given in order to access this page; for instance, ‘/index.html’.

A lot of people usually don’t understand the usage of this, for example if you wanted to access index.html but it didn’t exist on the server, you get redirected to say 404.php page which says that the filename doesn’t exist, when you will try to use any other value, like PHP_SELF or SCRIPT_NAME it will print you /404.php and not the file you requested, but when you will use REQUEST_URI, it will print the full URL which you typed in order to get to that page, this sometimes is quite useful.

In addition, I recommend to use the constant __FILE__ if you want to get the absolute path to your current dir and if you want to set an include path, it is best to do it also with this constant by adding the function dirname(); like this: dirname(__FILE__);

  1. /* Change Super Global */
  2. $s =& $_SERVER;
  3. /* Set the Default Include Path */
  4. set_include_path( dirname( $s[‘SCRIPT_FILENAME’] ).‘/includes’. PATH_SEPARATOR . dirname(__FILE__) );

If you ask if this is different, when I will say yes it is. The first value points to the currently executing file like /index.php and the second value is pointing to the current included file directory, it even can be outside /public_html/ somewhere in /home/user

Sometimes people don’t want to get the filename, but only the Query of the GET method, so there is a value $_SERVER['QUERY_STRING']; which returns everything after the ?

  • http://example.com// — – — (nothing)
  • http://example.com/test/index.php — – — (nothing)
  • http://example.com/index.php?q=submit — – — q=submit
  • http://example.com/index.php/test/ — – — (nothing)
  • http://example.com/index.php/test/?q=submit — – — q=submit

Furthermore, if you want to get the server root, you can use $_SERVER['DOCUMENT_ROOT']; which usually returns something like /home/user/public_html/

Moreover, sometimes you can have an headache if you want to get the domain the script is currently running on, you ask why? because sometimes you can use not the right $_SERVER array key for that.. if you’ll be using $_SERVER['SERVER_NAME']; you will get the domain of the server, but say you’re using CPanel and added a domain through it and you will execute under it, you will still get the original server domain, this is called virtual host, in order to get it you need to use $_SERVER['HTTP_HOST'];

Read more about Reserved Server Variables on PHP dot net Manual!

Posted in PHP | No Comments »

PHP function scan_dir();

January 23rd, 2007 by Quatrux

As a lot of who knows,PHP5 has a very good function called scan dir, but ash many of use still like to use PHP4 we need to find aletrnatives for it so here is a good function I wrote years ago and want to share it with you :)

  1. /* #### SCAN DIR ####
  2. Input: Directory, 1 to rsort() and files to not index to the Array
  3. Output: makes an Array with filenames and dirs on Success or False
  4. Status: Complete
  5. Last Editor: Quatrux
  6. */
  7.  
  8. function scan_dir($dir, $s = ‘0′, $u = ) {
  9. /* Check if input is a Directory and Open it */
  10. if (is_dir($dir)) {
  11. if ($d[‘open’] = opendir($dir)) {
  12. $u = "**.|..|$u|";
  13. while (($d[‘file’] = readdir($d[‘open’])) !== false) {
  14. /* Don’t add unneeded Files */
  15. if (!strpos($u, $d[‘file’]) ) {
  16. /* Make an array with all left Files */
  17. $d[‘array’][] = $d[‘file’];
  18. }
  19. }
  20. closedir($d[‘open’]);
  21. } else {
  22. return FALSE;
  23. }
  24. } else {
  25. return FALSE;
  26. }
  27. /* Check if Directory is not Empty */
  28. if (!isset($d[‘array’])) {
  29. return FALSE;
  30. /* Sort the Array by Request */
  31. } elseif (is_array($d[‘array’])) {
  32. if ($s == ‘1′) {
  33. rsort($d[‘array’]);
  34. } else {
  35. sort($d[‘array’]);
  36. }
  37. }
  38. return $d[‘array’];
  39. }

Well, will need to find a plugin or something which would highlight the code or something, because now, I don’t even see tabs, oh well.. Stupid Javascript Editor for Wordpress ;)

Posted in PHP | No Comments »

Site Security ?

April 2nd, 2006 by Quatrux

Every Site wants to be secure ? right ? Well, I think I have overdone, but I feel alright now, I totally rewrote my Quatrux theSite CMS and now it is very secure, in fact I can run several sites on it in different directories.. cool isn’t it ? there are library files which is always used, they are placed in a non public directory, I mean /home/user/private/theSite-library/ which are included with php include function. No one can access that directory except for the owner of the files, ftp user and I made a quite cool chmod for it.

The site runs on one index.php file which has several lines to define stuff, and some files in /dir/ directory which is protected by password using .htaccess so no one can access it except for php, perl etc. all the passwords in settings file are hashed using random hasher numbers and I just check the value and never can know it, but for mysql passwords I made it like this ? decrypt($settings['mysql']['password']); and it returns the value, this function is my own written custom function. The other files is just the template for the site. :)

I made two mysql users for my database, one which is selected when you’re browsing the site, his privileges is only to use SELECT and another who is selected while browsing the Panel, it can SELECT, UPDATE and INSERT and nothing more, my database is frequently backed up automatically if something was changed in the panel. :D

The PHP scripts are written nicely and does not throw any errors, I have changed to xHTML 1.0 Transitional and it is Valid, same as CSS. In Fact I am waiting for CSS 3 version :D and with time I will integrate AJAX on my Panel for easy usage, I have learned javascript, now only need practice. ;)

Posted in MySQL, PHP, Webmastering | No Comments »

.htaccess files

December 11th, 2005 by Quatrux

Using .htaccess files on your server is really useful, I found out that you can change php.ini and httpd.conf/apache.conf configuration but if the server lets to do it, well so I will show an example of my htaccess file ;)

Apache [Show Plain Code]:
  1. #######################################
  2. # APACHE CONFIGURATION FILE BEGINNING #
  3. #######################################
  4.  
  5. #****************************************************+
  6. # Enable this, but some google bots get an 406 error *
  7. #****************************************************+
  8.  
  9. #Options MultiViews
  10.  
  11. #*********************************************+
  12. # Alternative to above and googlebot is happy *
  13. #*********************************************+
  14.  
  15. #Options -Multiviews
  16. #RewriteEngine On
  17. #RewriteBase /
  18. #RewriteRule ^quatrux/(.*) /quatrux.php/$1
  19. #RewriteRule ^quatrux$ /quatrux.php
  20.  
  21. #******************************************************+
  22. # Manage Index Options                                 *
  23. #                     you can also include HEADER.html *
  24. #                             and README.html files    *
  25. #******************************************************+
  26.  
  27. #IndexOptions FancyIndexing SuppressHTMLPreamble DescriptionWidth=*
  28. #AddDescription "JPG File" *.jpg
  29. #AddDescription "GIF File" *.gif
  30.  
  31. #****************************+
  32. # Add new Extensions for PHP *
  33. #****************************+
  34.  
  35. AddType application/x-httpd-php .q .do
  36.  
  37. #*************************************************+
  38. # Default Extension for Files having no Extension *
  39. #*************************************************+
  40.  
  41.  # DefaultType application/x-httpd-php
  42.  
  43. #************************+
  44. # Default Index Settings *
  45. #************************+
  46.  
  47. DirectoryIndex index.html index.php
  48. IndexIgnore *
  49.  
  50. #******************************************************+
  51. # Change default PHP.ini Settings                      *
  52. #            Not all Options are allowed to be changed *
  53. #                             www.php.net/manual/en/   *
  54. #******************************************************+
  55.  
  56. #===========================\
  57. # ASP TAGS on/off (Boolean) +
  58. #===========================/
  59. php_flag asp_tags off
  60. #=================================\
  61. # SHORT OPEN TAG on/off (Boolean) +
  62. #=================================/
  63.  #php_flag short_open_tag off
  64. #===================================\
  65. # REGISTER GLOBALS on/off (Boolean) +
  66. #===================================/
  67. php_flag register_globals off
  68. #========================================\
  69. # SESSION USE TRANS SID on/off (Boolean) +
  70. #========================================/
  71. php_flag session.use_trans_sid off
  72. #===================================\
  73. # MAGIC QUOTES GPC on/off (Boolean) +
  74. #===================================/
  75.  #php_flag magic_quotes_gpc off
  76. #=======================================\
  77. # MAGIC QUOTES RUNTIME on/off (Boolean) +
  78. #=======================================/
  79.  #php_flag magic_quotes_runtime off
  80.  
  81. #==============================================\
  82. # MAX EXECUTION TIME time in seconds (Integer) +
  83. #==============================================/
  84. php_value max_execution_time "10"
  85. #=====================================\
  86. # ARG SEPERATOR OUTPUT value (String) +
  87. #=====================================/
  88. php_value arg_separator.output "&"
  89. #=============================\
  90. # URL REWRITER value (String) +
  91. #=============================/
  92. php_value url_rewriter.tags "frame=src"
  93. #=============================\
  94. # INCLUDE PATH value (String) +
  95. #=============================/
  96.  #php_value include_path ".:/home/user/public_html/includes/"
  97. #===========================\
  98. # USER AGENT value (String) +
  99. #===========================/
  100. php_value user_agent "Opera/8.51 (Windows NT 5.1; U; en)"
  101. #====================================\
  102. # UPLOAD MAX FILESIZE size (Integer) +
  103. #====================================/
  104. php_value upload_max_filesize 8M
  105. #==================================\
  106. # Error Reporting number (Integer) +
  107. #==================================/
  108. php_value error_reporting 2047
  109.  
  110. #******************************************************+
  111. # Error Documents Handler                              *
  112. #          Custom Error Documents are generated by PHP *
  113. #               Valid HTML META and HEADERS are Send   *
  114. #******************************************************+
  115.  
  116. ErrorDocument 400 /e.do?error=400
  117. ErrorDocument 401 /e.do?error=401
  118. ErrorDocument 402 /e.do?error=402
  119. ErrorDocument 403 /e.do?error=403
  120. ErrorDocument 404 /e.do?error=404
  121. ErrorDocument 405 /e.do?error=405
  122. ErrorDocument 406 /e.do?error=406
  123. ErrorDocument 407 /e.do?error=407
  124. ErrorDocument 408 /e.do?error=408
  125. ErrorDocument 409 /e.do?error=409
  126. ErrorDocument 410 /e.do?error=410
  127. ErrorDocument 411 /e.do?error=411
  128. ErrorDocument 412 /e.do?error=412
  129. ErrorDocument 413 /e.do?error=413
  130. ErrorDocument 414 /e.do?error=414
  131. ErrorDocument 415 /e.do?error=415
  132. ErrorDocument 416 /e.do?error=416
  133. ErrorDocument 417 /e.do?error=417
  134. ErrorDocument 500 /e.do?error=500
  135. ErrorDocument 501 /e.do?error=501
  136. ErrorDocument 502 /e.do?error=502
  137. ErrorDocument 503 /e.do?error=503
  138. ErrorDocument 504 /e.do?error=504
  139. ErrorDocument 505 /e.do?error=505
  140.  
  141. ####################################
  142. # APACHE CONFIGURATION FILE ENDING #
  143. ####################################

well and you could create your own file.php as a custom error page and do anything you like, hope this helps ;)

Posted in PHP, Webmastering | No Comments »

Your guestbook has Spam ?

December 6th, 2005 by Quatrux

Well a lot of people have problems with this, usually the bots find your guestbook and with time start adding some content about casino, gambling, viagra and medicine etc. this is so annoying, you get an email that somebody signed and you need to clean it, wow, what a waste of time ?! and other good robots might index it and that won’t look nice, your site might be thought of being spam one having links to porno sites :D so how can you protect from them, the bad robots ? well the first thing is banning, but as usually they have different IPs it does not help to much, the other thing is cookies, but usually those bots have cookies disabled and sends false headers, so it only might help from some guys spamming your guestbook, those idiots should be shot or their balls could be cut with a big big knife :) The best way is to have a random value of letters and numbers, though I prefer numbers, they look much nicer in the image, yeah so using for example with GD library create an image with that random value, do not forget to have random backgrounds, don’t use one colour, random positions of the letters or numbers, you might even use upper/lower case, but well this protection sometimes annoys the real users.. but that is life, you also should use sessions for this thing to work properly or any method you want. Here is a good PHP function which you can use to generate a value:

  1. < ?php
  2.  
  3. function random_chars($length = ‘6′) {
  4.         /* Make Random Seed */  $value = ;
  5.         mt_srand((double) microtime() * 1000000);
  6.         $letters = "abcdefghijklmnopqrstuvwxyz"; /* add it if needed ‘123456789′ ‘ABCDEFGHIJKLMOPQRSTUVWXZ’ */
  7.                 for ($i = 0; $i < $length; $i++) {
  8.                         $value .= substr($letters, (mt_rand()%(strlen($letters))), 1);
  9.                 }
  10.         return $value;
  11. }
  12.  
  13. ?>

So echo random_chars(); will parse a random value every time with the default length of 6, you can change the length you want.

Posted in PHP, Webmastering | 6 Comments »

Functions in PHP

December 4th, 2005 by Quatrux

custom Functions in PHP is one of the best things available to optimize your code, the things you can do with it are enormous, here is my two examples of some functions which you can use.

  1. < ?php
  2.  
  3. function pw_encode($pass) {
  4.         /* Check Input */
  5.         if (is_string($pass) AND !empty($pass)) {
  6.                 /* Make a Random Seed */        $s = '';
  7.                 for ($i = 0; $i < 8; $i++) {
  8.                         $s .= substr('0123456789abcdef', mt_rand(0,15), 1);
  9.                 }
  10.                 return md5($s.$pass).$s;
  11.         } else {
  12.                 user_error('pw_encode() The input should be non empty string', E_USER_WARNING);
  13.                 return FALSE;
  14.         }
  15. }
  16.  
  17. function pw_check($pass, $value) {
  18.         /* Check Input */
  19.         if (is_string($pass) AND is_string($value) AND !empty($pass) AND !empty($value)) {
  20.                 /* Get the Seed */
  21.                 $s = substr($value, 32, 8 );
  22.                 /* Check the Passwords */
  23.                 if (md5($s.$pass).$s == $value) {
  24.                         return TRUE;
  25.                 } else {
  26.                         return FALSE;
  27.                 }
  28.         } else {
  29.                 user_error('pw_decode() The both input values should be non empty strings', E_USER_WARNING);
  30.                 return FALSE;
  31.         }
  32. }

so now, how would you use those functions ? it is really simple, if you know some PHP, here is an example, you just need to call the function like an ordinary compiled php function :D

  1. < ?php
  2. /* Encode the Password */
  3. $password = pw_encode(‘my_pass’);
  4. // it is recommended to store the password somewhere in your database
  5. /* Check the Password */
  6. // the password could come from a Post method and the $password from the database or a txt file etc.
  7. if (pw_check($password, ‘my pass’)) {
  8.         echo ‘the password is correct’;
  9. } else {
  10.         echo ‘you forgot your password ?’;
  11. }
  12. ?>

This is just one example, in functions you can’t use variables from outside the script, unless you make them global, or you can use super globals like $_SERVER, $_GET, $_POST, $_SESSION inside the functions also $GLOBALS[] array and constants which you defined using define() like if you would like to use mysql_resource in the function, just pass it through into the function: function name($a, $b, $mysql_connection) {} and whola you can use mysql in the function without needing to connect inside the function, same for ftp and irc gateway connections. Don’t forget that include() function works well in the functions or you can use file() and everything you want, as I said it is enormous thing, imagine your simple site: file index.php

  1. < ?php
  2.  
  3. /* My Site*/
  4. include "functions.php";
  5. echo_site();
  6. ?>

and the function will just output everything, well it is not the best way but it is possible. ;)
Enough for today :D

Posted in PHP, Webmastering | No Comments »

Output Buffering

December 4th, 2005 by Quatrux

What I found interesting is that output buffering can be really handy and that using it for half of year I had no problems with it, I mean using ob_start() function with gz_handler here is an example, put it somewhere in top of your file:

  1. < ?php
  2. /* Start GZipped or Plain Output Buffering */
  3. if (extension_loaded(‘zlib’) AND (ini_get(‘zlib.output_compression’) != ‘1′ OR ini_get(‘output_handler’) != ‘ob_gzhandler’)) {
  4.         ob_start("ob_gzhandler");
  5. } else {
  6.         ob_start();
  7. }
  8. ?>

using it you can use header() function anywhere in the files even if you wrote echo or made some output, you can edit the output, just read about output buffering functions in the php manual – www.php.net/ob_gzhandler

because our html has so many the same tags it is just perfect for using gzip on it, it can compress up to 60% of your source, in this way you save bandwidth and time for the user to get the file and it works great because if the user browser can’t decode gzip it won’t be sent with gzip encoding, it saves time because apache does not need to use the resources of sending the file, but it uses a bit of resources to encode using gzip, all in all it is a thing which I found to late, but I am happy I found it, it opened me new possibilities. :D

Posted in PHP, Webmastering | 4 Comments »