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.
Related
This question already has an answer here:
PCRE2 Regex error escape sequence is invalid in character class
(1 answer)
Closed 2 years ago.
Our website with error turned on (plugin activated):
Example URLs with error:
https://www.live-karikaturen.ch/downloads/1-august-fahnen-schwingen-nationalfeiertag-schweiz/
https://www.live-karikaturen.ch/webshop-gratisbilder-free-cartoon-comic-images/
https://www.live-karikaturen.ch/downloads/auto-suv-autofan-abgase-umweltverschmutzung/
UPDATE INCOMPATIBILITY: I updated from a very old PHP version to 7.4
I use this EXTREMLY important plugin, which is horrible outdated (4 years last Update):
https://wordpress.org/support/plugin/creative-commons-configurator-1/
Now I get this error and I think it's maybe very easy to solve, but I know almost nothing about PHP, but I try to learn it a bit, so thank you very much in advance.
ERROR:
*
Warning: preg_match_all(): Compilation failed: escape sequence is
invalid in character class at offset 18 in
/home/clients/f9abb707fe4ac1215fe0f0a9c0b0ae21/www.live-karikaturen-ch/wp-content/plugins/creative-commons-configurator-1/creative-commons-configurator-1.php
on line 821
I copy the code from the .php file here
CODE:This is line 821:
if ( ! preg_match_all( $pattern_images_no_caption, $post_content, $matches ) ) {
return $post_content;
}
CODE From line 803 - 828 (don't know who to copy the line numbers):
function bccl_separate_licensing_on_images_without_caption( $post_content ) {
// Plugin options
$options = get_option('cc_settings');
if ( $options === false || $options['cc_enable_individual_media_licensing'] == '0' ) {
return $post_content;
}
$post = get_queried_object();
if ( apply_filters('bccl_exclude_license', false, $post) ) {
return $post_content;
}
// Pattern that matches images without caption
//$pattern_images_no_caption = '#<p>[\s\R]*(<img [^>]+>)#';
$pattern_images_no_caption = '#<(?:p|h[\d]+)>[\s\R]*(<img [^>]+>)#';
$pattern_images_no_caption = apply_filters('bccl_pattern_match_images_without_caption' , $pattern_images_no_caption);
**if ( ! preg_match_all( $pattern_images_no_caption, $post_content, $matches ) ) {
return $post_content;
}**
//var_dump($matches[1]);
// Iterate over the found images and add licensing metadata
foreach ( $matches[1] as $image_html ) {
Is there a simple way how to fix this error?
THANK YOU VERY MUCH FOR YOUR ANSWER & HELP!
THAAAANK you very much, you are AMAZING! :) I tried it out and it works, at least there is no error anymore.
FIRST
I am just not sure which version of the corrected code I should take. I guess Nr. 1 is ok, without []. That mean, as Toto wrote above I replaced [\s\R] with a simple \s.
Nr. 1.) without []
//$pattern_images_no_caption = '#\s*(<img [^>]+>)#';
$pattern_images_no_caption = '#<(?:p|h[\d]+)>\s*(<img [^>]+>)#';
Nr. 2.) with []
//$pattern_images_no_caption = '#<p>[\s]*(<img [^>]+>)#';
$pattern_images_no_caption = '#<(?:p|h[\d]+)>[\s]*(<img [^>]+>)#';
SECOND
I searched the whole creative-commons-configurator.php plugin code for \R and found further in line 979 this:
$parts = preg_split('#\R#u', $attach`enter code here`ment_data);
All lines together of this part are this:
// Attachment ID
// Unfortunately, WP does not provide enough information in order to determine the attachment ID
// So, first collect all the audio/video media file URLs in $attachments_urls
$attachments_data = get_post_meta( $post->ID, 'enclosure', false );
//var_dump($attachments_data);
$attachments_urls = array();
foreach ( $attachments_data as $attachment_data ) {
$parts = preg_split('#\R#u', $attachment_data);
$attachments_urls[] = $parts[0];
}
//var_dump($attachments_urls);
// Then check which media file URL exists in the $atts array so as to
// determine which attachment we are processing currently.
$atts_values = array_values($atts);
//var_dump($atts_values);
// Find the URL of the attachment we are processing
$current_attachment_url = '';
foreach ( $attachments_urls as $attachment_url) {
if ( in_array($attachment_url, $atts_values) ) {
$current_attachment_url = $attachment_url;
break;
}
}
QUESTION: In the moment I don't get any error, but I wonder if this will produce one and I have to delete or replace the "evil" \R?
I get the following error:
Catchable fatal error: Argument 1 passed to CorenlpAdapter::getOutput() must be an instance of string, string given, called in /Library/WebServer/Documents/website/php-stanford-corenlp-adapter/index.php on line 22 and defined in /Library/WebServer/Documents/website/php-stanford-corenlp-adapter/src/CoreNLP/CorenlpAdapter.php on line 95
index.php 21 and 22 contain:
$text1 = 'I will meet Mary in New York at 10pm';
$coreNLP->getOutput($text1);
corenlpAdapter.php lines 95 and onwards contain:
public function getOutput(string $text){
if(ONLINE_API){
// run the text through the public API
$this->getServerOutputOnline($text);
} else{
// run the text through Java CoreNLP
$this->getServerOutput($text);
}
// cache result
$this->serverMemory[] = $this->serverOutput;
if(empty($this->serverOutput)){
echo '** ERROR: No output from the CoreNLP Server **<br />
- Check if the CoreNLP server is running. Start the CoreNLP server if necessary<br />
- Check if the port you are using (probably port 9000) is not blocked by another program<br />';
die;
}
/**
* create trees
*/
$sentences = $this->serverOutput['sentences'];
foreach($this->serverOutput['sentences'] as $sentence){
$tree = $this->getTreeWithTokens($sentence); // gets one tree
$this->trees[] = $tree; // collect all trees
}
/**
* add OpenIE data
*/
$this->addOpenIE();
// to get the trees just call $coreNLP->trees in the main program
return;
}
Why exactly am I getting this error when text1 is a string?
I am the original author of this class. As you can see, the function getOutput looks like this:
public function getOutput(string $text){
...
}
Change that to:
public function getOutput($text){
...
}
The function tries to enforce that the input is string. The original code should work. However, it seems that in your case, PHP thinks "string" is not actually a string. Maybe the coding environment (the IDE) you are using uses the wrong character set? Or maybe you copy-pasted the code from HTML into the IDE or something like that. Thus whilst it says "string" on the screen, it's not actually a string to PHP.
If you are sure the input is a string, you can safely change the code like above. The class should then work normally.
public function getOutput($text){
.
.
.
}
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;
?>
I'm trying to load an Excel file from a certain source with PHPExcel. I have no control over how these Excel files are generated and they need to be opened automatically with PHPExcel without human interaction (re-saving the file, etc).
I'm getting the following error:
Fatal error: Uncaught exception 'Exception' with message 'Invalid character found in sheet title' in C:\path\to\PHPExcel\Worksheet.php on line 418
The error is occurring on the load() line, using the following code to open the file:
$reader = PHPExcel_IOFactory::createReader('Excel5');
$excel = $reader->load($filename_xls);
The sheet title is irrelevant to us, so is it possible to just ignore it? Thus ignoring the error?
You don't really need to hack the core, just add this in your own code:
// $invalidCharacters = array('*', ':', '/', '\\', '?', '[', ']');
$invalidCharacters = $worksheet->getInvalidCharacters();
$title = str_replace($invalidCharacters, '', $title);
Worksheet.php exposes getInvalidCharacters() public function you can use. or get lazy and use the array() directly (copy&paste from Workbook.php definitions)
We've just done this to get it sorted for now. It's probably horribly bad and I wouldn't really advise other people doing it, but hey, it should work for us!
On version 1.7.8 of PHPExcel, in /Classes/PHPExcel/Worksheet.php around line 414 - swap the checkSheetTitle() function for the following:
private static function _checkSheetTitle($pValue)
{
// Some of the printable ASCII characters are invalid: * : / \ ? [ ]
if (str_replace(self::$_invalidCharacters, '', $pValue) !== $pValue) {
//throw new Exception('Invalid character found in sheet title');
//Hack to remove bad characters from sheet name instead of throwing an exception
return str_replace(self::$_invalidCharacters, '', $pValue);
}
// Maximum 31 characters allowed for sheet title
if (PHPExcel_Shared_String::CountCharacters($pValue) > 31) {
throw new Exception('Maximum 31 characters allowed in sheet title.');
}
return $pValue;
}
You may passing special character at title. Please check the text before passing it it to title.
$sheet2->setTitle($sub_menu_title);
When a merchant adds a new product, as long as they type normal text into the body_html field, it works great. However, when they try to add some HTML from either copy paste or adding image into the WYSIWYG editor (that has "") we get the famous:
lexical error: invalid char in json text.
Now, they may be pasting from an unknown source, is there a way any has figured out how I could possible clean up the body_html before sending it on to ShopifyAPI?
By the way, I'm using PHP and the wcurl.php
https://github.com/sandeepshetty/wcurl
UPDATE:
lexical error: invalid char in json text.
"{"product":{"title":"Sample Event
(right here) ------^
CODE SAMPLE:
$shopify_data = array
(
"product"=>array
(
"title"=>$rs->product_title,
"body_html"=>$rs->product_details,
"vendor"=>"My Companay",
"product_type"=>"Laptop"
)
);
foreach ($variant as $key => $value) {
$shopify_data["product"]["variants"][$key] = array(
"option1"=> $value->variant_name,
"price"=> $value->price,
"requires_shipping"=>'true',
"inventory_management"=>"shopify",
"inventory_quantity"=> $value->quantity
);
}
// $shopify_data = json_encode($shopify_data); // This does not work either.
$shopify_data = stripslashes(json_encode($shopify_data));
If I understand this right the solution is:
stripslashes(json_encode($params))
I do this in my Shopify client:
https://github.com/sandeepshetty/shopify_api/blob/1f538276e690bd7b95f9cbb4007576ecb2d3f6de/client.php#L52
Note: PHP 5.4.0 has an option for this in json_encode.