Strip Characters from PHP String - php

I have this string:
An error page was displayed to the Web Services user.\nDetails: The Status you have chosen is invalid.\n\nStack Trace: Stack trace:
The string itself actually goes on and on for about another ~1000 characters. What I want to do is extract what's between Details: and \n\Stack. I'd end up with The Status you have chosen is invalid.
I think I have the preceding character removal using substr:
<?php
$error = "An error page was displayed to the Web Services user.\nDetails: The Status you have chosen is invalid.\n\nStack Trace: Stack trace:.........";
$error2 = substr($error, 63);
echo $error2;
?>
But I always get an error syntax error, unexpected end of file. I figured out that it's the \n and \n\ that are throwing that error, but I have no control over those as they are returned to my script from an external API call. I've only defined the $error here for illustrative purposes. This error is present even if I just echo $error not just $error2.
I've seen that I can do something like $short = substr($str, 0, strpos( $str, ' - Name:')); for the trailing character removal, but I need to get the preceding working before I can do that.
Any advice appreciated!
Edit: I mentioned this in a comment, but the error string gets passed to my script from the API by $error = $e->getMessage();.

Use a regex with the m and s modifiers so that you can match newlines:
<?php
$error = "An error page was displayed to the Web Services user.\nDetails: The Status you have chosen is invalid.\n\nStack Trace: Stack trace:.........";
$result = preg_match("/^.*Details:\s(.*?)\n*Stack/ms", $error, $matches);
$errora = $matches[1];
echo $errora;
?>

Related

Can missing delimiter errors in a preg/PHP regexp be read programmatically?

I have a need to detect whether a regular expression is valid, so that invalid ones can be gracefully rejected in a user interface. On Stack Overflow there is a clever abomination to do this with another regular expression, which I plan to strenuously avoid.
There is a much simpler approach of running a match and checking for errors, which returns the correct boolean result, but it would be interesting to get the failure reason/message as well:
// The error is that preg delimiters are missing
$testRegex = 'Location: (.+)';
// This bit is fine
$result = preg_match($testRegex, ''); // returns false i.e. failure
$valid = is_int($result); // false, i.e. the regex is invalid
// Returns PREG_NO_ERROR, which means no error occured
echo preg_last_error() . "\n";
If I run this I correctly get:
PHP Warning: preg_match(): Delimiter must not be alphanumeric or backslash in ... on line ...
However, the output of the error function is 0, which is equal to PREG_NO_ERROR. I would have thought this would return a non-zero error code -- and it would be even better if I can get my hands on a clean version of the warning message.
It is of course possible that this is not generally available (i.e. is just available to the PHP engine for the purposes of printing the warning). I am running 5.5.3-1ubuntu2.6 (cli).
This should work for you:
Here I just turn on output buffering with ob_start(). Then I capture the last error with error_get_last(). Then I end the output buffering with ob_end_clean(). After this you can check if the array is empty and if not an error occurred.
ob_start();
$result = preg_match(".*", "Location: xy");
$error = error_get_last();
ob_end_clean();
if(!empty($error))
echo "<b>Error:</b> " . $error["message"];
else
echo "no error found!";
output:
Error: preg_match(): No ending delimiter '.' found
EDIT:
If you want you can create your own error handler, which basically just throws an Exception for each error which you would normally get.
Then you can put your code into a try - catch block and catch the exception.
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
// error was suppressed with the #-operator
if (0 === error_reporting()) {
return false;
}
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
try {
$result = preg_match(".*", "Location: xy");
} catch(Exception $e) {
echo "<b>Error:</b> " . $e->getMessage();
}
The code for the error handler is from Philippe Gerber in this answer
Maybe you could use error_get_last() to get a little bit more information.
Array
(
[type] => 2
[message] => preg_match(): Delimiter must not be alphanumeric or backslash
[file] => /Users/ivan/Desktop/test.php
[line] => 6
)
The type is E_WARNING and you can safely assume the function name string from the message part, since it will always be in the same format.
You can then do
$lastError = error_get_last()['message']; // php 5.5 expression
if(strpos($lastError, 'preg_match(): ') === 0){
$error = substr($lastError, 14);
}
And $error will be var_dump'ed to
string(47) "Delimiter must not be alphanumeric or backslash"
Or a null
Also, in response to another answer, you can surpress warnings by using #preg_match(...) so you don't have to handle output buffers yourself. error_get_last() will still catch the error.

PHP - Grab the code that threw an error

I'd like to be able to grab the actual line of code (not the number, the line of code text) where a NOTICE error occurred. Is there any way to accomplish this? I can't seem to find a function that will return the code on a certain line # in the currently running script.
Assuming the PHP script has permissions to read the current file, you can do this:
<?php
echo $b; // Undefined variable
$errors = error_get_last();
$errorMessage = $errors['message'];
$pathToScript = $errors['file'];
$line = $errors['line'];
$arrayOfLines = file(__FILE__);
echo "The error message was: '$errorMessage occured in $pathToScript'";
echo "The line of code that caused the error is: \n";
highlight_string($arrayOfLines[$line-1]);
Output:
The error message was: 'Undefined variable: b occured in /path/to/script.php'
The line of code that caused the error is: echo $b;

PHP Strange Syntax Error Line 1 Setting Up Mailchimp

