PHP - Creating An Image With Php Code.
Hello,
I have a website called http://flappycreator.com/ where users can upload multiple images to create their own version of Flappy Bird. As a result of this I created a PHP page that takes a GET param to create a preview image of their game to display in various locations on the website.
Here is an example:
http://flappycreator...d=5305a9ad9dc30
http://flappycreator...d=5305a9ad9dc30
http://flappycreator...d=5305a9ad9dc30
My issue is, I have given my users the ability to upload PNGs or JPGs and trying to figure out reliable code to display the preview has become a huge hassle. In the example above the Pac-Man character shows a white background but when you play the game, it is actually transparent. In other situations I am getting extremely bad color distortion. The code I have provided is my final attempt after a ton of trial-and-error and the PNG imagealphablending() and imagesavealpha() commands have shown me the best results, however I don't know what they do.
Please help! Thanks.
<?php $bird_picture = "default/bird.png"; $tube1_picture = "default/tube1.png"; $tube2_picture = "default/tube2.png"; $ground_picture = "default/ground.png"; $bg_picture = "default/bg.png"; // If an id is set, then reset values if (isset ( $_GET ['id'] )) { require ('XXX.php'); $db = new DBAccess (); $query = "SELECT * FROM XXX WHERE XXX = '{$_GET['id']}'"; $result = $db->query ( $query ); $num_results = $result->num_rows; $row = mysqli_fetch_array ( $result ); if ($num_results != 0) { if ($row ['bird_picture'] != "") { $bird_picture = "instances/" . $row ['folder_dir'] . "/" . $row ['bird_picture']; } if ($row ['tube1_picture'] != "") { $tube1_picture = "instances/" .$row ['folder_dir'] . "/" . $row ['tube1_picture']; } if ($row ['tube2_picture'] != "") { $tube2_picture = "instances/" .$row ['folder_dir'] . "/" . $row ['tube2_picture']; } if ($row ['ground_picture'] != "") { $ground_picture = "instances/" . $row ['folder_dir'] . "/" . $row ['ground_picture']; } if ($row ['bg_picture'] != "") { $bg_picture = "instances/" . $row ['folder_dir'] . "/" . $row ['bg_picture']; } } } $temp = explode(".", $bg_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $background = imagecreatefromjpeg($bg_picture); } else { $background = imagecreatefrompng($bg_picture); // Turn off alpha blending and set alpha flag imagealphablending($background, true); imagesavealpha($background, true); } $temp = explode(".", $ground_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $ground = imagecreatefromjpeg($ground_picture); } else { $ground = imagecreatefrompng($ground_picture); // Turn off alpha blending and set alpha flag imagealphablending($ground, false); imagesavealpha($ground, true); } $temp = explode(".", $bird_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $bird = imagecreatefromjpeg($bird_picture); } else { $bird = imagecreatefrompng($bird_picture); // Turn off alpha blending and set alpha flag imagealphablending($bird, false); imagesavealpha($bird, true); } $temp = explode(".", $tube1_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $tube1 = imagecreatefromjpeg($tube1_picture); } else { $tube1 = imagecreatefrompng($tube1_picture); // Turn off alpha blending and set alpha flag imagealphablending($tube1, false); imagesavealpha($tube1, true); } $temp = explode(".", $tube2_picture); $extension = end($temp); if ($extension == "jpeg" || $extension == "jpg") { $tube2 = imagecreatefromjpeg($tube2_picture); } else { $tube2 = imagecreatefrompng($tube2_picture); // Turn off alpha blending and set alpha flag imagealphablending($tube2, false); imagesavealpha($tube2, true); } imagecopymerge($background, $tube1, 200, -200, 0, 0, 52, 320, 100); imagecopymerge($background, $tube2, 200, 200, 0, 0, 52, 320, 100); imagecopymerge($background, $ground, 0, 320, 0, 0, 336, 112, 100); imagecopymerge($background, $bird, 70, 190, 0, 0, 36, 26, 100); header('Content-Type: image/png'); imagepng($background); # Destroy imagedestroy($background); imagedestroy($ground); imagedestroy($bird); imagedestroy($tube1); imagedestroy($tube2); ?>Attached Files preview.php 3.31KB 1 downloads Similar TutorialsHi, Posted here as it is in regards to PHP code making MySQL queries. Let's say i had this code below: <?php # Databse query $query = mysql_query("SELECT id, admin, username, first_name, last_name, email FROM `users` WHERE username = '$username' AND password = '$password' LIMIT 1"); # Check login query if(!$query){ echo 'Oops'; } else { echo 'Login Succesful'; } ?> Now this code with slight difference: <?php # Databse query $query = mysql_query("SELECT id, admin, username, first_name, last_name, email FROM `users` WHERE username = '$username' AND password = '$password' LIMIT 1"); # Check login query if(!$query){ echo 'Oops'; } else { if (mysql_num_rows($query) == 1) { echo 'Login Succesful'; } else { echo 'Login Details Invalid'; } } ?> Now my question is in the second lot of code; i am doing a check to ensure that the query is true in terms of username and password match database login credentials by doing mysql_num_rows as in code . Basically do i need to do that extra check in the second lot of code or is the first lot of code fine in checking username and password match database and if not return oops and return Oops if query fails for any other reason ? not sure if i am creating more code that is needed. I am slightly confused see in whether the extra check in second lot of code is needed or not. Could someone please explain in simple terms to me if it is or not and why? Thanks hey guys, what i have done so far is got the link to a bbc video feed so when you go to my site the php code will retrive the latest video from bbc and get the link. so i now have $url as having the value of the video but i now need to insert it into the html embed video code. so how can i make this. Code: [Select] <object width="416" height="374" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="ep"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="wmode" value="transparent" /><param name="movie" value="http://i.cdn.turner.com/cnn/.element/apps/cvp/3.0/swf/cnn_416x234_embed.swf?context=embed_edition&videoId=world/2009/06/28/penhaul.lok.honduras.cnn" /><param name="bgcolor" value="#000000" /><embed src="http://i.cdn.turner.com/cnn/.element/apps/cvp/3.0/swf/cnn_416x234_embed.swf?context=embed_edition&videoId=world/2009/06/28/penhaul.lok.honduras.cnn" type="application/x-shockwave-flash" bgcolor="#000000" allowfullscreen="true" allowscriptaccess="always" width="416" wmode="transparent" height="374"></embed></object> Hi, So i have HTML table which i'm attempting to turn into executable SQL code which i can then insert into a SQL database table. I'm wondering if anyone has any good ideas for the best way to get this done? I need to extract the data from each of the <tr bgcolor="#EEEEEE">, scrape the text within each <td></td> and then format it in sql. so far i have removed the html not required and created an array by exploding "<tr bgcolor="#EEEEEE">", however, its creating an empty element in the first array index [0], to fix this i have tried $players = array_shift($players); however it removed everything from the array. next i was thinking i would need to remove all html within each array element and add a comma to the end, then i would need to compress it all back together again? would this be the best way to do this? source html <html> <head> <title><br/></title> <style type ="text/css"> body,td,th { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; } th { padding: 5px; text-align: left; } td { padding: 2px; border-style: solid; border-width: 1px } </style> </head> <body> <center><B><br/> </center></B> <p> <table bordercolor="#000000" width="90%" align="center"> <tr bgcolor="#EEEEEE"> <th>UID</th> <th>Name</th> <th>Nat</th> <th>Position</th> <th>Best Pos</th> <th>Age</th> <th>DoB</th> <th>Height</th> <th>Weight</th> <th>Expires</th> <th>Wage</th> <th>Value</th> <th>Aer</th> <th>Cmd</th> <th>Com</th> <th>Ecc</th> <th>Han</th> <th>Kic</th> <th>1v1</th> <th>Pun</th> <th>Ref</th> <th>TRO</th> <th>Thr</th> <th>Cor</th> <th>Cro</th> <th>Dri</th> <th>Fin</th> <th>Fir</th> <th>Fre</th> <th>Hea</th> <th>Lon</th> <th>L Th</th> <th>Mar</th> <th>Pas</th> <th>Pen</th> <th>Tck</th> <th>Tec</th> <th>Agg</th> <th>Ant</th> <th>Bra</th> <th>Cmp</th> <th>Cnt</th> <th>Dec</th> <th>Det</th> <th>Fla</th> <th>Ldr</th> <th>OtB</th> <th>Pos</th> <th>Tea</th> <th>Vis</th> <th>Wor</th> <th>Acc</th> <th>Agi</th> <th>Bal</th> <th>Jum</th> <th>Nat</th> <th>Pac</th> <th>Sta</th> <th>Str</th> </tr> <tr bgcolor="#EEEEEE"> <td>859596</td> <td>Tim Krul</td> <td>NED</td> <td>GK</td> <td>GK</td> <td>31</td> <td>3/4/1988 (31 years old)</td> <td>194 cm</td> <td>83 kg</td> <td>30/6/2022</td> <td>£25,000 p/w</td> <td>£12.75M</td> <td>15</td> <td>13</td> <td>14</td> <td>8</td> <td>13</td> <td>13</td> <td>15</td> <td>12</td> <td>16</td> <td>15</td> <td>12</td> <td>1</td> <td>2</td> <td>1</td> <td>3</td> <td>8</td> <td>4</td> <td>5</td> <td>3</td> <td>2</td> <td>2</td> <td>9</td> <td>4</td> <td>3</td> <td>8</td> <td>11</td> <td>12</td> <td>14</td> <td>13</td> <td>13</td> <td>12</td> <td>14</td> <td>2</td> <td>14</td> <td>2</td> <td>15</td> <td>10</td> <td>5</td> <td>13</td> <td>11</td> <td>13</td> <td>14</td> <td>17</td> <td>13</td> <td>8</td> <td>14</td> <td>10</td> </tr> <tr bgcolor="#EEEEEE"> <td>5204730</td> <td>Michael McGovern</td> <td>NIR</td> <td>GK</td> <td>GK</td> <td>34</td> <td>12/7/1984 (34 years old)</td> <td>188 cm</td> <td>86 kg</td> <td>30/6/2021</td> <td>£8,000 p/w</td> <td>£875K</td> <td>12</td> <td>11</td> <td>10</td> <td>2</td> <td>12</td> <td>12</td> <td>12</td> <td>11</td> <td>13</td> <td>8</td> <td>10</td> <td>5</td> <td>2</td> <td>1</td> <td>3</td> <td>9</td> <td>7</td> <td>6</td> <td>3</td> <td>3</td> <td>2</td> <td>7</td> <td>1</td> <td>2</td> <td>5</td> <td>7</td> <td>12</td> <td>14</td> <td>13</td> <td>13</td> <td>11</td> <td>17</td> <td>1</td> <td>12</td> <td>7</td> <td>12</td> <td>15</td> <td>10</td> <td>15</td> <td>10</td> <td>13</td> <td>12</td> <td>12</td> <td>12</td> <td>8</td> <td>15</td> <td>14</td> </tr> </table> <p> <p align="center"> </body> </html>
code i've created so far: <?php // Defining the basic scraping function function scrape_between($data, $start, $end) { $data = stristr($data, $start); // Stripping all data from before $start $data = substr($data, strlen($start)); // Stripping $start $stop = stripos($data, $end); // Getting the position of the $end of the data to scrape $data = substr($data, 0, $stop); // Stripping all data from after and including the $end of the data to scrape return $data; // Returning the scraped data from the function } $myfile = fopen("source.html", "r") or die("Unable to open file!"); $page = fread($myfile,filesize("source.html")); $page = scrape_between($page, '</tr>', '</table>'); $players = explode('<tr bgcolor="#EEEEEE">', $page); echo '<pre>'; print_r($players); echo '</pre>'; fclose($myfile); ?> Edited December 14, 2019 by seany1234 I want to add some text onto an image. Sometimes I either get nothing returned or I get a shit load of garbage returned. Garbage in the form of little question mark symbols and other crap like that. PHP File - show Tickets Code: [Select] include("createImage.php"); while( $row = mysql_fetch_array( $r ) ){ echo generateTicket( $row['ticketNumber'] ) . "<br /><br />"; } PHP - createImage.php Code: [Select] <? header("Content-type: image/jpeg"); function generateTicket( $ticketNum ){ $imageFile = "images/ticket.jpeg"; if( file_exists( $imageFile ) ){ $im = @imagecreatefromjpg( $imageFile ); $text_color = imagecolorallocate( $im, 0, 0, 0 ); imagestring( $im, 6, 25, 150, $ticketNum, $text_color ); imagejpeg( $im ); }else echo 'error'; } ?> Hey all, I'm trying to upload multiple image(which works great) but the problem I'm having is when an image is uploaded it over-rights a previous image if they are the same name and the old one is gone. Solution: create a unique name for each image before it's uploaded, change the name and then upload it. I can't seem to figure the correct syntax. My thought was to take the image name and add a random number to the front of it. Am i going about this the right way? thanks for the replies in advance. code below Code: [Select] if (isset($_POST['Submit'])) { $number_of_file_fields = 0; $number_of_uploaded_files = 0; $number_of_moved_files = 0; //creating my random number $random_digit=rand(0000,9999); $uploaded_files = array(); $upload_directory = dirname(__file__) . '/car-images/'; //set upload directory for ($i = 0; $i < count($_FILES['images']['name']); $i++) { $number_of_file_fields++; if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not $number_of_uploaded_files++; $uploaded_files[] = $_FILES['images']['name'][$i]; if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) { $number_of_moved_files++; } } } $image0 = $uploaded_files[0]; $image1 = $uploaded_files[1]; $image2 = $uploaded_files[2]; $image3 = $uploaded_files[3]; $image4 = $uploaded_files[4]; Hi, I need help in my code. I have written a CAPTCHA code, but it is not appearing when I test run in my website. My code is below, could anyone highlight to me my error? Any problems to those that were highlighted in red? Thanks <?php session_start(); // Set some important CAPTCHA constants define('CAPTCHA_NUMCHARS', 6); // number of characters in pass-phrase define('CAPTCHA_WIDTH', 100); // width of image define('CAPTCHA_HEIGHT', 25); // height of image // Generate the random pass-phrase $pass_phrase = ""; for ($i = 0; $i < CAPTCHA_NUMCHARS; $i++) { $pass_phrase .= chr(rand(97, 122)); //chr(), convert a number to its ASCII character equivalent } // Store the encrypted pass-phrase in a session variable $_SESSION['pass_phrase'] = SHA($pass_phrase); // Create the image $img = imagecreatetruecolor(CAPTCHA_WIDTH, CAPTCHA_HEIGHT); // Set a white background with black text and gray graphics $bg_color = imagecolorallocate($img, 255, 255, 255); // white $text_color = imagecolorallocate($img, 0, 0, 0); // black $graphic_color = imagecolorallocate($img, 64, 64, 64); // dark gray // Fill the background imagefilledrectangle($img, 0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT, $bg_color); // Draw some random lines for ($i = 0; $i < 5; $i++) { imageline($img, 0, rand() % CAPTCHA_HEIGHT, CAPTCHA_WIDTH, rand() % CAPTCHA_HEIGHT, $graphic_color); } // Sprinkle in some random dots for ($i = 0; $i < 50; $i++) { imagesetpixel($img, rand() % CAPTCHA_WIDTH, rand() % CAPTCHA_HEIGHT, $graphic_color); } // Draw the pass-phrase string imagettftext($img, 18, 0, 5, CAPTCHA_HEIGHT - 5, $text_color, 'Courier New Bold.ttf', $pass_phrase); // Output the image as a PNG using a header header("Content-type: image/png"); imagepng($img); // Clean up imagedestroy($img); ?> Been just trying to test out some basic code that utilizes gd. In Chrome i receive a blank page. In firefox I get "The image "image.php" cannot be displayed because it contains errors". There is no whitespace before or after the php tags, which seems to cause this error sometimes. $image = imagecreate(200,20); $background = imagecolorallocate($image, 0, 0, 0); $foreground = imagecolorallocate($image,255,255,255); imagestring($image, 5, 5, 1, "Test", $foreground); header("Content-type: image/jpeg"); $imagejpeg($image); I am just following a tutorial, and at this point in the tutorial i should get at least some garbled text, if not an image. I looked at other common causes. gd2 is un-commented in php.ini. phpinfo shows: GD Support enabled GD Version bundled (2.0.34 compatible) FreeType Support enabled FreeType Linkage with freetype FreeType Version 2.4.3 GIF Read Support enabled GIF Create Support enabled JPEG Support enabled libJPEG Version 6b PNG Support enabled libPNG Version 1.2.46 WBMP Support enabled XBM Support enabled gd.jpeg_ignore_warning 0 0 I have not found any other solutions to try, or maybe I have made an error is checking these solutions. Any advice with be great! Thank you for your time. Please Help me on how to create a website using with code n a little bit explanation using PHP n phpmyadmin. The mainthing that i need to do is using php create a simple site that logs on by connecting it to the phpmyadmin database such that i need to store the user details like name,mobile number,age,loaction,lattitude n longitude in database.Also i need to retrieve the database whenever required!!! Can Any1 please help how to do this...It means a lot to me n i'm a new User n Beginner to learn these things!!! Thank u for reading this Hi there I've been working with some code to display a single record on page. This all works fine and I'm able to pull what I want from the database. My problems is trying to use that data and turning it into something else like a link. I have a field in the database called image url which contains rows of image urls. So here is the problem area of the code: Code: [Select] <?php //////Displaying Data///////////// $id=$_GET['id']; // Collecting data from query string if(!is_numeric($id)){ // Checking data it is a number or not echo "Data Error"; exit; } $fetch=mysql_query("select * from productfeeds where ProductID=$id "); $row=mysql_fetch_object($fetch); echo mysql_error(); echo "<table>"; echo " <tr><td><b>ProductID</b></td><td>$row->ProductID</td></tr> <tr><td><b>ProductName</b></td><td>$row->ProductName</td></tr> <tr><td><b>ProductPrice</b></td><td>$row->ProductPrice</td></tr> //problem area for me <tr><td><b>Image</b></td><td>$row->ImageURL</td></tr> echo "</table>"; I'm trying to edit this part of the code: <tr><td><b>Image</b></td><td>$row->ImageURL</td></tr> I've tried this: <tr><td><b>Image</b></td><td><a href='{$row['URL']}'> <img src='{$row['ImageURL']}'></a> and <tr><td><b>Image</b></td><td><a href='$row['URL']'> <img src='$row['ImageURL']'></a> //removed brackets but I'm just getting errors. Can you guys help please? Thank you very much. Hello Forums, So basically I am trying to place text over an image. It works but the max text size is 5 which is way too small for my needs! What can I do to increase the size of the text? If anyone can help it would be much appreciated. Here is my code: Code: [Select] <?php $title = $_REQUEST['title'] ; $my_img = imagecreatefrompng ( "Template.png" ); $text_color = imagecolorallocate( $my_img, 0, 0, 0 ); imagestring( $my_img, 5, 30, 25, "$title", $text_colour ); header( "Content-type: image/png" ); imagepng( $my_img ); imagecolordeallocate( $text_color ); imagedestroy( $my_img ); ?> I am refactoring entire collective scattered SQL from my legacy codebase, and into separate classes, and looking for some structure to put it into. Right now I have folders effectively called `DataFromDB` - contains classes that accepts whatever parameters are given, and returns pure data back to the user `DAO` - Data Access Object, which takes that raw data from DB and makes sense out of it and prepares it for consumption by the model/business logic layer objects. That is: - src (folder) |- DAO (folder) | - ProductADAO (classes - take data in, return consumable objects out) | - ProductBDAO | - ... | - ProductZDAO |- DataFromDB (folder) | - ProductAData (classes - contain methods to query pure result sets from DB) | - ProductBData | - ... | - ProductZDataWhenever I need to make a new SQL or refactor an old one I do this: What is this SQL doing? Is it operating on `SomeObjectX`? If yes, find/create class called `ObjectX`, and add a method to it, extracting pure data from DB, put it into `DataFromDB` folder. Write the `DAO` object if needed to transform data into a consumable object. Use the object as is in my code. Does this look like a good strategy? Is there a better one? My problem with this one is that before (now) all the SQL is tightly coupled and is included into the multiple business classes. Using the above strategy will mean I am to be creating many many classes, a lot of classes, most likely one for every few SQL statements. The pros is that it seems like I will achieve a level of code modularity that I wanted. Hi group, I need to create a string to be used by base64_encode to build an SVG file. The source for the string is an image I built in memory. Code: [Select] $img = imagecreatetruecolor( 50,50 ); Other stuff, draw circles, test, ect. I currently write it out to disk with: Code: [Select] imagepng( $img, "$Name.png" ); Then read it back in and process it to create an SVG file. I would like to avoid writing it to disk, so how can I create a string for base64_encode from an in memory image?? Thanks for your time. Greetings, What I'm trying to do is have users upload their event information into a database which would include a flyer. I don't want the image file to go into the database (other than the filename) rather I'd like it to be dropped into a directory. In the same script I'd like to dynamically generate a thumbnail. I have the two scripts and separately they work fine, but I can't get them to work together. I'm guessing the conflict because the thumbnail script is using $_POST and the mysql script is using $_SESSION. If so how can I modify them to both use $_SESSION? The thumbnail script is goes from line 1 - 146 and the mysql portion is the rest. The results of processing this look something like this. QUERY TEXT: INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) VALUES ('12', 'spooky times', 'Ironwood Stage & Grill', '2010-12-17 22:36:00', 'DNB', '5000', 'me', '174366-1.jpg') <?php $debug = FALSE; /********************************************************************************************** CREATES THUMBNAIL **********************************************************************************************/ //define a maxim size for the uploaded images define ("MAX_SIZE","1024"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","500"); define ("HEIGHT","650"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext) || !strcmp("PNG",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) // and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['eventflyer']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['eventflyer']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message // and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which // the uploaded file was stored on the server $size=getimagesize($_FILES['eventflyer']['tmp_name']); $sizekb=filesize($_FILES['eventflyer']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*500) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=$filename; //the new name will be containing the full path where will be stored (images folder) $newname="flyers/".$image_name; $copied = copy($_FILES['eventflyer']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='flyers/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters // the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } /************************************************************ Adjust the headers... ************************************************************/ header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 /***************************************************************************** Check the session details. we will store all the post variables in session variables this will make it easier to work with the verification routines *****************************************************************************/ session_start(); if (!isset($_SESSION['SESSION'])) require_once( "../include/session_init.php"); $arVal = array(); require_once("../include/session_funcs1.php"); reset ($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "") $val = "NULL"; $arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); if ($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($debug) echo $key . " : " . $arVals[$key] . "<br>"; } /********************************************************************************************** Make sure session variables have been set and then check for required fields otherwise return to the registration form to fix the errors. **********************************************************************************************/ // check to see if these variables have been set... if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) || (!isset($_SESSION["eventgenre"])) || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) { resendToForm("?flg=red"); } // form variables must have something in them... if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") { resendToForm("?flg=red"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $conn = mysql_connect($_SESSION['MYSQL_SERVER1'],$_SESSION['MYSQL_LOGIN1'],$_SESSION['MYSQL_PASS1']) or die ('Error connecting to mysql'); mysql_select_db($_SESSION['MYSQL_DB1']) or die("Unable to select database"); $eventgenre_sel = addslashes($_REQUEST['eventgenre_sel']); $eventname = addslashes($_REQUEST['eventname']); $eventvenue = addslashes($_REQUEST['eventvenue']); $eventdate = addslashes($_REQUEST['eventdate']); $eventgenre = addslashes($_REQUEST['eventgenre']); $eventprice = addslashes($_REQUEST['eventprice']); $eventpromoter = addslashes($_REQUEST['eventpromoter']); $eventflyer = addslashes($_REQUEST['eventflyer']); $sqlquery = "INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) " ."VALUES ('$eventgenre_sel', '$eventname', '$eventvenue', '$eventdate', '$eventgenre', '$eventprice', '$eventpromoter', '$eventflyer')"; echo 'QUERY TEXT:<br />'.$sqlquery; $result = MYSQL_QUERY($sqlquery); $insertid = mysql_insert_id(); /*** This following function will update session variables and resend to the form so the user can fix errors ***/ function resendToForm($flags) { reset ($_POST); // store variables in session... while (list ($key, $val) = each ($_POST)) { $_SESSION[$key] = $val; } // go back to the form... //echo $flags; header("Location: /user_registration.php".$flags); exit; } mysql_close($conn); ?> Good afternoon: I have added a database field to a table that has quiz questions in it. the field I have added is for images and I have entered the image url that is stored on the server in an image folder. Please could you tell me how I can include the image in the request by adding to the code below: $Questions = $DB->query("select * from ".TABLE_PREFIX."quiz_questions where q_forquiz='{$Quiz['qid']}' order by qqid"); while($Question = $DB->fetch_array($Questions)){ $Q[$Question['qqid']] = $Question; } Fields in table quiz_questions: qqid q_question q_type q_params q_forquiz q_questionimages - This is the field I added. Thank you for helping. Amilo Hi , I got "High Slide Script" for making photogallery .. The problem is that code has no admin panel to upload images and their description . All you make that you write image path into html code of its index page.. I thought to make admin panel by a small database you enter the image path uploaded and description . and the code has a loop to read this data throught a php code . I attached what I made . The problem is : why my images doesn't appear ??? NB: the original script in the file named : highslide-custom-example.htm my code is in the file : highslide-custom-example.php I attached the DB also.. Here is the attachments : http://www.seed-share.com/6mghkdpg0ywj Thanks I've been working on this site that allows users to upload images to the server... the code i have right now basically uploads the file to the server and then resizes it and makes a new copy of it... Upuntil now it was working flawlessly, however now i'm getting this error: Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error: in /home/content/t/h/e/thereferralpro/html/beta/region.php on line 144 Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'images/projects/porncheck_star.png' is not a valid JPEG file in /home/content/t/h/e/thereferralpro/html/beta/region.php on line 144 Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/content/t/h/e/thereferralpro/html/beta/region.php on line 162 Warning: imagedestroy(): supplied argument is not a valid Image resource in /home/content/t/h/e/thereferralpro/html/beta/region.php on line 165 In order for you guys to understand the error here's the code i'm using //move file to the folder before resizeing move_uploaded_file($_FILES['image']['tmp_name'], $target); //resize the image and add to server $source_pic = $target; $final_pic = $dir.$final_img_name; $max_width = 800; $max_height = 600; $src = imagecreatefromjpeg($source_pic); list($width,$height)=getimagesize($source_pic); $x_ratio = $max_width / $width; $y_ratio = $max_height / $height; if( ($width <= $max_width) && ($height <= $max_height) ){ $tn_width = $width; $tn_height = $height; }elseif (($x_ratio * $height) < $max_height){ $tn_height = ceil($x_ratio * $height); $tn_width = $max_width; }else{ $tn_width = ceil($y_ratio * $width); $tn_height = $max_height; } $tmp=imagecreatetruecolor($tn_width,$tn_height); imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height); imagejpeg($tmp,$final_pic,80); imagedestroy($src); imagedestroy($tmp); list($width, $height, $type, $attr) = getimagesize($final_pic); Keep in mind that this code was working perfectly and now for some reason its not working anymore, and no i have not touch it at all nor i have done nay edits to this code Hope someone can help me out because i have no idea what this could be. Thanks I have an image upload script where I am trying to compress an image to a lower file size. The code works. The image uploads to the directory with the correct name as intended. The only thing is that it's not compression the image as it should be. The size of the new image is the same as the old image. Here's my code. Can you spot what i'm doing wrong? // FUNCTION FOR COMPRESSION function compress_image($source_url, $destination_url, $quality) { $info = getimagesize($source_url); if($info['mime'] == 'image/jpeg') { $image = imagecreatefromjpeg($source_url); } else if ($info['mime'] == 'image/gif') { $image = imagecreatefromgif($source_url); } else if ($info['mime'] == 'image/png') { $image = imagecreatefrompng($source_url); imagejpeg($image, $destination_url, $quality); } return $destination_url; } // FORM SUBMIT CODE $errors = array(); $db->beginTransaction(); if(isset($_FILES['fileToUpload']) AND !empty($_FILES['fileToUpload']["name"])) { if(is_uploaded_file($_FILES['fileToUpload']["tmp_name"])) { // GENERATES A 10 CHARACTER STRING TO BE USED FOR AN IMAGE NAME $random_name = generateRandomString(10); $global_user_id = 10; $url_project_id = 5; $target_dir = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/'; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); if(!is_dir($target_dir)){ mkdir($target_dir, 0775, true); } // RESIZE IMAGE $pathname = $_FILES["fileToUpload"]["tmp_name"]; $resized_image = compress_image($pathname, $random_name, 40); $new_file_path = $target_dir . $resized_image . '.' . $imageFileType; // Check if image file is a actual image or fake image $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { // echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { $errors[] = 'File is not an image!'; $uploadOk = 0; } // Check if file already exists if (file_exists($new_file_path)) { $errors[] = 'Sorry, file already exists!'; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 5000000) { $errors[] = 'Sorry, your file size is bigger than 5mb!'; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "JPG" && $imageFileType != "PNG" && $imageFileType != "JPEG" && $imageFileType != "GIF") { $errors[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed!'; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if($uploadOk == 0) { $errors[] = 'Sorry, your file was not uploaded!'; // if everything is ok, try to upload file } else { if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $new_file_path)) { // SUCCESS MESSAGE } else { $errors[] = 'Sorry, there was an error uploading your file!'; } } } else { $errors[] = 'You must upload an image!'; } } if(empty($errors)) { $db->commit(); header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"); exit; } else { $db->rollBack(); }
Well here is the original code in my script file, and it has a background color Green now: [/php]$article_content = "<center><table style='color: #FFFF31; background: Green; width: 400px; border: 1px solid #9BDDFF;'><tr><td><i><b><u>Welcome to Mysidia City's fishing pool</b></u></i><br><br><br> Before you actually begin your fishing career, I'd strongly recommend you to doublecheck if you have a fishing rod already since it is apparently required for every fisherman here. <br><br><br><a href='fishing.php?act=1'>Enter</a> the fishing pool now if you have a fishing rod already or <br>Visit this <a href='fishingquiz.php'>Page</a> to take the fishing quiz and earn yourself an old rod to begin with. <td></tr></table><br><center><img src='picuploads/other/lakeofrage.png'></center>";[/php] Now I wish to replace the background color with a background image, what should I do? The image url is provided below: http://www.pokemansion.net/picuploads/other/seadrabg.png I'm tired and just about given up. Can anybody help me? Code: [Select] <?php $objConnect = mysql_connect("localhost","","root") or die(mysql_error()); $objDB = mysql_select_db("sdf"); $pic2 = "SELECT * FROM images"; if (!isset($_GET['Page'])) $_GET['Page']='0'; $pic1 = mysql_query($pic2); $Num_Rows = mysql_num_rows($pic1); $Per_Page = 16; // Per Page $Page = $_GET["Page"]; if(!$_GET["Page"]) {$Page=1;} $Prev_Page = $Page-1; $Next_Page = $Page+1; $Page_Start = (($Per_Page*$Page)-$Per_Page); if($Num_Rows<=$Per_Page) {$Num_Pages =1;} else if(($Num_Rows % $Per_Page)==0) {$Num_Pages =($Num_Rows/$Per_Page) ;} else {$Num_Pages =($Num_Rows/$Per_Page)+1; $Num_Pages = (int)$Num_Pages;} $pic2 .=" order by thumbnailID ASC LIMIT $Page_Start , $Per_Page"; $pic1 = mysql_query($pic2); $cell = 0; $link1 = "SELECT * FROM images"; $result_link1 = mysql_query($link1); $link = mysql_fetch_array($result_link1); $alt1 = "SELECT * FROM images"; $alt = mysql_fetch_array(mysql_query($alt1)); echo ' <div id="tablediv"> <table border="0" cellpadding="17" cellspacing="0" class="table"> <tr>'; while($pic = mysql_fetch_array($pic1)) { if($cell % 4 == 0) { echo '</tr><tr>'; } if($cell == 2) { echo ' <td> fillerspace </td>'; } elseif ($cell == 3) { echo ' <td> Fillerspace2 </td>'; } else { echo ' <td> <a href="/' . $link["link"] . '.php"> <div class="image"> <img src="https://s3.amazonaws.com/image/' . $pic["pic"] . '.png" alt="' . $alt["alt"] . '" height="200" width="200" /> </div> </a> </td>'; } $cell++; } echo '</tr></table></div>'; ?> Basically, there are a couple of faults with this code. I didn't include the pagination part, but there is, for simplicity. But right now, when I insert a new record such as this: INSERT INTO `images` VALUES (' ', 'blog', 'yo', '6', 'hello', '2011-02-15T07:24:17Z') The columns go in order of thumbnailID, folder, link, pic, alt, and time.^^^^^^^^ several problem arises. One, the new record is not displayed as the newest entry on my site. So the record is actually placed in one of the paginated pages. How can I reverse the order? The other thing is, it seems like my pic column is the only thing being understood. You see, when I inserted the above record, I checked my site and saw the pic 6, but the link wasn't 'yo', and the alt wasn't 'hello'. Why is that? By the way, my host is awfully terrible. Maybe it's just having a major delay in reading the link and alt? I don't know. That would be the only reasonable answer, unless my code is off. Thank you, and I'll check 10hours from now. |