Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Friday, February 12, 2010

Convert: missing an image filename, Command not found

convert: missing an image filename 'image-test.jpg'.

sh: line 1: image-test.jpg: command not found

Running the convert function through system() in a PHP script may result in the following error, "convert: missing an image filename"

The filename has been passed correctly to convert. The error persists.

Why does the error appear?

Line breaks. During the dump process it is possible that extra line breaks were added to the filenames.

Line breaks are invisible. That is why you cannot see the problem in the filename. The problem is not visible.

The solution is to run a trim() on all the filenames. That will instantly clean up and remove all the extra line breaks.

Thursday, February 11, 2010

phpMyAdmin Blank Page and eaccelerator

Blank phpmyadmin

So you've installed a brand new version of phpmyadmin. Running the config tool displays a blank page.

phpmyadmin displays a blank config page. The page is blank. Changing the configs manually will not work.

This issue appears if you have a version of php eaccelerator installed. It appears that certain versions of phpmyadmin will not work correctly with a version eaccelerator.

Disable php eaccelerator.

Heres how:

Open the /etc/php.ini file and edit the following line:

eaccelerator.enable="0"

Saturday, April 26, 2008

Importing UTF-8 Datasets in MySQL

Before importing a UTF-8 dataset, be sure to change the default MySQL database collation to utf8_unicode_ci.

Note: If the tables and structures are in the utf8 collation but the database is on a Latin collation, the import will not be successful.

The database, tables and structures need to be all UTF8 enabled.

Saturday, April 19, 2008

Escape MySQL Variables in the Same Sequence

When escaping a MySQL query, be sure to escape the variables in the correct order.

Example:

UPDATE
table_name
SET
var1='%s',
var3='%s',
var2='%s'
WHERE
foo=bar
mysql_real_escape_string($var1, $db),
mysql_real_escape_string($var3, $db),
mysql_real_escape_string($var2, $db)

The mysql_real_escape_string function will escape variables in the order specified in SET

Sunday, February 17, 2008

What Not to Do on Duplicate Records

You've probably grabbed a bunch of records from the database, pumped them into an array and then tried to delete the duplicate records. The result is a dataset that is messed up, the reason why is unknown.

Lets look at the array:

// Your query here
$SqlSelectRow = mysql_fetch_array($SqlSelectResult)

This behavior occurs because you perform the action on the contents in the array. Updates to the array are not reflected on the database, and therein lies the problem.

Be sure to directly update records in the database or have the array update contents in the db.

An easy solution though is to set the column as 'unique' and then dump the dataset. Be sure to remove the unique attribute once this process completes if you want duplicate records during future inserts.

Wednesday, October 31, 2007

Howto Display Records from a Database without Refreshing the Entire Page, PHP & AJAX

This post address a common question found on on AJAX and PHP forums.

Howto grab the newest records from the database and display them without the traditional meta refresh?
Or
Howto display records from a database without refreshing the entire page?

The requirements:
A basic understanding of AJAX. Get started with AJAX here: http://developer.mozilla.org/en/docs/AJAX:Getting_Started
PHP
MySQL
A dataset

I am going to use the mozilla developer docs as a reference point.

The first step is to create a HTTP request. Before we do that we need to figure out the browser that the user is running.

If the browser is Internet Explorer, call the ActiveXObject
else, call the XMLHttpRequest();
// This includes all browsers other than Microsoft Internet Explorer.
//Mozilla, Safari etc


// Create the HTTP request
function createRequestObject()
{
var browser;
if (window.XMLHttpRequest)
{
// Mozilla, Safari, ...
browser = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
browser = new ActiveXObject("Microsoft.XMLHTTP");
}
return browser;
}

var httpRequest = createRequestObject();


Once we've got the HTTP request setup, our next step is to grab the contents from the database. It is here that we set the time interval or the frequency on when the updated content is displayed.

We're going to call a PHP script get_records.php that actually grabs the dataset from the database. More on the PHP script later.

The time interval is set to 300000 milli seconds, 5 minutes

Convert minutes to seconds:
5 minutes = 5 x 60 seconds = 300 seconds

Convert seconds to milli seconds:
300 seconds = 300 x 1000 milli seconds = 300000 milli seconds

Note the exception handler below. The alert popup box will appear if there was an error. You can comment out that line later.