I have html sending a POST request that reaches php code to process the request...I'm getting a strange error saying theres a syntax error on line 1
Parse error: syntax error, unexpected T_FUNCTION in /home/content/31/9275231/html/subscribe.php on line 1
However I don't see any errors on line 1.
Here is the code (I hid my API key info)
<?php
function isValidEmail( $email = null )
{
return preg_match( "/^
[\d\w\/+!=#|$?%{^&}*`'~-]
[\d\w\/\.+!=#|$?%{^&}*`'~-]*#
[A-Z0-9]
[A-Z0-9.-]{1,61}
[A-Z0-9]\.
[A-Z]{2,6}$/ix", $email );
}
/* Check if email has been posted */
if ( !isset($_POST['email']) ) die();
/* Validate email */
if ( isValidEmail($_POST['email']) ) {
require_once('./MCAPI.class.php');
// **************************************************************** //
// Enter your API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('apikey');
// Enter your list's unique id from http://admin.mailchimp.com/lists/
// (click the "settings", the unique id is at the bottom of the page)
$list_id = 'list_unique_id';
// **************************************************************** //
if($api->listSubscribe($list_id, $_POST['email'], '') === true) {
echo 'successful';
}else{
echo 'Error: ' . $api->errorMessage;
}
}
else {
echo 'invalid_email';
}
One other peculiar thing: I notice that when I open this php code in textmate it looks fine, but when I open it in vim, all the code is displayed in one line with strange '^M' characters where new lines should be...any ideas?
The weird ^M characters are Windows/DOS line endings. Use this to replace them with Unix line endings:
:%s/^V^M/\r/g
More info here: http://grx.no/kb/2008/11/17/remove-windows-line-endings-in-vim/
Check the options in your text editor to see if you can make newlines as LFs instead of CRs (or both a CR followed by an LF). What's happening is your newlines are only CRs, whereas the PHP interpreter is looking for LFs for newlines, so it reads your code as one big line.

PHP Offset Error

I'm running into a PHP error that through all of my scrummaging around the internet - I have been unable to crack as of yet.
The error says:
Error message
Notice: Undefined offset: 3 in include() (line 89 of /home/devced/public_html/site/sites/all/themes/cedncsu/page.tpl.php).
So, looking around my code, I currently have (actual use commented below):
<?php
// Get Base URL
global $base_url;
// Get the Page's Parent Menu Item
$menuParent = menu_get_active_trail();
// Since it returns an array, make sure to target what you are looking for
// You should print_r what menu_get_active_trail() to see what else it gives you
$menuParent = $menuParent[1]['link_title'];
$menuParent = strtolower(str_replace( " ", "-", $menuParent));
$menuParent = preg_replace('/[^\w\d_ -]/si', '', $menuParent);
// Generate class specific for department page headers
$menuParentDepartment = menu_get_active_trail();
$menuParentDepartment = $menuParentDepartment[3]['link_title']; // This is where they say the error is
$menuParentDepartment = strtolower(str_replace( " ", "-", $menuParentDepartment));
$menuParentDepartment = preg_replace('/[^\w\d_ -]/si', '', $menuParentDepartment);
// Current Page space replace/lowercase
$currentTitle = strtolower(str_replace( " ", "-", $title));
$currentTitle = preg_replace('/[^\w\d_ -]/si', '', $currentTitle);
?>
I think this is a general coding practice that I'm missing, but have thus-far been stumped. Any help would be greatly appreciated. Thanks!
Quite simply: $menuParentDepartment[3] is not defined. You need to make sure that the index (or as PHP calls it, offset) exists before you try to index it. Use isset.

How can I fix this PHP XML parsing error?

This is my first question :).
Im writing a little twitter app in PHP that sends a DMs to all your followers. What im trying to do right now is to get the list of followers. So through twitter api and getting all usernames but for some reason this parsing error appear. Im new to php(but not so much to programming), I actually started learning it yesterday so please be easy on me ;).
Here is the code:
$t= new twitter();
$t->username= $_GET["username"];
$t->password= $_GET["password"];
$fi = $t->followers();
$xml[$page] = new SimpleXMLElement($fi[2]);
$user1count=0;
while(isset($xml[$page]->user[0])){
foreach ($xml[$page]->user as $user) {
$userdet[(string)$user->screen_name]=array( ’screen_name’=> (string)$user->screen_name, ‘location’=>(string)$user->location, ‘description’=>(string)$user-> description, ‘profile_image_url’=> (string)$user-> profile_image_url, ‘url’=>(string)$user-> url, ‘name’=>(string)$user->name );
$user1details[$user1count]= (string)$user->screen_name;
$user1count++;
}
$page++;
$fi=getfilecontents($friendsurl.$username1."xml?page".$page);
if($fi[0]===false){
echo ("Error :".$fi[1]);
$err=new SimpleXMLElement($fi[2]);
echo " ".$err->error." ";
// echo ““;
die();
}
$xml[$page] = new SimpleXMLElement($fi[2]);
}
And the error said:
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /Applications/XAMPP/xamppfiles/htdocs/scripts/dmsend.php:125 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/scripts/dmsend.php(125): SimpleXMLElement->__construct('') #1 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/scripts/dmsend.php on line 125
Thank you! :)
It looks like $fi[2] is not a valid xml string. I am not 100% familiar with the twitter API, but I would do a var_dump($fi) and evaluate what is begin returned. From there, you should be able to figure out what is happening.

Categories