Интернет-журнал дачника. Сад и огород своими руками

Преступный details php image id

After you or your users have uploaded image assets to Cloudinary, you can deliver them via dynamic URLs. You can include instructions in your dynamic URLs that tell Cloudinary to manipulate your assets using a set of transformation parameters. All manipulations are performed automatically in the cloud and your transformed assets are automatically optimized before they are routed through a fast CDN to the end user for optimal user experience.

For example, you can resize and crop, add overlay images, blur or pixelate faces, apply a large variety of special effects and filters, and apply settings to optimize your images and to deliver them responsively.

Cloudinary"s PHP library simplifies the generation of transformation URLs for easy embedding of assets in your PHP application.

Deliver and transform images

You can deliver your images using methods the generate image tags or via direct URL-building directives.

The cl_image_tag method

You can add images to your PHP view using Cloudinary"s cl_image_tag helper method. This method generates the full image resource URL based on the given transformation parameters and adds the image tag to your HTML code:

cl_image_tag(" sample " );

The code above generates the following HTML image tag:

" https://res.сайт/demo/image/upload/sample " >

You can also include transformation parameters in the request, for example, to deliver a JPEG image padded to a width of 400 pixels:

cl_image_tag(" sample.jpg " , array (" width " => 400 , " crop " => " pad " ));

You can either add transformations directly to your cl_image_tag method (all transformations will be in a single, flat component of the resulting URL source, as above), or you can define them with the transformation parameter.

cl_image_tag(" sample.jpg " , array (" transformation " => array (" width " => 400 , " crop " => " pad " )));

Chaining transformations

Cloudinary supports powerful transformations. You can even combine multiple transformations together as part of a single transformation request, e.g. crop an image and add a border. In certain cases you may want to perform additional transformations on the result of the previous transformation request. To do that, you can use chained transformations.

To apply chained transformations in a transformation URL, you include multiple transformation components separated by "/". Each transformation component is applied to the result of the previous one. In PHP, applying multiple transformations is done by specifying the transformation parameter as an array of transformation arrays. The following example first crops the original image to a specific set of custom coordinates and then transforms the result so it fills a 130x100 rectangle:

cl_image_tag(" brown_sheep.jpg " , array (" transformation " =>array (array (" x " =>355 , " y " =>410 , " width " =>300 , " height " =>200 , " crop " =>" crop " ), array (" width " =>130 , " height " =>100 , " crop " =>" fill " ))))

The following example applies 4 chained transformations: custom cropping to 300x200, fill to 130x100, rotate by 20 degrees and then scale to 50%:

cl_image_tag(" brown_sheep.jpg " , array (" transformation " =>array (array (" x " =>355 , " y " =>410 , " width " =>300 , " height " =>200 , " crop " =>" crop " ), array (" width " =>130 , " height " =>100 , " crop " =>" fill " ), array (" angle " =>20 ), array (" width " =>0.5 , " crop " =>" scale " ))))

For more information on image transformations, see .

Direct URL building

The cl_image_tag method described above generates an HTML image tag. In certain conditions, you might want to generate a transformation URL directly, without the containing image tag. To return only the URL, either use the cloudinary_url view helper method. Here are few examples:

cloudinary_url(" sample.jpg " , array (" width " => 100 , " height " => 150 , " crop " => " fill " )); // Output: "https://res..jpg"

cloudinary_url(" sample_spreadsheet.xls " , array (" resource_type " => " raw " )); // Output: "https://res..xls"

Apply common image transformations

This section provides an overview and examples of the following commonly used image transformation features, along with links to more detailed documentation on these features:

Keep in mind that this section is only intended to introduce you to the basics of using image transformations with PHP.

For comprehensive explanations of how to implement a wide variety of transformations, see Image transformations . For a full list of all supported image transformations and their usage, see the Image transformation reference .

Resizing and cropping

There are a variety of different ways to resize and/or crop your images, and to control the area of the image that is preserved during a crop.