function displayOutput()
{
try
{
setTimeout("displayOutput()", 300000); // Recursive JavaScript function calls displayOutput() every 5 minutes, 1800 seconds
httpRequest.open('GET', 'get_records.php', true);
httpRequest.onreadystatechange = handleResponse;
httpRequest.send(true);
}
catch( e1 )
{
// Unable to open file
alert('Caught Exception: ' + e1.description);
}
}

The next step is to handle the data. We've made the HTTP request, we've called the PHP script, we've got the data. What are we going to do with the data?

If everything went well, readystate should be == 4(complete) and httpRequest.status should be == 200. All ok .. Proceed to set the innerHTML with the data.

Read about innerHTML:
http://msdn2.microsoft.com/en-us/library/ms533897.aspx


function handleResponse()
{
try {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
//alert(httpRequest.responseText);
document.getElementById("data").innerHTML = httpRequest.responseText;
} else
{
alert('There was a problem with the request.');
}
}
}
catch( e2 )
{
alert('Caught Exception: ' + e2.description);
}
}


Our final step is to display the data:

\<\body onload\=\"displayOutput\(\)\;\"\>
\<\div id\=\"data\"\>\<\/div\>
\<\/body\>

To be continued ...

Friday, October 12, 2007

Parse error: syntax error, unexpected ':'

If short open tags are enabled and if the HTML content in a PHP file has a <\?, PHP will display the error, Parse error: syntax error, unexpected ':'

Tags such as <\? could be used to open XML tags or other non PHP based tags.

The solution is to disable the short_open_tag directive in the \/etc\/php.ini file. This would force PHP to parse PHP code with tags that begin with <\?php

Saturday, August 25, 2007

Managing Multiple Simultaneous Sessions With PHP

The Issue:

Managing multiple simultaneous sessions with PHP is not a fun thing.

How does one go about creating a session that is unique to the browser window or tab? The goal is to freeze the session state.

Generally when a user signs in into a Control Panel type of environment -> screen elements are displayed -> the user clicks on the element and performs the action. If the user were to open multiple new windows or tabs, all of the assigned session variables _will be_ overwritten. What this results in, is a huge mess of what was opened previously and newly opened content.

One way to work around this problem is to disable the right-click. Prevent the user from opening new windows, prevent the user from clicking any of the mouse buttons other than the left click. This workaround requires the user to sign in into the Control Panel with the Internet Explorer browser. Any other browser would fly through the filters. Javascript must be enabled etc etc. Detecting the browser_type is the next issue. It is possible to spoof the HTTP User Agent and have the client report, spoof and copy any other client/app. The disadvantages on such an approach quickly add to the mix. A lot of the online banking portals seem to follow this approach.

The next solution involves renaming and creating new PHP sessions. I haven't found this to work too well. There were too many hoops involved.

The Solution:

The solution is to create a multi-dimensional array. Dynamically feed and call the multi-dimensional array based on the parent called.

Lets say you have five variables (parent vars) and need to register five sessions. Create a unique hash for each of the five variables, create a multi-dimensional array and call the hash in every GET and POST request. Its that simple!

// session_start();

// Select vars from db

$foo = generate_hash();

// Loop them {
$_SESSION[$foo]['type'] = $foo;
}

To call these sessions, the subsequent pages would need to call a GET request of the form, $type = hash_value

Thursday, May 24, 2007

PHP Fatal error: [] operator not supported for strings

PHP Fatal error: [] operator not supported for strings

PHP will throw up the error:

"Fatal error: [] operator not supported for strings"

if:

- The array variable eg, $foo[] has been set elsewhere as a string
- The array variable has already been set as an array elsewhere

The solution:

- Do not mix the same variable names between strings and arrays
- Do not create duplicate array names

PHP fopen Fails to Open Directory in Windows

fopen Fails to Open Directory in Windows

fopen — Opens file or URL


However, if the file is a directory, fopen will fail to open the directory in windows. This issue does not occur in Linux.

Windows Error:
Warning: fopen(c:\windows\): failed to open stream: Permission denied

Regardless of the permissions on the windows or any other directory, fopen will display the error.

PHP Code:

Windows:
$fh = fopen('c:\\windows\\', 'r');

Linux:
$fh = fopen('/home/test/', 'r');

fopen Fails to Open Directory in Windows

PHP INSERT an Array into MySQL

Inserting an array into MySQL while escaping the string with mysql_real_escape_string() will throw up the error:

"mysql_real_escape_string() expects parameter 1 to be string"

