PHP Index
- Wiki.PHP
- Wiki.PhpAuthenticationScript
- Wiki.PhpClasses
- Wiki.PhpDatabaseAbstraction
- Wiki.PhpIndex
- Wiki.PhpMultipleUploadInputBoxesAndProcessingScript
- Wiki.PhpNotes
- Wiki.PhpNotes2
- Wiki.PhpNotes3
- Wiki.PhpSqlite
- Wiki.PhpTemplates
- Wiki.Php-AHandyWayOfCommentingForDebugging
- Wiki.Php-AScriptICreatedThatMimicsSimpleXMLInPHP5
- Wiki.Php-AccessCharactersOfStringWithArraySyntax
- Wiki.Php-ApplyAFunctionToEveryEntryOfAnArray
- Wiki.Php-ArrayOfMysqlStopWords
- Wiki.Php-ArraysAndStdClassObjects
- Wiki.Php-BackTickOperatorForExecutingShellCommands
- Wiki.Php-BackupYourListOfPearPackages
- Wiki.Php-BitwiseOperators
- Wiki.Php-Break
- Wiki.Php-ChainingMethodsOOP
- Wiki.Php-CheckToSeeIfHostIsUpOrDown
- Wiki.Php-ClassConstants
- Wiki.Php-Classes
- Wiki.Php-CompressYourHttpTraffic
- Wiki.Php-ConditionalStatementsWithEmptyConditions
- Wiki.Php-ConvertAnObjectToAnArray
- Wiki.Php-ConvertTextLinksToActualHTMLLinks
- Wiki.Php-ConvertingXMLToUTF-8OrAnyOtherEncoding
- Wiki.Php-CreateAZipFile
- Wiki.Php-CreateArrayElementsViaQueryString
- Wiki.PHP-Create1920x1080ImagesScript
- Wiki.Php-CustomErrorHandler
- Wiki.Php-DateKeepsReturningADateOf1969
- Wiki.Php-DateQueriesInOracleWithOci8PhpDrivers
- Wiki.Php-EncryptAndDecryptFunctions
- Wiki.Php-EncryptAnyFile
- Wiki.Php-EndOfLineCharacter
- Wiki.Php-EregVsPreg
- Wiki.Php-ErrorFetchingHttpHeaders
- Wiki.Php-EscapingSQLiteStrings
- Wiki.Php-ExampleRegularExpressionWhichWasUsefulInCreatingAWikiEngine
- Wiki.Php-ExecVersusUsingBackticksForSystemCalls
- Wiki.Php-ExportContactsInEntourageExportEntourageContacts
- Wiki.Php-ExtensiveListOfRegularExpressions
- Wiki.Php-FatalErrorAllowedMemorySizeOf8388608BytesExhausted
- Wiki.Php-FiguringOutWhenDSTStarts
- Wiki.Php-FilePutContentsStripsLastLineEnding
- Wiki.Php-FindOutWhatModulesAreCompiledIntoYourPHPFromTheCommandLineInterfaceCli
- Wiki.Php-FlagsToRemoveLineEndingsInTheFileFunction
- Wiki.Php-FunctionThatAutomaticallyCreatesRealHtmlLinksFromJustText
- Wiki.Php-FunctionToBuildAQueryString
- Wiki.Php-FunctionToValidateAnXmlFile
- Wiki.Php-FunctionsThatCauseCaching
- Wiki.Php-GetTheUsernameFromEmailString
- Wiki.Php-GettingInformationFromAPathToAFile
- Wiki.Php-GlobByExpandingBraces
- Wiki.Php-GLOBALVariables
- Wiki.Php-GmailImapConnectionStringForAllMail
- Wiki.Php-GreatExampleOfPassingByReference
- Wiki.Php-HandlingIntegerTypes
- Wiki.Php-HandlingNamespacesWithSimplexml
- Wiki.Php-HandlingPropertiesOfAnObjectThatHaveProblemCharactersLikeColonsForExample
- Wiki.Php-Hashing
- Wiki.Php-HowMuchDidYourMeetingCost
- Wiki.Php-HowToCommitOracleQueries
- Wiki.Php-HowToCreateAnInfiniteLoop
- Wiki.Php-HowToDisplayOnlyCertainPHPErrors
- Wiki.Php-HowToGenerateACryptoQuote
- Wiki.Php-HowToInsertElementsInsideAnArray
- Wiki.Php-HowToInstallOptionalFeaturesOfPackage
- Wiki.Php-HowToMakeAnInteractiveShellScriptInPHP
- Wiki.Php-HowToPrintEveryVariableAndItsValueThatIsBeingUsedInAPHPScript
- Wiki.Php-HowToRemoveAByteOrderMark
- Wiki.Php-HowToRenameFilesWithoutSpecialCharacters
- Wiki.Php-HowToSetUserAgentOnFileGetContents
- Wiki.Php-HowToStartASession
- Wiki.Php-HowToUseThePearPackageMdb2
- Wiki.Php-HttpPostWithCurl
- Wiki.Php-ImagemagickExamples
- Wiki.Php-InitialParsingOfAXMLFile
- Wiki.Php-InvalidSuppliedArgumentErrorMySQLAndPHP
- Wiki.Php-Is_intVersusIs_numeric?
- Wiki.Php-JavaScriptLibraryThatMimicsPhpFunctions
- Wiki.Php-LockPageBasedOnHourOfTheDay
- Wiki.Php-LockingFiles
- Wiki.Php-LoopThroughAnArrayManually
- Wiki.Php-LoopingThroughAStringCharacterByCharacterLineByLine
- Wiki.Php-LoopingThroughLettersInsteadOfNumbers
- Wiki.Php-MakeARESTRequestUsingCurl
- Wiki.Php-Message-IdAndDateAppearingInTheBodyOfAnEmailWhenUsingTheMailFunction
- Wiki.Php-MoreDetailedErrorOutputing
- Wiki.Php-MultidimensionalArraySorting
- Wiki.Php-MyDefaultFunctions
- Wiki.Php-NegativeLookupRegularExpression
- Wiki.Php-NiceCommandLineScriptToRenameBadFileNames
- Wiki.Php-NiftyLooping
- Wiki.Php-Non-GUIStatusDialogForPhpCommandLineInterfaceScripting
- Wiki.Php-ObjectVisibilty
- Wiki.Php-OneWayToRemoveACookie
- Wiki.Php-ParseChromeHtmlBookmarksFile
- Wiki.Php-ParsePhpFilesAsTextWithHtaccess
- Wiki.Php-PassingHtmlEntitiesAndProcessingThem
- Wiki.Php-PearPhpCodeSnifferForAutoFormattingCode
- Wiki.Php-PHPsBuiltInCodeHighlighting
- Wiki.Php-PHPErrorHandlingFunction
- Wiki.Php-PHPIndex
- Wiki.Php-PHPOracleOci8Example
- Wiki.Php-PlaceCurlRequestResponseInVariable
- Wiki.Php-PotentialGotchaWithTheCountFunction
- Wiki.Php-PreventFlashCaching
- Wiki.Php-PrintVersusEcho
- Wiki.Php-ProblemsPrintsAStringThatHasMathOperationsInTheMiddle
- Wiki.Php-PuttingFileContentsIntoAStringOrArray
- Wiki.Php-QuestionMarkColonControlStatementGotcha
- Wiki.Php-QuickScriptThatCanBackupAFileYouAreWorkingOn
- Wiki.Php-QuickScriptToDisplayAllImagesInADirectory
- Wiki.Php-QuickScriptToTestPageLoadTimes
- Wiki.Php-ReadingHeadersSent
- Wiki.Php-References
- Wiki.Php-RegularExpressionForMatchingEmails
- Wiki.Php-RegularExpressions
- Wiki.Php-RemovingHtmlSpecialCharactersFromAString
- Wiki.Php-RemovingWhiteSpacesAndOtherUnwantedCharacters
- Wiki.Php-ScriptThatStripsExcessWhiteSpaceFromString
- Wiki.Php-ScriptToShowMockupDesigns
- Wiki.Php-SearchAndReplace
- Wiki.Php-SendPostVariableFromScript
- Wiki.Php-SessionTimeoutConfigurationPhpIni
- Wiki.Php-ShebangProblems
- Wiki.Php-SimpleCookieLoginScript
- Wiki.Php-SimpleScriptToGetSizeOfDirectory
- Wiki.Php-SimpleXMLWithXPath
- Wiki.Php-SmallBackupScript
- Wiki.Php-SQLite3ClassExample
- Wiki.Php-StoringCookiesInAnArray
- Wiki.Php-StripAllOrSomePHPAndHtmlTagsFromString
- Wiki.Php-TableOfContents
- Wiki.Php-TernaryOperators-HandyWayOfGettingA_GETVariableOr_POSTOr_COOKIEOrAnythingElseYouWant?
- Wiki.Php-TestTheSpeedOfYourProcessor
- Wiki.Php-TidyYourHtmlWithPhp
- Wiki.Php-TriggerAFileDownload
- Wiki.Php-TurnCachingOff
- Wiki.Php-UltimateHandlePrintFunction
- Wiki.Php-UpdateThePearChannelsProtocols
- Wiki.Php-UsePhpInJavascript
- Wiki.Php-UsingGetcwdAndAvoidingThePossibleOutputsYouDontWant
- Wiki.Php-UsingPregFunctionsSuchAsPreg_replaceAndAvoidingProblems?
- Wiki.Php-UsingVarAndVarAndTheDifferences
- Wiki.Php-UsingXsltProcessorToConvertXml
- Wiki.Php-VariableVariablesAndHowToUseIllegalVariableNames
- Wiki.Php-WhatIs0xff
- Wiki.Php-WritingFiles
- Wiki.Php-ZipLikeFilesIntoChunks
Passing html entities and processing them.
Basically, this deals with having a form that passes an html entity. When PHP reads this, it's not in html entity form anymore. Below is two examples. The first one was the problem, and the second is the solution.
extract($_REQUEST);
echo($var);
$html = <<<eof
<html>
<head>
<title>test</title>
</head>
<body>
<form action="{$_SERVER['PHP_SELF']}" method="post">
<select name="var">
<option value="M&M © ©">M&M © ©</option>
</select> <input type="submit" value="go" />
</form>
</body>
</html>
eof;
echo($html);
?>
If you execute the code above in a browser, you will see that the © symbol will be converted into the actuall copyright symbol itself and not an html entity. I was wanting to put these into a database and then compare that value to the one predefined in an array. The point is, it was comparing © to (C) where (C) was the actual copyright symbol.
Below, just add the function htmlentities() around the variable being passed and it will convert it back into the html entity. In my case, ©.
It's worth noting, that htmlentities() will convert the copyright symbol into © and not ©. I was actually using the character code instead of © and the comparison in the database didn't work out. htmlentities() put © in the database, and the array in my script was using © so they never matched.
extract($_REQUEST);
echo(htmlentities($var));
$html = <<<eof
<html>
<head>
<title>test</title>
</head>
<body>
<form action="{$_SERVER['PHP_SELF']}" method="post">
<select name="var">
<option value="M&M © ©">M&M © ©</option>
</select> <input type="submit" value="go" />
</form>
</body>
</html>
eof;
echo($html);
?>
Conditional statements with empty conditions
I ran into this issue, but detected it by accident.
The following I believe will work.
if($something ==)
{
print("hi");
}
?>
This was suppose to say if($something == "yes"), however it didn't trigger an error in my application. I suppose it was checking that $something was NULL, but I'm not sure.
The way to ensure this won't happen is to reverse the statement.
if(== $something)
{
print("hi");
}
?>
Actually, this is to prevent errors by using good coding practices. The above would never make sense, because there needs to be something for $something to equal.
In the example above, by putting values on the left and variables on the right, you can prevent these kind of errors in the future.
print versus echo
Just a note, I've read that echo() is faster than print().
How to display only certain PHP errors
In PHP you can set display_errors = yes in the php.ini. This is pretty much all or nothing.
Say you have a script, and you only want to display errors for a specific section you're working on, but not the whole thing. Here's what to do, assuming the global display_errors = no. If it's not, just add ini_set("display_errors","no"); towards the top of your code before any source of possible errors.
print("Here's some code that you don't want errors to display on.");
ini_set("display_errors","on");
print("Here's some code that you want to display errors for.");
ini_set("display_errors","off");
print("Here's some code that you don't want errors to display on.");
?>
Simple cookie login script
extract($_REQUEST);
$user['some_username'];
$user['some_username']->password = 'some_password';
$phpself = $_SERVER['PHP_SELF'];
session_start();
$sessid = session_id();
if($action == "login" && $f_user != "" && $f_pass != "")
{
if($user[$f_user]->password == $f_pass)
{
setcookie("sesser",md5($sessid . $f_user),time()+86400);
}
else
{
$rm = urlencode("Something went wrong while trying to log in.");
}
header("Location:{$phpself}?rm={$rm}&f_user={$f_user}"); exit();
}
if($action == "logout")
{
setcookie("sesser",md5($sessid . $f_user),time()-1);
header("Location:{$phpself}"); exit();
}
?>
One way to remove a cookie
This simply sets the expiration date to one second ago. As soon as that happens, the cookie should be removed by browsers.
setcookie("cookie_name","cookie value",time()-1);
?>
Setting php.ini values.
You can certain php.ini values using .htaccess.
To do this, since .htaccess really only accepts on/off, yes/no, and other certain values, you have to prefix those lines with php_value. Here's an example .htaccess file.
php_value post_max_size 50M
php_value upload_max_filesize 50M
You can also set certain values inside scripts. The following shows the same.
ini_set("allow_url_fopen","yes");
ini_set("allow_url_include","yes");
?>
If you visit http://uk.php.net/manual/en/ini.php#ini.list » you will see a list of all php.ini directives. At the very bottom, it explains what the Changeable column means.
Arrays and stdClass Objects
This is just a note about arrays and how things can go wrong if not correctly setup.
The moral of the story, is don't do the following.
$array = Array();
$array->item[0]->value = "something";
?>
Even though these objects behave similar to arrays, you cannot initialize the array or object with Array() unless you are using $array as a real array.
The following would have worked.
$array->item[0]->value = "something";
?>
By the way, when I said real array, I meant using $array in the form $array['item'][0] = "something";.
I know this may not be clear and exactly kosher in terms of correct terminology -- I did my best. If you'd like more information, please write me. The email address is at the bottom of this page.
Function to validate an xml file
You can apply this function to a file. Say you have an xml file located at /home/foobar/myfile.xml and you want to validate it. The following function validate_xml() will do it. On success it returns TRUE and on failure it returns FALSE (1 and 0 respectively).
function validate_xml($xml_file)
{
$a_errors = array();
$xml_parser = xml_parser_create();
#####> open a file and read data
$fp = fopen($xml_file, 'r');
while($xml_data = fread($fp, 4096))
{
#####> parse the data chunk
if(!xml_parse($xml_parser,$xml_data,feof($fp)))
{
$a_errors[] = "Error: " . xml_error_string(xml_get_error_code($xml_parser));
}
}
fclose($fp);
xml_parser_free($xml_parser);
if(count($a_errors) == 0)
{
return 1;
}
else
{
return 0;
}
}
?>
Here is the syntax to validate /home/foobar/myfile.xml.
if(validate_xml("/home/foobar/myfile.xml"))
{
print("Your xml file is valid.");
}
else
{
print("Your xml file is not valid.");
}
?>
With a little modification, it also builds an array $a_errors[] that actually contains the errors it found in the xml. If you'd like to return the errors, anywhere it returns TRUE i.e. return 1; just replace that with return $a_errors;. You can than perform a check on that to see if there are more than 0 errors, and if so, it doesn't validate. You can also use the $a_errors[] to actually print the errors.
Here is the function that returns $a_errors[].
function validate_xml($xml_file)
{
$a_errors = array();
$xml_parser = xml_parser_create();
#####> open a file and read data
$fp = fopen($xml_file, 'r');
while($xml_data = fread($fp, 4096))
{
#####> parse the data chunk
if(!xml_parse($xml_parser,$xml_data,feof($fp)))
{
$a_errors[] = "Error: " . xml_error_string(xml_get_error_code($xml_parser));
}
}
fclose($fp);
xml_parser_free($xml_parser);
return $a_errors;
}
?>
I believe the root of these functions came from the W3 Schools » website.
Converting XML to UTF-8 or any other encoding
Just use the mb_convert_encoding() function as follows,
$xml_source_string = mb_convert_encoding($xml_source_string,"UTF-8");
?>
The function below about Byte Order Mark is related to this function.
How to remove a Byte Order Mark
A byte order mark is supposed to begin a unicode plain text file. You can read about this at: http://msdn2.microsoft.com/en-us/library/ms776429%28VS.85%29.aspx »
I ran into this while trying to parse an RSS feed. I believe xml_parse_insto_struct() was throwing the error. It can actually through you off, because you can't readily see the byte order mark and the php errors don't give you a hint of the problem.
I found this nice function on http://docs.php.net » that will remove the byte order mark. There's also a function to add a byte order mark.
Remove Byte Order Mark
function removeBOM($str="")
{
if(substr($str,0,3) == pack("CCC",0xef,0xbb,0xbf))
{
$str=substr($str,3);
}
return $str;
}
?>
Write UTF-8 file with byte order mark
function writeUTF8File($filename,$content) {
$dhandle=fopen($filename,"w");
# Now UTF-8 - Add byte order mark
fwrite($dhandle, pack("CCC",0xef,0xbb,0xbf));
fwrite($dhandle,$content);
fclose($dhandle);
}
?>
http://docs.php.net/manual/de/function.utf8-encode.php »
Nice command line script to rename bad file names
When I say "bad file names" I mean spaces and other non word characters. I like to have nice UNIX compatible file names. I know, you can have other characters, but I don't like to escape them, and the most important thing, I have OCD :), so I like things to be the way I want them, and this script does it for me.
I added \. inside of the first preg_replace because I don't want file extensions to get renamed. I haven't tested this though. It may complain.
foreach(glob("*") as $file)
{
$newfile = preg_replace("/[^a-zA-Z0-9_-\.]/","_",$file);
$newfile = preg_replace("/_{2,}/","_",$newfile);
$newfile = preg_replace("/^_/","",$newfile);
rename($file,$newfile);
}
?>
Handling integer types
Just to give you an idea of the problem before I show you the solution, here's why this is posted here.
I had a script that read an xml file with simplexml and then output the value of the tag based on a number passed in a query string attached to the url. I had to print the message using the following line
This did not work, because it did not think $number was an integer value so that we could reference the value from the array $xml_parsed->msg. In order to tell PHP that $number is an integer, or at least a number, you can run the following function on $number.
Simple script to get size of directory
$total_size = 0;
function get_filesize($dir,$total_size)
{
foreach(glob("$dir/*") as $file)
{
if(is_dir($file))
{
get_filesize($file,$total_size);
}
else
{
$total_size = $total_size + filesize($file);
}
}
return $total_size;
}
print(get_filesize("www",$total_size) . "\n");
?>
Writing files
The quick method with file_put_contents() comes after the fwrite() method in this document.
Say we have a string with contents,
This is a string that contains some words.
eof;
Say we want to write the contents of $some_var to the file myfile.txt.
Here is the brute force way to write the contents.
fwrite($fp,$some_var);
fclose($fp);
You can find the specifics at http://docs.php.net/fopen », http://docs.php.net/fwrite » and http://docs.php.net/fclose ».
Anyway, if you have a web application writing to the same file, you may want to put a lock on the file to prevent overwriting. In PHP you can use flock() » with LOCK_EX to get an exclusive lock on the file.
Here is the easy way to write to files.
By using file_put_contents() you by pass having to use multiple functions to write files. You can also create a lock on the file with the command.
You can also append contents to the file with FILE_APPEND.
Invalid supplied argument error (MySQL and PHP)
If you are trying to perform a query with mysql and you get a message that resembles the following,
If this happens, you can get more information by using the following code (the second code block is the fix that displays more detailed error reporting).
Original Code with unclear error message.
Code with error reporting.
{
#> Do whatever your code is supposed to do.
}
else
{
print(mysql_error());
}
is_int() versus is_numeric()
When checking for a number, is_int() actually checks for an integer value whereas is_numeric() checks to make sure a string contains a number. The later is useful for verifying form input where variables are always strings and could not be integers.
Using preg functions such as preg_replace() and avoiding problems
When using preg functions the regular expression you are searching for may contain characters that are special regular expression characters such as ^ and $ and [. To avoid this problem, you can escape them with the preg_quote() function. You just have to pass it your delimiter. Here's an example.
$match = "This is my /path/to/file";
$bad_way_will_not_work = preg_replace("/" . $match . "/","replace with",$string);
$correct_way = preg_replace("/" . preg_quote($match,"/") . "/","replace with",$string);
?>
Since we use / as a delimiter, we have to pass it to preg_quote() so that the forward slashes in $match get escaped before passing $match to preg_replace.
The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | :
This also goes for other preg functions such as preg_match.
Search and Replace
Just a little note out there. preg_replace() is much faster than ereg_replace. Also, if you're not replacing using a regular expression, you should use str_replace() to just replace strings which is probably even faster that the later 2.
How much did your meeting cost?
### meeting length is in hours
$meeting_length = 8;
### This array contains each employees salary
$a_amounts = array("35029","20303","83802","38250","92038","28383","10320");
function get_hourly_rate($amount)
{
$monthly = $amount / 12;
$weekly = $monthly / 4;
$daily = $weekly / 5;
$hourly = $daily / 8;
return $hourly;
}
function get_meeting_cost($a_amounts,$meeting_length)
{
$today = 0;
foreach($a_amounts as $k=>$v)
{
$today = get_hourly_rate($v) * $meeting_length;
$a_how_much[] = $today;
}
$how_much = array_sum($a_how_much);
$how_much = round($how_much,2);
return "Your meeting cost: \$" . $how_much;
}
print(get_meeting_cost($a_amounts,$meeting_length));
?>
Function that automatically creates real html links from just text.
There is also a preg_replace one liner on down this page.
function hyperlink($text) {
// match protocol://address/path/file.extension?some=variable&another=asf%
$text = preg_replace("/\s([a-zA-Z]+:\/\/[a-z][a-z0-9\_\.\-]*
[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)([\s|\.|\,])/i",
" <a href=\"$1\" target=\"_blank\">$1</a>$2", $text);
// match www.something.domain/path/file.extension?some=variable&another=asf%
$text = preg_replace("/\s(www\.[a-z][a-z0-9\_\.\-]*
[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)([\s|\.|\,])/i",
" <a href=\"http://$1\" target=\"_blank\">$1</a>$2", $text);
// match name@address
$text = preg_replace("/\s([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]*
\@[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})([\s|\.|\,])/i",
" <a href=\"mailto://$1\">$1</a>$2", $text);
return $text;
}
?>
http://us2.php.net/preg_replace »
Script that strips excess white space from string
$str = 'foo o';
$str = preg_replace('/\s\s+/', ' ', $str);
// This will be 'foo o' now
echo $str;
?>
http://us2.php.net/preg_replace »
Small Backup script
This script has a few requirments.
- It is ideal to have a cron job run this script
- The backup/remote server must have your public ssh key stored in
authorized_keys2so that we can ssh without a password. - The remote server must have PHP and the script
filesize.phpplaced somewhere. - Very important: What ever path to the remote file you use in the
$a_filesarray, you must create by hand a directory calledarchivewithin that remote directory. For example, if your path is/path/to/my/file.txton the remote server, you would have to create the directory on the remote server,/path/to/my/archive.
File: backup_to_remote.php
$a_files = array(
"/path/to/file1/on/local"=>"/backup/path/to/file1/on/remote",
"/path/to/file2/on/local"=>"/backup/path/to/file2/on/remote"
);
$timestamp = date("YmdHis");
foreach($a_files as $local_file=>$remote_file)
{
$a_local_file = pathinfo($local_file);
$a_remote_file = pathinfo($remote_file);
$local_file_name = $a_local_file['basename'];
$local_file_path = $a_local_file['dirname'];
$remote_file_name = $a_remote_file['basename'];
$remote_file_path = $a_remote_file['dirname'];
$local_filesize = filesize($local_file);
exec("ssh bob@remote-server 'php /path/to/filesize.php {$remote_file}'",$a_remote_filesize);
$remote_filesize = $a_remote_filesize[0];
if($local_filesize != $remote_filesize)
{
exec("ssh bob@remote-server 'mv {$remote_file} {$remote_file_path}/archive/{$remote_file_name}.{$timestamp}'");
exec("scp {$local_file} bob@remote-server:{$remote_file_path}/");
}
unset($a_remote_filesize);
}
?>
File: filesize.php
$filename = $_SERVER['argv'][1];
print(filesize($filename));
?>
date() keeps returning a date of 1969
While working with dates and times in PHP, you may run into a date() operation that outputs Wed, 31 Dec 1969 19:33:27 EST or something completely wrong.
Here's a scenario.
First of all, I needed this for an RSS feed for the <pubDate> tag. That's why I added the 00:00:00 or why it appears. Anyway, I want to convert a date that looks like 2007-10-17 into Wed, 17 Oct 2007 00:00:00 GMT where the 00:00:00 just comes along for the ride. date() will add that time just because there was no time associated with 2007-10-17.
Here's the bad code:
$new_date = date("D, j M Y H:i:s T",$old_date);
Here's the good code:
$new_date = date("D, j M Y H:i:s T",$old_date);
So basically, just don't forget to apply the function strtotime() to your date before running it through the date() function unless you're running the correct date string through date(). I only had to do this because I'm only dealing with the date, (I guess). I'm not quite sure the specifics, only the solution.
Convert text links to actual HTML links
This one liner will search a string and replace all links found in the text to a real html link.
Initial parsing of a XML file
$xml_file = "/path/to/file.xml";
$xml_file_string = file_get_contents($xml_file);
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($xml_parser, $xml_file_string, $a_xml, $a_index);
xml_parser_free($xml_parser);
?>
Once this code has been executed, the XML file will have been entered into the $a_xml array. You can view it's contents with print_r($a_xml);. It basically puts every node of the XML into an array slot. Each array slot contains an array that has the tag name, value of the tag, type of tag (close, open or complete) and maybe the attributes -- I forget where they are stored. Below are examples of a (close, open and complete) tag.
<car> <!-- type=open -->
<color> <!-- type=open -->
blue
</color> <!-- type=close -->
<condition /> <!-- type=complete -->
</car> <!-- type=close -->
</xml_document> <!-- type=close -->
I've put this to use in examples below.
Getting information from a path to a file
$path_parts = pathinfo('/www/htdocs/index.html');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>
http://us.php.net/manual/en/function.pathinfo.php »
Script to show mockup designs
extract($_REQUEST);
$phpself = $_SERVER['PHP_SELF'];
print <<<eof
<html>
<head>
<title>Mock Ups</title>
<style type="text/css">
body {
font-family:sans-serif;
}
div.container {
margin:0 0 16px 0; padding:16px;
text-align:left;
background-image:url(http://www.domain.org/images/back.png);
background-repeat:repeat;
border:1px solid #ebebeb;
}
a, a:link {
color:#7d110c;
}
a:hover {
color:navy;
text-decoration:none;
}
h1 {
font-size:175%;
}
</style>
</head>
<body>
<div class="container">
<h1>Your Project Name</h1>
<ol>
<li><a href="{$phpself}?url=http://www.domain.org/page1.html">Design 1</a></li>
<li><a href="{$phpself}?url=http://www.domain.org/page1.html">Design 2</a></li>
<li><a href="{$phpself}?url=http://www.domain.org/page1.html">Design 3</a></li>
</ol>
</div><!--end:class:container-->
eof;
if($url != ''){
print <<<eof
<iframe src="{$url}?style={$style}&short_title={$short_title}" width="100%" height="100%"></iframe>
eof;
}
print <<<eof
</body>
</html>
eof;
?>
GLOBAL variables
Say you have a variable $myvar that is outside of a function, but you want to call it inside a function. If you have globals turned on in your PHP configuration, you can reference $myvar with $GLOBALS['myvar'].
A script I created that mimics SimpleXML in PHP5
This script is very limited, and by that I mean it only works on the XML file I designed it for. If I have time and feel the need, I may right it to encompass any XML file. If you feel this is what you need and you'd like to work on it or ask me to work on it, go ahead, I'll try to make time. Just send me your request to mailto:webmaster@wsams.org ».
function ws_parse_xml_complete($xml_file,$sort)
{
#####> start the xml parser
$xml_file_string = file_get_contents($xml_file);
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($xml_parser, $xml_file_string, $a_vals, $a_index);
xml_parser_free($xml_parser);
$Group_cnt = $rec_cnt = $loop_cnt = 0;
foreach($a_vals as $a_val) #####> loop through the entire array of the xml file
{
if($a_val['type'] == 'open') #####> if a tag is open, see if it's <Group> or <rec>
{
if($a_val['tag'] == 'Group')
{
$Group_type = 'open';
}
elseif($a_val['tag'] == 'rec')
{
$rec_type = 'open';
$rec_Flag_cnt = $loop_cnt + 1;
$rec_campus_cnt = $loop_cnt + 7;
}
}
if($xml_parsed->document->Group[$Group_cnt]->alphabet == '' && $Group_type == 'open')
{
$xml_parsed->document->Group[$Group_cnt]->alphabet = $a_val['value'];
}
if($rec_type == 'open')
{
if(($sort == 'complete' || $sort == '' || $sort == $a_vals[$rec_campus_cnt]['value']) && ($a_vals[$rec_Flag_cnt]['value'] == 1 || $a_vals[$rec_Flag_cnt]['value'] == 3))
{
$a_tags = array("Flag","Name","phone","email","role","location","campus","gName");
foreach($a_tags as $tag)
{
if($a_val['tag'] == $tag)
{
$xml_parsed->document->Group[$Group_cnt]->rec[$rec_cnt]->{$tag} = $a_val['value'];
}
}
}
}
if($a_val['type'] == 'close')
{
if($a_val['tag'] == 'Group')
{
$Group_type = 'close';
$Group_cnt += 1;
$rec_cnt = 0;
}
elseif($a_val['tag'] == 'rec')
{
$rec_type = 'close';
$rec_cnt += 1;
}
}
$loop_cnt += 1;
}
return $xml_parsed;
}
?>
Below is the general structure of my XML file.
<Group>
<alphabet>A</alphabet>
<rec>
<Flag>1</Flag>
<Name>Able, Foo</Name>
<phone>555-555-5555</phone>
<email>joefoo@foonannyfoo.bar</email>
<role>Master</role>
<location>Right Here</location>
<campus>Harvard</campus>
<gName>Whatever you want</gName>
</rec>
</Group>
</List>
Shebang problems
I had this problem that whenever I ran a PHP script, the shebang was printed to the output. Here was my setup that caused the problem.
PHP_file_1 was executed from a web browser and it contained a shebang. PHP_file_2 was included via include_once() from inside PHP_file_1 and it contained a shebang.
On my server, the main file you type in the address bar must have a shebang in order to run, otherwise I get a fatal error. But, the file that was included did not have to have the shebang in order to run. So, the moral of the story is, if a PHP file is ran from within another PHP file, you don't have to have the shebang in the second file that is included.
That seems weird to me, but that's what worked. If anyone has a reason for this, or reads this as incorrect, please let me know at mailto:webmaster@wsams.org ».
Fatal error: Allowed memory size of 8388608 bytes exhausted
If you get this message or one like it, just add the following line to the top of your PHP script. Instead of around 8M you can try raising it to say 12M to start with. That's 8 megabytes and 12 megabytes.
Quick script that can backup a file you are working on.
Make sure you change the shebang #!/usr/local/bin/php to point to your php executable. Read about the -Cq on this page below.
As of version 1.1, there is a bug when performing an action like the following.
$ php -f bakme.php path/to/file path/to/bak/folder
This will not work. Until I get this fixed, the backup folder and the file being backed up must be in the same location. The syntax right now must be,
$ php -f bakme.php file bak_folder
<?php
###
# Version: 1.1
#
# Description: This file creates the directory bak unless you specify one, and then
# copies the file you provide to that directory appending an ascending number.
#
# Usage: bakme [options] <file_to_backup> [directory_to_put_backup_file_in]
#
# Examples: file_to_backup=report.txt && directory_to_put_backup_file_in=backup_dir
#
# ---Backup report.txt to default directory---
# $ bakme report.txt
#
# ---Backup report.txt to your defined directory (backup_directory)---
#
# $ bakme report.txt backup_dir
#
# ---Backup report.txt to default directory and gzip the file---
# $ bakme -g report.txt
#
# ---Backup report.txt to your defined directory (backup_directory) and gzip the file---
# $ bakme -g report.txt backup_dir
###
$arg1 = $_SERVER['argv'][1]; #> your file to backup (or options)
$arg2 = $_SERVER['argv'][2]; #> directory to backup in [default is bak] or (your file to backup)
$arg3 = $_SERVER['argv'][3]; #> your directory to backup in
$options = '';
$gzip = '/bin/gzip';
$backup_file_extension = 'bak';
$default_backup_location = 'bak';
$eol = "\n";
define('FILE_APPEND', 1);
if(!function_exists("file_put_contents"))
{
function file_put_contents($n, $d, $flag = false) {
$mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';
$f = @fopen($n, $mode);
if ($f === false) {
return 0;
} else {
if (is_array($d)) $d = implode($d);
$bytes_written = fwrite($f, $d);
fclose($f);
return $bytes_written;
}
}
}
if($arg1 != '' && $arg2 != '' && $arg3 != ''){
$options = $arg1;
$file = $arg2;
$dir = $arg3;
}
elseif($arg1 != '' && $arg2 != '' && $arg3 == ''){
if(eregi("-",$arg1)){
$options = $arg1;
$file = $arg2;
$dir = $default_backup_location;
}
else{
$file = $arg1;
$dir = $arg2;
}
}
elseif($arg1 != '' && $arg2 == '' && $arg3 == ''){
$file = $arg1;
$dir = $default_backup_location;
}
else{
die("I don't know what to do with your input!");
}
if($options != ''){
if(eregi("g",$options)){
$zip = 'gzip';
}
}
if(!file_exists($file)){
die("Your file, {$file}, DNE" . $eol);
}
if(!file_exists($dir)){
if(!mkdir($dir)){
die("Couldn't make directory {$dir}" . $eol);
}
}
$x = 1;
while(file_exists("{$dir}/{$file}.{$backup_file_extension}{$x}") || file_exists("{$dir}/{$file}.{$backup_file_extension}{$x}.gz")){
$x += 1;
}
if(!file_exists("{$dir}/{$file}.{$backup_file_extension}{$x}")){
if(copy("{$file}","{$dir}/{$file}.{$backup_file_extension}{$x}")){
if($zip == 'gzip'){
exec("{$gzip} {$dir}/{$file}.{$backup_file_extension}{$x}");
$append_ext = '.gz';
}
else{
$append_ext = '';
}
if(!file_exists("{$dir}/.htaccess"))
{
$htaccess = <<<eof
Order Deny, Allow
Deny from all
eof;
if(!file_put_contents("{$dir}/.htaccess",$htaccess))
{
print("Could not create {$dir}/.htaccess\n");
}
if(!chmod("{$dir}/.htaccess",0755))
{
print("Could not change mode of {$dir}/.htaccess");
}
}
print <<<eof
{$file} copied to {$dir}/{$file}.{$backup_file_extension}{$x}{$append_ext}
eof;
}
else{
die("I couldn't not create your file {$dir}/{$file}.{$backup_file_extension}{$x}{$append_ext}" . $eol);
}
}
?>
Using getcwd() and avoiding the possible outputs you don't want.
If your PHP cli binary is built as a cgi binary (check with php_sapi_name), the cwd functions differently than you might expect.
say you have a script /usr/local/bin/purge
you are in /home/username
php CLI: getcwd() gives you /home/username
php CGI: getcwd() gives you /usr/local/bin
This can trip you up if you're writing command line scripts with php. You can override the CGI behavior by adding -C to the php call (or shebang):
and then getcwd() behaves as it does in the CLI-compiled version.
[Click to add or edit comments])
Please prepend comments below including a date