The following example uses the fill cropping method to generate and deliver an image that completely fills the requested 250x250 size while retaining the original aspect ratio. It uses face detection gravity to ensure that all the faces in the image are retained and centered when the image is cropped:

Original image Fill cropping with "faces" gravity

For details on all resizing and cropping options, see

Converting to another image format

You can deliver any image uploaded to Cloudinary in essentially any image format. There are 3 main ways to convert and deliver in another format:

  • Specifying the image"s public ID with the desired extension.
  • Explicitly set the desired format using the fetch_format parameter.
  • Use the auto fetch_format to instruct Cloudinary to deliver the image in the most optimized format for each browser that request it.

Deliver a .jpg file in .gif format:

Let Cloudinary select the optimal format for each browser. For example, in Chrome, this image delivers in .webp format.

You can select from a large selection of image effects, enhancements, and filters to apply to your images. The available effects include a variety of color balance and level effects, tinting, blurring, pixelating, sharpening, automatic improvement effects, artistic filters, image and text overlays, distortion and shape changing effects, outlines, backgrounds, shadows, and more.

For example, the code below applies a cartoonify effect, rounding corners effect, and background color effect (and then scales the image down to a height of 300 pixels).

cl_image_tag(" actor.jpg " , array (" transformation " =>array (array (" effect " =>" cartoonify " ), array (" radius " =>" max " ), array (" effect " =>" outline:100 " , " color " =>" lightblue " ), array (" background " =>" lightblue " ), array (" height " =>300 , " crop " =>" scale " ))))

For more details on the available image effects and filters, see Applying image effects and filters

Adding text and image overlays

You can add images and text as overlays on your main image. You can apply the same types of transformations on your overlay images as you can with any image and you can use gravity settings or x and y coordinates to control the location of the overlays. You can also apply a variety of transformations on text, such color, font, size, rotation, and more.

For example, the code below overlays a couple"s photo on a mug image. The overlay photo is cropped using face detection with adjusted color saturation and a vignette effect applied. The word love is added in a pink, fancy font and rotated to fit the design. A balloon graphic is also added. Additionally, the final image is cropped and the corners are rounded.

cl_image_tag(" coffee_cup.jpg " , array (" transformation " =>array (array (" width " =>400 , " height " =>250 , " gravity " =>" south " , " crop " =>" fill " ), array (" overlay " =>" nice_couple " , " width " =>1.3 , " height " =>1.3 , " gravity " =>" faces " , " flags " =>" region_relative " , " crop " =>" crop " ), array (" effect " =>" saturation:50 " ), array (" effect " =>" vignette " ), array (" flags " =>" layer_apply " , " width " =>100 , " radius " =>" max " , " gravity " =>" center " , " y " =>20 , " x " =>-20 , " crop " =>" scale " ), array (" overlay " =>" balloon " , " height " =>55 ), array (" effect " =>" hue:-20 " , " angle " =>5 ), array (" flags " =>" layer_apply " , " x " =>30 , " y " =>5 ), array (" overlay " =>array (" font_family " =>" Cookie " , " font_size " =>40 , " font_weight " =>" bold " , " text " =>" Love " ), " effect " =>" colorize " , " color " =>" #f08 " ), array (" angle " =>20 , " flags " =>" layer_apply " , " x " =>-45 , " y " =>44 ), array (" width " =>300 , " height " =>250 , " x " =>30 , " crop " =>" crop " ), array (" radius " =>60 ))))

For an in-depth review of the many ways you can optimize your images, see Image optimization

Responsive image settings

Responsive web design is a method of designing websites to provide an optimal viewing experience to users, irrespective of the device, window size, orientation, or resolution used to view it. Ensuring that optimal experience means you should avoid sending high resolution images that get resized client-side, with significant bandwidth waste for users of small displays. Instead, you should always deliver the right size image for each device and screen size.

For example, you can ensure that each user receives images at the size and device pixel ratio (dpr) that fit their device using the auto value for the dpr and width attributes. The auto value is replaced with actual values on the client side based on the actual browser settings and window width:

