php base64 decode file
base64_decode
(PHP 4, PHP 5, PHP 7, PHP 8)
base64_decode — Декодирует данные, закодированные MIME base64
Описание
Список параметров
Возвращаемые значения
Возвращает декодированные данные или false в случае возникновения ошибки. Возвращаемые данные могут быть бинарными.
Примеры
Пример #1 Пример использования base64_decode()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 17 notes
If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:
Base64 for URL parameters/filenames, that adhere to RFC 4648.
Defaults to dropping the padding on encode since it’s not required for decoding, and keeps the URL free of % encodings.
The base64-decoding function is a homomorphism between modulo 4 and modulo 3-length segmented strings. That motivates a divide and conquer approach: Split the encoded string into substrings counting modulo 4 chars, then decode each substring and concatenate all of them.
This function supports «base64url» as described in Section 5 of RFC 4648, «Base 64 Encoding with URL and Filename Safe Alphabet»
To follow up on Starson’s post, PHP was changed to no longer treat a space as if it were a plus sign in CVS revision 1.43.2.1, which corresponds to PHP 5.1.0. You can see what happened with a diff to branch point 1.43 at:
The CVS log indicates that this change was made to fix bug #34214 (base64_decode() does not properly ignore whitespace).
It would seem from the comment preceding the code which was removed that the treatment of the space as if it were the plus sign was actually intentional at one time:
When Base64 gets POSTed, all pluses are interpreted as spaces.
This line changes them back. It’s not exactly the Base64 spec,
but it is completely compatible with it (the spec says that spaces
are invalid). This will also save many people considerable
headache.
However, RFC 3548 states that characters not in the Base64 alphabet should either be ignored or cause the implementation to reject the encoding and RFC 2045 says they should be ignored. So the original code was unfortunately not fully compatible with the spec or other implementations. It may have also masked problems with code not properly escaping POST variables.
base64_encode
(PHP 4, PHP 5, PHP 7, PHP 8)
base64_encode — Кодирует данные в формат MIME base64
Описание
Кодирует string с base64.
Эта кодировка предназначена для корректной передачи бинарных данных по протоколам, не поддерживающим 8-битную передачу, например, для отправки тела письма.
Данные, закодированные base64 занимают на 33% больше места по сравнению с оригинальными данными.
Список параметров
Данные для кодирования.
Возвращаемые значения
Кодированные данные в виде строки.
Примеры
Пример #1 Пример использования base64_encode()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 35 notes
For anyone interested in the ‘base64url’ variant encoding, you can use this pair of functions:
gutzmer at usa dot net’s ( http://php.net/manual/en/function.base64-encode.php#103849 ) base64url_decode() function doesn’t pad longer strings with ‘=’s. Here is a corrected version:
function base64_encode_url($string) <
return str_replace([‘+’,’/’,’=’], [‘-‘,’_’,»], base64_encode($string));
>
Checked here with random_bytes() and random lengths:
Unfortunately my «function» for encoding base64 on-the-fly from 2007 [which has been removed from the manual in favor of this post] had 2 errors!
The first led to an endless loop because of a missing «$feof»-check, the second caused the rare mentioned errors when encoding failed for some reason in larger files, especially when
setting fgets($fh, 2) for example. But lower values then 1024 are bad overall because they slow down the whole process, so 4096 will be fine for all purposes, I guess.
The error was caused by the use of «empty()».
Here comes the corrected version which I have tested for all kind of files and length (up to 4,5 Gb!) without any error:
$cache = » ;
$eof = false ;
Base64 encoding of large files.
So if you read from the input file in chunks of 8151 (=57*143) bytes you will get (up to) 8151 eight-bit symbols, which encode as exactly 10868 six-bit symbols, which then wrap to exactly 143 MIME-formatted lines. There is no need to retain left-over symbols (either six- or eight-bit) from one chunk to the next. Just read a chunk, encode it, write it out, and go on to the next chunk. Obviously the last chunk will probably be shorter, but encoding it is still independent of the rest.
?>
Conversely, each 76-character MIME-formatted line (not counting the trailing CRLF) contains exactly enough data for 57 bytes of output without needing to retain leftover bits that need prepending to the next line. What that means is that each line can be decoded independently of the others, and the decoded chunks can then be concatenated together or written out sequentially. However, this does make the assumption that the encoded data really is MIME-formatted; without that assurance it is necessary to accept that the base64 data won’t be so conveniently arranged.
A function I’m using to return local images as base64 encrypted code, i.e. embedding the image source into the html request.
This will greatly reduce your page load time as the browser will only need to send one server request for the entire page, rather than multiple requests for the HTML and the images. Requests need to be uploaded and 99% of the world are limited on their upload speed to the server.
How to get rid of eval-base64_decode like PHP virus files?
My site (very large community website) was recently infected with a virus. Every index.php file was changed so that the opening php tag of these files it was changed to the following line:
When I decoded this, it produced the following PHP code:
I’ve tried several things to clean the virus even restoring from a backup and the files get re-infected after a few minutes or hours. So can you please help me?
What do you know about this virus?
Is there a known security hole it uses to install and propagate?
What does the above php code actually does?
What does the page it embeds in the iframe does?
And of course more importantly: What can i do to get rid of it?
Please help, we have been almost run out of ideas and hope 🙁
UPDATE1 Some more details: A weird thing is: When we first checked the infected files. They were changed but their modified time in the ftp program was showing last access to be days, months or even years ago in some cases! How is this even possible? It drives me crazy!
UPDATE 2 I think the problem initiated after a user installed a plugin in his WordPress installation. After restoring from backup and completely deleting the WordPress folder and the associated db the problem seems gone. We have currently subscribed to a security service and they are investigating the issue just to be sure the hack is gone for good. Thanks for anyone who replied.
8 Answers 8
Steps to recover and disinfect your site (provided you have a known good backup).
1) Shutdown the Site
You need to basically close the door to your site before you do your remedial work. This will prevent visitors getting malicious code, seeing error messages, etc. Just good practice.
2) Download a Copy of All of your Files from the Server
Download everything into a separate folder from your good backups. This may take a while (dependent on your site size, connection speed, etc).
3) Download and Install a File/Folder Comparison Utility
4) Run the File/Folder Comparison Utility
You should end up with a few different results:
5) Resolve the Differences
(a.k.a «Why can’t we all just get along?»)
For Files which are Identical, no further action is required. For Files which Exist on One Side Only, look at the file and figure out whether they are legitimate (ie user uploads which should be there, additional files you may have added, etc.) For Files which are Different, look at the file (the File Difference Utility may even show you which lines have been added/modified/removed) and see whether the server version is valid. Overwrite (with the backed-up version) any files which contain malicious code.
6) Review your Security Precautions
Whether this is as simple as changing your FTP/cPanel Passwords, or reviewing your use of external/uncontrolled resources (as you mention you are performing alot of fgets, fopens, etc. you may want to check the parameters being passed to them as that is a way to make scripts pull in malicious code), etc.
7) Check the Site Works
Take the opportunity of being the only person looking at the site to make sure that everything is still operating as expected, after the infected files are corrected and malicious files have been removed.
8) Open the Doors
Reverse the changes made in the .htaccess file in Step 1. Watch carefully. Keep an eye on your visitor and error logs to see if anyone tries to trigger the removed malicious files, etc.
9) Consider Automated Detection Methods
There are a few solutions, allowing for you to have an automated check performed on your host (using a CRON job) which will detect and detail any changes which occur. Some are a bit verbose (you will get an email for each and every file changed), but you should be able to adapt them to your needs:
10) Have Scheduled Backups, and Retain a Good Bracket
Make sure you have scheduled backups performed on your website, keep a few of them, so you have different steps you can go back in time, if necessary. For instance, if you performed weekly backups, you might want to keep the following:
These will always make life easier if you have someone attack your site with something a bit more destructive than a code injection attack.
Malicious code : eval(base64_decode( [closed]
Someone out there, please advise.
Here is the full code
2 Answers 2
To answer the direct question: yes, your site has been hacked.
The eval(base64_decode(. )) is intended to disguise the nature of the code being executed, but it can’t disguise the fact that there is code in your PHP files that does not belong there.
As for what the hacked code does, I’m unable to answer that, as you haven’t provided all of it.
I also can’t answer any question as to how they might have got in, but the likelyhood is that somewhere in your system (or in your web hosting company’s system) there is a software package which has a known security flaw.
In most cases, this flaw will have been fixed by the providers of that software, but the version on the hacked site won’t have been updated with the latest fixes, thus giving the hackers an opportunity to get in.
There are other methods to break into a site, but this is by far the most likely.
I can’t tell you which software was used to hack your site; there are too many variables involved, and I don’t know enough about it. I can advise you to make sure that all the software you are responsible for is secure and running the latest versions, and to check with your hosting company to make sure they’re fully up-to-date as well.
You haven’t mentioned WordPress by name, but the files you’ve specified sound like they belong to WordPress. Therefore, recovering the files should be simply a case of updating them back to the original WordPress versions. However, as I say, you should make sure you update to the latest WP version, because it sounds like the version you’ve got is out of date and vulnerable.
The actual data in your pages may have been compromised, but the nature of the hack described, it sounds more like a PHP injection hack, so I would expect that if you get the WP files back to their original state, your pages will be restored. You should check thoroughly, however, to make sure there isn’t anything unexpected still lurking in there.
Выводим изображение в кодировке Base64 на HTML/CSS и сохраняем его на jQuery+PHP
Base64 – это некий стандарт кодирования информации посредством только 64 символов таблицы ASCII. В эту таблицу входят символы латинского языка (A-Z и a-z), цифры от 0 до 9, а также некоторые знаки.
Принцип этого кодирования – представление любой цифровой информации в виде уникального набора символов этой таблицы.
Чтобы вы наглядно понимали, что это такое, поясню. Перед вами изображение:
А вот его кодировка Base64:
Что нас здесь интересует? Как сохранить такие данные и представить их в читабельном виде на примере все тех же изображений.
Выводим изображение в формате Base64 на HTML/CSS
В HTML встраивание подобного рода кода осуществляется с помощью всем привычного тега IMG. И на примере все той же картинки результат будет следующим:
Помимо этого, Base64 можно встроить и в CSS-файл:
Какие есть преимущества у этой кодировки? Основное преимущество – это то, что изображения вы не храните на своем сервере и вообще ни на каком в принципе, а просто размещаете нужные вам файлы в теле страницы обычным текстом.
Сохранение изображения в формате Base64 на jQuery+PHP
Чуть выше мы разобрали с вами встраивание изображений непосредственно в страницу вашего сайта с помощью HTML и CSS, а сейчас мы рассмотрим способ сохранения такого изображения на вашем сайте.
В одной из статей был рассмотрен вопрос о том, как же сделать скриншот элемента на JavaScript, используя библиотеку html2canvas. В примере мы рассматривали скриншот как уже готовое изображение, но мы не упомянули, что при использовании там кода:
можно получить изображение как раз в кодировке Base64.
Давайте попробуем сохранить это (вы можете использовать свое) изображение в кодировке Base64, используя технологию AJAX и не большой PHP-скрипт.
Начнем с jQuery. Скрипт, который будет посылать в обработчик (PHP-скрипт) наши данные, будет выглядеть следующим образом:
Где «base_image» – данные изображения в Base64, «/upload/base-image.php» – путь до PHP-скрипта, а «#result» – ID элемента, в который будет выводиться результат.
Сам же скрипт-обработчик будет выглядеть следующим образом:
Здесь все предельно просто – получаем данные, обрабатываем и сохраняем их в той же директории, что и сам обработчик.
В качестве функции запуска я использовал обычную загрузку страницы, вы же можете привязать ее, например, к клику по ссылке или другому нужному вам действию.
Расписал вроде все максимально подробно, но если какие-то моменты вызывают у вас трудности, не стесняйтесь и задавайте их в комментариях – никого не оставим без внимания.