I haven't got down to research the real reason behind this issue. The obvious reason is that mysql_real_escape_string() escapes all characters in a string. To escape an array, I guess we'd need to loop the contents and return the escaped array.

The solution:

-- During INSERT or UPDATE

- Serialize the array before the INSERT or UPDATE query
$array_var[] = $some_data;

$serialized_array = serialize($array_var);

// mysql_real_escape_string() will now escape $serialized_array and insert/update without errors.

-- During SELECT

- Unserialize the array after the SELECT query is executed

$array_var = unserialize($get_all[$k]['array_var']);

// Print the array
print_r($array_var);

Tuesday, May 22, 2007

Logic to Check the Status of a URL

Open socket to host
Check socket status
Proceed to grab headers
Check headers status

IF the URL is a file or similar
Parse page and look for href patterns
For each URL
Open socket to host
Check socket status
Proceed to grab headers
Check headers status

End

// Local Filesystem - Perform integrity checks
// Local Filesystem - Checks on date attribute
// Local Filesystem - Replace domain with the localPath, check status

Thursday, November 02, 2006

PHP Extract a String that does not Match a given String of Text

PHP Extract a String that does not Match a given String of Text

Use explode, to strip and remove a line of text or word that matches "Foo"

$string = "Test Foo Bar";
$split = explode("Foo",$string);
$strip0 = $split[0];
$strip1 = $split[1];

echo "$strip0"; => Test
echo "$strip1"; => Bar
The [0] var gets the char previous to the match
The [1] var gets the char after the match

Monday, October 09, 2006

preg_replace(): Error - Delimiter must not be alphanumeric or backslash

preg_replace(): Error - Delimiter must not be alphanumeric or backslash

preg_replace() will output a delimiter error if the "$pattern" does not have a / delimiter or if quotes are used when calling the preg_replace() function itself.

The Error:

$patterns[0] = '/PHP/4.4.4/';
$replacements[0] = "FooBar!";

preg_replace("$patterns",$replacements,"$string[$counter]");

The above will result in the following error:
"preg_replace(): Parameter mismatch, pattern is a string while replacement in an array"


Corrected Version:

// Delimiter is /
// Note: the forward slash after PHP is to be escaped with a backslash
// The i after the / is for case-insensitive matches. This means, you can match lower case words with upper case words and vice-versa

$patterns[0] = '/PHP\/4.4.4/i';
$replacements[0] = "FooBar!";

// Double quotes are to be removed
preg_replace($patterns,$replacements,"$string[$counter]");

Saturday, October 07, 2006

Find and Replace the Exact Match in a String

To find and replace the exact match in a string, use the function ereg_replace. ereg will find the exact match and not a pattern.

// Strip the extra --
$string= ereg_replace("--","-",$string);
// Replace \n with a br tag
$string = str_replace("\n","
",$string);

// Find and replace multiple needles in a haystack
$patterns[0] = '/>/';
$patterns[1] = '/1/';
$patterns[2] = "/2/";
$patterns[3] = '/3/';
$patterns[4] = '/4/';

// Escape non alpha characters
$patterns[5] = '/\"/';
$patterns[6] = '/\+/';
$patterns[7] = '/\'/';
$patterns[8] = '/\./';
$patterns[9] = '/Some Text/';

$replacements = '-';

$data = preg_replace($patterns, $replacements, $data);

PHP DOCUMENT_ROOT Include does not work with CRON

When including libraries or external files in PHP, the variable $_SERVER['DOCUMENT_ROOT'] will not call the external files if the script is run through CRON.

This is because, usually a PHP script would be executed through a /usr/local/bin/php -q directive. Since Apache does not play a role here, the DOCUMENT_ROOT variable will not work.

To ensure that the DOCUMENT_ROOT works, call the script through curl, wget or lynx. As a security measure, apps like wget are disabled on most servers. The alternative option is to get rid of the DOCUMENT_ROOT variable all together.

When including files in PHP scripts, it is best to create an includes.php in the base dir of the application. All scripts in the sub-directories can call the include file through a define path. The includes file can in turn define paths to other dependencies.

Note:

The -q flag suppresses HTTP header output. As long as your script itself does not send anything to stdout, -q will prevent cron from sending you an email every time the script runs. For example, print and echo send to stdout. Avoid using these functions if you want to prevent cron from sending you email.

Note:
The ../dirname directory include path does not work with cron too. The path needs to be included in full

Source:
http://www.modwest.com/help/kb5-125.html

Further Reference:
http://www.us2.php.net/features.commandline