cl_image_tag(" myphoto " , array (" transformation " => array (array (" dpr " => " auto " , " responsive " => TRUE , " width " => " auto " , " crop " => " scale " , " angle " => 20 ), array (" effect " => " art:hokusai " , " : " border" => " 3 px_solid_rgb:00390 b " , " radius" => 20))));

Cloudinary offers several options for simplifying the complexity of delivering responsive images. For a detailed guide on how to implement these options, see

Over the past few years, web hosting has undergone a dramatic change. Web hosting services have changed the way websites perform. There are several kinds of services but today we will talk about the options that are available for reseller hosting providers. They are Linux Reseller Hosting and Windows Reseller Hosting. Before we understand the fundamental differences between the two, let’s find out what is reseller hosting.

Reseller Hosting

In simple terms, reseller hosting is a form of web hosting where an account owner can use his dedicated hard drive space and allotted bandwidth for the purpose of reselling to the websites of third parties. Sometimes, a reseller can take a dedicated server from a hosting company (Linux or Windows) on rent and further let it out to third parties.

Most website users either are with Linux or Windows. This has got to do with the uptime. Both platforms ensure that your website is up 99% of the time.

1. Customization

One of the main differences between a Linux Reseller Hostingplan and the one provided by Windows is about customization. While you can experiment with both the players in several ways, Linux is way more customizable than Windows. The latter has more features than its counterpart and that is why many developers and administrators find Linux very customer- friendly.

2. Applications

Different reseller hosting services have different applications. Linux and Windows both have their own array of applications but the latter has an edge when it comes to numbers and versatility. This has got to do with the open source nature of Linux. Any developer can upload his app on the Linux platform and this makes it an attractive hosting provider to millions of website owners.

However, please note that if you are using Linux for web hosting but at the same time use the Windows OS, then some applications may not simply work.

3. Stability

While both the platforms are stable, Linux Reseller Hosting is more stable of the two. It being an open source platform, can work in several environments.This platform can be modified and developed every now and then.

4. .NET compatibility

It isn’t that Linux is superior to Windows in every possible way. When it comes to .NET compatibility, Windows steals the limelight. Web applications can be easily developed on a Windows hosting platform.

5. Cost advantages

Both the hosting platforms are affordable. But if you are feeling a cash crunch, then you should opt for Linux. It is free and that is why it is opted by so many developers and system administrators all around the world.

6. Ease of setup

Windows is easier to set up than its counterpart. All things said and done, Windows still retains its user-friendliness all these years.

7. Security

Opt for Linux reseller hosting because it is more secure than Windows. This holds true especially for people running their E-commerce businesses.

Conclusion

Choosing between the two will depend on your requirement and the cost flexibility. Both the hosting services have unique advantages. While Windows is easy to set up, Linux is cost effective, secure and is more versatile.



Back in March of this year, I had a very bad experience with a media company refusing to pay me and answer my emails. They still owe me thousands of dollars and the feeling of rage I have permeates everyday. Turns out I am not alone though, and hundreds of other website owners are in the same boat. It"s sort of par for the course with digital advertising.

In all honesty, I"ve had this blog for a long time and I have bounced around different ad networks in the past. After removing the ad units from that company who stiffed me, I was back to square one. I should also note that I never quite liked Googles AdSense product, only because it feels like the "bottom of the barrel" of display ads. Not from a quality perspective, but from a revenue one.

From what I understand, you want Google advertising on your site, but you also want other big companies and agencies doing it as well. That way you maximize the demand and revenue.

After my negative experience I got recommend a company called Newor Media . And if I"m honest I wasn"t sold at first mostly because I couldn"t find much information on them. I did find a couple decent reviews on other sites, and after talking to someone there, I decided to give it a try. I will say that they are SUPER helpful. Every network I have ever worked with has been pretty short with me in terms of answers and getting going. They answered every question and it was a really encouraging process.

I"ve been running the ads for a few months and the earnings are about in line with what I was making with the other company. So I can"t really say if they are that much better than others, but where they do stand out is a point that I really want to make. The communication with them is unlike any other network I"ve ever worked it. Here is a case where they really are different:

They pushed the first payment to me on time with Paypal. But because I"m not in the U.S (and this happens for everyone I think), I got a fee taken out from Paypal. I emailed my representative about it, asking if there was a way to avoid that in the future.

They said that they couldn"t avoid the fee, but that they would REIMBURSE ALL FEES.... INCLUDING THE MOST RECENT PAYMENT! Not only that, but the reimbursement payment was received within 10 MINUTES! When have you ever been able to make a request like that without having to be forwarded to the "finance department" to then never be responded to.

The bottom line is that I love this company. I might be able to make more somewhere else, I"m not really sure, but they have a publisher for life with me. I"m not a huge site and I don"t generate a ton of income, but I feel like a very important client when I talk to them. It"s genuinely a breathe of fresh air in an industry that is ripe with fraud and non-responsiveness.

Microcomputers that have been created by the Raspberry Pi Foundation in 2012 have been hugely successful in sparking levels of creativity in young children and this UK based company began offering learn-to-code startup programs like pi-top an Kano. There is now a new startup that is making use of Pi electronics, and the device is known as Pip, a handheld console that offers a touchscreen, multiple ports, control buttons and speakers. The idea behind the device is to engage younger individuals with a game device that is retro but will also offer a code learning experience through a web based platform.

The amazing software platform being offered with Pip will offer the chance to begin coding in Python, HTML/CSS, JavaScript, Lua and PHP. The device offers step-by-step tutorials to get children started with coding and allows them to even make LEDs flash. While Pip is still a prototype, it will surely be a huge hit in the industry and will engage children who have an interest in coding and will provide them the education and resources needed to begin coding at a young age.

Future of Coding

Coding has a great future, and even if children will not be using coding as a career, they can benefit from learning how to code with this new device that makes it easier than ever. With Pip, even the youngest coding enthusiasts will learn different languages and will be well on their way to creating their own codes, own games, own apps and more. It is the future of the electronic era and Pip allows the basic building blocks of coding to be mastered.
Computer science has become an important part of education and with devices like the new Pip , children can start to enhance their education at home while having fun. Coding goes far beyond simply creating websites or software. It can be used to enhance safety in a city, to help with research in the medical field and much more. Since we now live in a world that is dominated by software, coding is the future and it is important for all children to at least have a basic understanding of how it works, even if they never make use of these skills as a career. In terms of the future, coding will be a critical component of daily life. It will be the language of the world and not knowing computers or how they work can pose challenges that are just as difficult to overcome as illiteracy.
Coding will also provide major changes in the gaming world, especially when it comes to online gaming, including the access of online casinos. To see just how coding has already enhanced the gaming world, take a look at a few top rated casino sites that rely on coding. Take a quick peek to check it out and see just how coding can present realistic environments online.

How Pip Engages Children

When it comes to the opportunity to learn coding, children have many options. There are a number of devices and hardware gizmos that can be purchased, but Pip takes a different approach with their device. The portability of the device and the touchscreen offer an advantage to other coding devices that are on the market. Pip will be fully compatible with electronic components in addition to the Raspberry Pi HAT system. The device uses standard languages and has basic tools and is a perfect device for any beginner coder. The goal is to remove any barriers between an idea and creation and make tools immediately available for use. One of the other great advantages of Pip is that it uses a SD card, so it can be used as a desktop computer as well when it is connected to a monitor and mouse.
The Pip device would help kids and interested coder novice with an enthusiasm into learning and practicing coding. By offering a combination of task completion and tinkering to solve problems, the device will certainly engage the younger generation. The device then allows these young coders to move to more advanced levels of coding in different languages like JavaScript and HTML/CSS. Since the device replicates a gaming console, it will immediately capture the attention of children and will engage them to learn about coding at a young age. It also comes with some preloaded games to retain attention, such as Pac-Man and Minecraft.

Innovations to Come

Future innovation largely depends on a child’s current ability to code and their overall understanding of the process. As children learn to code at an early age by using such devices as the new Pip, they will gain the skills and knowledge to create amazing things in the future. This could be the introduction of new games or apps or even ideas that can come to life to help with medical research and treatments. There are endless possibilities. Since our future will be controlled by software and computers, starting young is the best way to go, which is why the new Pip is geared towards the young crowd. By offering a console device that can play games while teaching coding skills, young members of society are well on their way to being the creators of software in the future that will change all our lives. This is just the beginning, but it is something that millions of children all over the world are starting to learn and master. With the use of devices like Pip, coding basics are covered and children will quickly learn the different coding languages that can lead down amazing paths as they enter adulthood.

The uploaded image is stored in a directory of the server and the respective image name is inserted into the database. But if you want to upload an image without storing on the server, it can be done using MySQL database. If you’re concerned about the server space and need to free space on your server, you can insert an image file in the database without upload it to the directory. This procedure helps to optimize the server space because the image file content is stored in the database rather than the server.

In this tutorial, we will show you how to store the image file into MySQL database and retrieve image from database using PHP . It’s very easy to store and retrieve images from the database using PHP and MySQL.

Insert Image File in MySQL

MySQL has a BLOB (binary large object) data type that can hold a large amount of binary data. The BLOB data type is perfect for storing the image data. In MySQL, four BLOB types are available – TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB.

To store the image data a table needs to be created in the database. The following SQL creates images table with LONGBLOB data type field in the MySQL database.

CREATE TABLE `images ` (`id` int (11 ) NOT NULL AUTO_INCREMENT, `image` longblob NOT NULL , `created` datetime NOT NULL , PRIMARY KEY (`id` )) ENGINE= InnoDB DEFAULT CHARSET= utf8 COLLATE= utf8_unicode_ci;

Image Upload Form

The following HTML form allows users to choose the image file to upload.

Select image to upload:

Store Image in Database (upload.php)

The upload.php file contains the following functionalities.

  • Check whether the user selects an image file to upload.
  • Retrieve the content of image file by the tmp_name .
  • Create the connection to MySQL database and select the database.
  • Insert the binary content of the image in the images table.
if(isset($_POST [ "submit" ])){
$check = getimagesize ($_FILES [ "image" ][ "tmp_name" ]);
if($check !== false ){
$image = $_FILES [ "image" ][ "tmp_name" ];
$imgContent = addslashes (file_get_contents ($image ));/*
* Insert image data into database
*/

//DB details

$dbHost = "localhost" ;
$dbUsername = "root" ;
$dbPassword = "*****" ;
$dbName = "codexworld" ;$db = new mysqli ($dbHost , $dbUsername , $dbPassword , $dbName );// Check connection
if($db -> connect_error ){
die("Connection failed: " . $db -> connect_error );
}$dataTime = date ("Y-m-d H:i:s" );//Insert image content into database
$insert = $db -> query ("INSERT into images (image, created) VALUES (" $imgContent ", " $dataTime ")" );
if($insert ){
echo "File uploaded successfully." ;
}else{
echo "File upload failed, please try again." ;
}
}else{
echo "Please select an image file to upload." ;
}
}
?>

Retrieve image from database (view.php)

In this file, we will retrieve the image content from the MySQL database based on the ID and display on the web page. To render image file in the web page, the Content-type header is used.

if(!empty($_GET [ "id" ])){
//DB details
$dbHost = "localhost" ;
$dbUsername = "root" ;
$dbPassword = "*****" ;
$dbName = "codexworld" ;//Create connection and select DB
$db = new mysqli ($dbHost , $dbUsername , $dbPassword , $dbName );//Check connection
if($db -> connect_error ){
die("Connection failed: " . $db -> connect_error );
}//Get image data from database
$result = $db -> query ("SELECT image FROM images WHERE id = { $_GET [ "id" ]} " );$result -> num_rows > 0 ){
$imgData = $result -> fetch_assoc ();//Render image
header ("Content-type: image/jpg" );
echo $imgData [ "image" ];
}else{
echo "Image not found..." ;
}
}
?>

Are you want to get implementation help, or modify or extend the functionality of this script?

Вы наверняка задавались вопросом «Что это за цифры и где мой путь к картинке?» 🙂 Давайте разберем несколько примеров, как с этим можно работать.

Как узнать полный путь к картинке в Битриксе

Файлы изображений нам обычно нужны, когда мы говорим за новости или товары. За такие поля, как правило, отвечают свойства элемента «Картинка для анонса » и «Детальная картинка «. Иногда, создают свойства инфоблока, тип этого свойства файл, и используют для дополнительных изображений (например, галерея товаров). Вся проблема в том, что Битрикс не даст вам сразу готовый путь к файлу изображения, или к его уменьшенной ресайз копии.

Советую для начала прочесть небольшую статью про вывод элементов на странице т.к. в дальнейшем мы столкнемся с похожим кодом.

"ASC"), Array("IBLOCK_ID" => $iblock_id), false, false, Array("ID", "NAME", "DETAIL_PAGE_URL", "PREVIEW_PICTURE", "DETAIL_PICTURE")); while($ar_fields = $my_elements->GetNext()) { echo $ar_fields["PREVIEW_PICTURE"]."
"; } endif; ?>

и на самом деле все отработало правильно, мы получили «код изображений», некий уникальный идентификатор файла, по которому мы сможем получить данные.

В 1С-Битрикс есть класс CFile — который используется для работы с файлами и изображениями. Мы воспользуемся его методом GetPath и получим полный путь к изображению на примере картинки для анонса (для детальной все точно также):

"ASC"), Array("IBLOCK_ID" => $iblock_id), false, false, Array("ID", "NAME", "DETAIL_PAGE_URL", "PREVIEW_PICTURE", "DETAIL_PICTURE")); while($ar_fields = $my_elements->
"; $img_path = CFile::GetPath($ar_fields["PREVIEW_PICTURE"]); echo $img_path."
"; } endif; ?>

Теперь у меня выводит:

/upload/iblock/c2a/c2a29aad47791f81f6fa8fd038d83789.jpg /upload/iblock/35e/35e000d0e7c3a94b32fb086c627f87eb.jpg /upload/iblock/088/08847400f3c59cae1371cf97009228a9.jpg

Отлично, это то что нужно. Теперь мы при помощи HTML тега img сможем задать картинке путь. Меняем нашу строчку с echo

Echo "
";

Как изменить размер изображений в Битриксе или выполнить ресайз

Перед тем как создать проект или новый инфоблок, всегда думайте «какого размера должны быть мои изображения «. Это очень важно, т.к. если вы не настроите в информационном блоке уменьшение картинки после загрузки, генерацию картинки анонса из детальной (если нужно) и прочие параметры, то размер вашей страницы может превышать несколько мегабайт (а в очень редких случаях даже больше 10 мб 🙂).

На самом деле, когда вы строго задаете размеры изображению, используя CSS, картинка все равно грузится в полном размере, и такие вещи не прокатят:

//HTML //CSS .my-prev-image { width: 200px; height: 200px; }

Это не решит нашу проблему с размером исходного изображения на странице, и единственные допустимые правила, на мой взгляд, могут быть max-width и max-height .

Рассмотрим случай, когда у нас уже есть большие картинки и мы хотим получить их уменьшенные копии. Нам поможет метод CFile::ResizeImageGet . Его преимущество в том, что когда мы запускаем страницу, он создает картинки в папке /upload/resize_cache/путь — и если такая картинка уже есть, он автоматически вернет нам путь к ней. Кроме того, мы можем задавать любой размер, качество и даже вид масштабирования изображений.

Вот какие типы нам доступны (информация взята из официальной документации Битрикс ):

  • BX_RESIZE_IMAGE_EXACT — масштабирует в прямоугольник $arSize c сохранением пропорций, обрезая лишнее;
  • BX_RESIZE_IMAGE_PROPORTIONAL — масштабирует с сохранением пропорций, размер ограничивается $arSize;
  • BX_RESIZE_IMAGE_PROPORTIONAL_ALT — масштабирует с сохранением пропорций, размер ограничивается $arSize, улучшенная обработка вертикальных картинок.

Давайте попробуем уменьшить наши картинки используя ResizeImageGet:

"ASC"), Array("IBLOCK_ID" => $iblock_id), false, false, Array("ID", "NAME", "DETAIL_PAGE_URL", "PREVIEW_PICTURE", "DETAIL_PICTURE")); while($ar_fields = $my_elements->GetNext()) { //echo $ar_fields["PREVIEW_PICTURE"]."
"; //$img_path = CFile::GetPath($ar_fields["PREVIEW_PICTURE"]); $img_resize_path = CFile::ResizeImageGet($ar_fields["PREVIEW_PICTURE"], array("width"=>"100", "height"=>"150"), BX_RESIZE_IMAGE_PROPORTIONAL); //echo "

";print_r($img_resize_path);echo "
"; echo "
"; } endif; ?>

$img_resize_path[‘src’] — надеюсь вы заметили что этот метод возвращает нам массив, и нам нужен только src .

Разберем по порядку:

$ ar_ fields[« PREVIEW_ PICTURE»] — поле для кода файла (для детальной меняем на $ar_fields[«DETAIL_PICTURE»]),

array(‘ width’=>’100′, ‘ height’=>’150′) — размеры итогового изображения (или вышеупомянутый arSize),

BX_ RESIZE_ IMAGE_ PROPORTIONAL — тип масштабирования, про котором наши изображения не будут вылазить за указанные границы.

В официальной документации этого метода есть подробное описание, кроме того, там описываются остальные 4 параметра, которые мы тут не использовали (InitSizes, Filters, Immediate, jpgQuality) .

Members can add or update their photo to their membership account. This is popularly known as profile photo. We will learn how to add profile photo by a member.

This script is a part of membership management script so profile photo can be added or updated by the member after login. Here there is a membership table where all details of the member is stored. You can see the structure of the membership table here.

Watch the last column where we store the file name.

Unique file name

Each member profile photo is stored in a common folder so the file names are to be unique. Each member has one unique member id and user id. Hence we will store the file name along with the member id. For example for user id plus2net member id is 4. Hence the file name will be 4.jpg

You can add userid also to the file name. like plus2net.jpg

Where to store the profile pictures.

In the root of the script there is a folder profile-photo . Here we are uploading all images and storing profile photo. If you want to change the folder then it can be done inside memadmin area two different files used for uploading photo.

You must give write permission to this folder to enable file upload.

How members can add profile photo

After login member can go to memadmin area saying settings. From memadmin area there are two links, one is to update profile and one more to update or add profile photo.


On visiting the profile photo page , the old profile photo page if already added will be displayed below the upload photo button. Here user can use the upload button to select a new profile photo from its computer. On Clicking the choose file button user can browse local computer files and select an image of jpg or gif type. Other file type are not allowed.

Once uploaded the file extension is checked for gif or jpg type images otherwise file is deleted.

After uploading the script check the dimensions of image and they are reduced proportionately to the required size. $n_width=100; // Fix the width of the thumb nail images $n_height=100; // Fix the height of the thumb nail image you can read more on here.

Once the resizing of images are over it is time to update the record with new file name. In our member table we store details of each member. For profile picture we have a column profile_photo . We will update this column with our new file name.

We will take member id which is unique and is present as session variable for updating record in where clause.

Here is the code for updating record with pfile photo. Note that we are not storing the photo in the table but storing the file name against member record. $sql=$dbo->prepare("update mem_signup set profile_photo=:profile_photo where mem_id=$_SESSION and userid="$_SESSION""); $sql->bindParam(":profile_photo",$profile_file_name,PDO::PARAM_STR, 199); if($sql->execute()){ echo "

"; echo ""; }// End of if profile is ok else{ print_r($sql->errorInfo()); $msg="
"; }

How to check script or add profile photo

Download the script and install the database file. Inside Memadmin directory there are two files, profile-photo.php & profile-photock.php .
This is a part of Membership Management Script.

Script part

There are two files, one is profile-photo.php and other one is profile-photock.php .

profile-photo.php

This file show the upload button and handle the form. Here is the code $profile_photo_path="../profile-photo/"; $count=$dbo->prepare("select profile_photo from mem_signup where mem_id=:mem_id"); $count->bindParam(":mem_id",$_SESSION["mem_id"],PDO::PARAM_INT,1); if($count->execute()){ $row = $count->fetch(PDO::FETCH_OBJ); }else{ print_r($dbo->errorInfo()); } echo "
"; if(strlen($row->profile_photo) > 1){ // Path where thumb nail image will be stored $tsrc=$profile_photo_path.$row->profile_photo; echo ""; } /////////////////////////////

profile-photock.php

This file upload the photo and place them in a directory after resizing it. Here is the code. $profile_photo_path="../profile-photo/"; // To display file name, temp name and file type , //use them for testing your script only////// //echo "File Name: ".$_FILES["userfile"]["name"]."
"; //echo "tmp name: ".$_FILES["userfile"]["tmp_name"]."
"; //echo "File Type: ".$_FILES["userfile"]["type"]."
"; //echo "

"; /////////////////// // the path with the file name where the file will be stored. $add=$profile_photo_path.$_FILES["userfile"]["name"]; //echo $add; if(move_uploaded_file ($_FILES["userfile"]["tmp_name"],$add)){ //echo "
Successfully uploaded the image
"; chmod("$add",0777); }else{echo "
Failed to upload file Contact Site admin to fix the problem
"; @unlink($add); exit;} ///////////////////////// if (!($_FILES["userfile"]["type"] =="image/jpeg" OR $_FILES["userfile"]["type"]=="image/gif")){ echo "
Your uploaded file must be of JPG or GIF. Other file types are not allowed
"; unlink($add); exit;} ////////////////// ///////// Start the thumbnail generation////////////// $n_width=100; // Fix the width of the thumb nail images $n_height=100; // Fix the height of the thumb nail image if($_FILES["userfile"]["type"]=="image/gif") { $im=ImageCreateFromGIF($add); $width=ImageSx($im); // Original picture width is stored $height=ImageSy($im); // Original picture height is stored $newimage=imagecreatetruecolor($n_width,$n_height); imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height); $profile_file_name=$_SESSION["mem_id"].".gif"; // Path where thumb nail image will be stored $tsrc=$profile_photo_path.$profile_file_name; if (function_exists("imagegif")) { Header("Content-type: image/gif"); ImageGIF($newimage,$tsrc); } elseif (function_exists("imagejpeg")) { Header("Content-type: image/jpeg"); ImageJPEG($newimage,$tsrc); } chmod("$tsrc",0777); }////////// end of gif file thumb nail creation////////// ////////////// starting of JPG thumb nail creation////////// if($_FILES["userfile"]["type"]=="image/jpeg"){ $im=ImageCreateFromJPEG($add); $width=ImageSx($im); // Original picture width is stored $height=ImageSy($im); // Original picture height is stored $newimage=imagecreatetruecolor($n_width,$n_height); imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height); $profile_file_name=$_SESSION["mem_id"].".jpg"; // Path where thumb nail image will be stored $tsrc=$profile_photo_path.$profile_file_name; ImageJpeg($newimage,$tsrc); chmod("$tsrc",0777); } $sql=$dbo->prepare("update mem_signup set profile_photo=:profile_photo where mem_id=$_SESSION and userid="$_SESSION""); $sql->bindParam(":profile_photo",$profile_file_name,PDO::PARAM_STR, 199); if($sql->execute()){ echo "
Successfully updated Profile photo
"; echo ""; }// End of if profile is ok else{ print_r($sql->errorInfo()); $msg="
Database problem, please contact site admin
"; } unlink($add); echo $msg;

Похожие публикации