PHP - Update Google Calendar From Web Form
hello all,
I have been Googling for a bit and have not found a good tut or place to start with adding or updating events on my google calendar from a web form. There should be a ton of tuts on this kind of thing but I can't find them. Any idea where to start? Here is what my php web form collects: Name, email, date (this is a future date the user is signing up for), notes The Form has a title: Craft and Lesson Schedule Which I would like to show on the gcal as the event name. I did see something about using php and Zend <?php // load classes require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata'); Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); Zend_Loader::loadClass('Zend_Gdata_Calendar'); Zend_Loader::loadClass('Zend_Http_Client'); // connect to service $gcal = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; $user = "username@gmail.com"; $pass = "pass"; $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $gcal); $gcal = new Zend_Gdata_Calendar($client); // validate input if (empty($_POST['title'])) { die('ERROR: Missing title'); } if (!checkdate($_POST['sdate_mm'], $_POST['sdate_dd'], $_POST['sdate_yy'])) { die('ERROR: Invalid start date/time'); } if (!checkdate($_POST['edate_mm'], $_POST['edate_dd'], $_POST['edate_yy'])) { die('ERROR: Invalid end date/time'); } $title = htmlentities($_POST['title']); $start = date(DATE_ATOM, mktime($_POST['sdate_hh'], $_POST['sdate_ii'], 0, $_POST['sdate_mm'], $_POST['sdate_dd'], $_POST['sdate_yy'])); $end = date(DATE_ATOM, mktime($_POST['edate_hh'], $_POST['edate_ii'], 0, $_POST['edate_mm'], $_POST['edate_dd'], $_POST['edate_yy'])); // construct event object // save to server try { $event = $gcal->newEventEntry(); $event->title = $gcal->newTitle($title); $when = $gcal->newWhen(); $when->startTime = $start; $when->endTime = $end; $event->when = array($when); $gcal->insertEvent($event); } catch (Zend_Gdata_App_Exception $e) { echo "Error: " . $e->getResponse(); } echo 'Event successfully added!'; } ?> however, this looked out of date? Similar TutorialsHi, at the moment, I am pulling events from my Google Calendar and showing them by calling the outputCalendarByDateRange() function below. Now would like to be able to update/Delete them <html> <head> <title>Gdata</title> </head> <body> <?php //session_start(); //ini_set('display_errors',1); //ini_set('display_startup_errors',1); //error_reporting (E_ALL); //DATES if(!isset($_REQUEST['from'])){ $newdateTimeStart = "01/01/2009"; } else { $newdateTimeStart = $_REQUEST['from']; } if(!isset($_REQUEST['to'])){ $newdateTimeEnd = "11/05/2011"; } else { $newdateTimeEnd = $_REQUEST['to']; } $startyear = substr($newdateTimeStart, 6, 4); $startmonth = substr($newdateTimeStart, 3, 2); $startday = substr($newdateTimeStart, 0, 2); $newdateTimeStart = $startyear.'-'.$startmonth.'-'.$startday; $endyear = substr($newdateTimeEnd, 6, 4); $endmonth = substr($newdateTimeEnd, 3, 2); $endday = substr($newdateTimeEnd, 0, 2); $newdateTimeEnd = $endyear.'-'.$endmonth.'-'.$endday; $dateStart = $newdateTimeStart; $dateEnd = $newdateTimeEnd; //between dates function outputCalendarByDateRange($client, $startDate='2007-05-01', $endDate='2007-08-01') { $gdataCal = new Zend_Gdata_Calendar($client); $query = $gdataCal->newEventQuery(); $query->setUser('default'); $query->setVisibility('private'); $query->setProjection('full'); $query->setOrderby('starttime'); $query->setStartMin($startDate); $query->setStartMax($endDate); $eventFeed = $gdataCal->getCalendarEventFeed($query); echo "<ul>\n"; foreach ($eventFeed as $event) { echo "\t<li>" . $event->title->text . " (" . $event->id->text . ")\n"; echo "\t\t<ul>\n"; foreach ($event->when as $when) { echo "\t\t\t<li>Starts: " . $when->startTime . "</li>\n"; } echo "\t\t</ul>\n"; echo "\t</li>\n"; } echo "</ul>\n"; } //Connect to google calendar //If you do not have access to the PHP.INI file on the remote server, you should use the following statement to set the path information for Zend framework $clientLibraryPath = 'libraries'; $oldPath = set_include_path(get_include_path() . PATH_SEPARATOR . $clientLibraryPath); // load ZEND classes require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata'); Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); Zend_Loader::loadClass('Zend_Gdata_Calendar'); Zend_Loader::loadClass('Zend_Http_Client'); // connect to calendar service $gcal = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; $user = "***"gmail.com"; //Insert your google username $pass = "***"; //Insert your Google password //$user = stripslashes($_POST['user']); //Insert your google username //$pass = stripslashes($_POST['pass']); //Insert your Google password $_SESSION['user'] = $user; $_SESSION['pass'] = $pass; $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $gcal); $gcal = new Zend_Gdata_Calendar($client); function createEvent ($client, Zend_GData_Calendar $gcal, $title = 'testing google calendar', $desc='this is great', $where = 'at work', $startDate = '2011-04-20', $startTime = '10:00', $endDate = '2011-04-20', $endTime = '11:00', $tzOffset = '+01') { $newEvent = $gcal->newEventEntry(); $newEvent->title = $gcal->newTitle($title); $newEvent->where = array($gcal->newWhere($where)); $newEvent->content = $gcal->newContent("$desc"); $when = $gcal->newWhen(); $when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00"; $when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00"; $newEvent->when = array($when); // Upload the event to the calendar server // A copy of the event as it is recorded on the server is returned $createdEvent = $gcal->insertEvent($newEvent); return $createdEvent->id->text; } echo outputCalendarByDateRange($client, "$dateStart", "$dateEnd"); ?> </body> </html> Not sure if I posted this in the right board: As I'm setting up a plugin to parse Google Calendar events, when they are set as All Day events, they "end" at midnight, which pushes them into the next day. So if an event is to run All Day Friday, Saturday, and Sunday, it actually shows the end date as Monday, since it's midnight. Any thoughts? I have events added to mysql on my site and wish to them also to be added to my Google Calendar. Is this possible? Hi, I want to check entered dates and times that a user selects against my "book-off" calendar which is a Google Calendar. The dates× from Google is in the form: 2011-04-29T23:00:00.000+02:00 The dates in my booking software (ABPro) is in the form: 2011-04-29 Times in form: 23:00:00 All I want the function to return is a number other than 0 if any of the dates/times in Google feed overlap the requested date/time entered in the booking. So I add a function and get the feed from Google: Code: [Select] function checkOverlapG($calendarID, $startdate, $starttime, $enddate, $endtime){ // Create an instance of the Calendar service using an unauthenticated //HTTP client $service = new Zend_Gdata_Calendar(); //Retrieving events in order of start time $query = $service->newEventQuery(); $query->setUser('calendarID'); // Set to $query->setVisibility('private-magicCookieValue') if using MagicCookie auth $query->setVisibility('public'); $query->setProjection('full'); $query->setOrderby('starttime'); $query->setSortOrder('ascending'); //start with first event in future //seFutureevents must be commented out when using start and end times. $query->setFutureevents('true'); $query->setSingleEvents('true'); $query->setMaxResults('200'); //Guess this could be anything, but can possibly make things slower. Default 25 events //$query->setStartMin('2006-12-01'); //$query->setStartMax('2006-12-16); // setStartMax is exclusive, will not include last date. Must add +1 day. // Retrieve the event list from the calendar server try { $eventFeed = $service->getCalendarEventFeed($query); } catch (Zend_Gdata_App_Exception $e) { echo "Error: " . $e->getMessage(); return null; } Now I want to compare the dates and times and see if any of them collide or overlap. I want to add a counter, and if any of the events overlap, I want the counter to add one number. 1. the first thing I do is check if the event feed include. any events. 2. then I add a counter 3. then I run a foreach to retrieve events one at a time 4. then I change the date and time format from Google Event to match the date and time format form the booking. 5. If fullday event from google, no time information is added, so I add this 6. COMPARE DATES AND TIMES and if overlapping events --> n++; I've not gotten this code to work. Probably I'm doing something wrong, and I'm sorry but I'm completely new to this. Getting the Google Calendar data is working fine, and so is changing the format of the dates/times to be same format as request data. After that (and before, I don't know). Code: [Select] $gCount = count($eventFeed); $n = 0; if (gCount>0){ foreach($eventFeed as $event){ foreach ($event->when as $when) { //Getting rid of extra 00's and time zone info for now $startGevent = $when->startTime; $startGevent = str_replace('.000+02:00',"",$startGevent); $endGevent = $when->endTime; $endGevent = str_replace('.000+02:00',"",$endGevent); //Splitting date and time into two variables list($startDateEvent, $startTimeEvent) = split('T',$startGevent); list($endDateEvent, $endTimeEvent) = split('T',$endGevent); //Fill in the blanks if($startTimeEvent!=0) {} else{$startTimeEvent = "00:00:00";} if($endTimeEvent!=0) {} else{$endTimeEvent = "00:00:00";} //Compare dates if($startdate == $endDateEvent){ if($starttime > $endTimeEvent OR $endtime < $startTimeEvent){} else { n++; } } if($enddate == $startDateEvent){ if($endtime < $startTimeEvent OR $starttime > $endTimeEvent){} else { n++; } } } } return $n; } Hi i have this simple update form and scrip but somehow it doesnt seem to be update the field on the database can someone help out please. The html form is the second form bellow where the action send to status_update.php HTML FORM Code: [Select] <?php include("../header.html"); ?> <?php include("header_news.html"); extract($_REQUEST,EXTR_SKIP); ?><?php /* print("sfilm_refnum = $sfilm_refnum<BR>"); print("sfilm_addr01 = $sfilm_addr01<BR>"); print("sfilm_postcode = $sfilm_postcode<BR>"); print("Film Client = $fclient<BR>"); */ ?> <form id="search" action="list.php" method="post" name="search"> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#eeeeee"> <tr> <td align="right" width="140"></td> <td width="320"><span class="hofblack10"> </span> </td> <td align="center" width="100"><input type="hidden" name="lstart" value="<?php print("$lstart"); ?>" /><input type="hidden" name="lend" value="<?php print("$lend"); ?>" /><input type="hidden" name="lamount" value="<?php print("$lamount"); ?>" /></td> <td align="center" width="100"></td> <td align="right"></td> </tr> </table> </form> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#4050c4"> <tr> <td width="60" class="hofwhite10">action</td> <td width="140"><span class="hofwhite14">DATE</span></td> <td width="80"><span class="hofwhite14">ID</span></td> <td><span class="hofwhite14">News Titile</span></td> <td width="100"><span class="hofwhite14">Status</span></td> </tr> <tr height="0"> <td bgcolor="white" width="60"></td> <td bgcolor="white" width="140" height="0"></td> <td bgcolor="white" width="80" height="0"></td> <td bgcolor="white" height="0"></td> <td bgcolor="white" width="100" height="0"></td> </tr> </table><table width="780" border="0" cellspacing="0" cellpadding="4"><tr> <td width="60"></td> <td width="80"></td> <td><a class="blueullrg" href="add.php">Add News</a></td> <td align="right" width="120"></td> </tr> <tr height="0"> <td width="60" height="0"></td> <td width="80" height="0"></td> <td height="0"></td> <td align="right" width="120" height="0"></td> </tr> </table> <?php //get the DB connection variables include("../../../includes/config.php"); //connect to DB $connection = @mysql_connect($db_address,$db_username,$db_password) or die("Couldn't CONNECT."); $db = @mysql_select_db($db_name, $connection) or die("Couldn't select DATABASE."); $query2="SELECT * FROM news WHERE !(news_status='deleted')"; $result2 = mysql_query($query2) or die("Couldn't execute QUERY - Select NEWS Qty"); $fqty = mysql_num_rows($result2); //SELECT or FIND the same USERNAME $query3="SELECT * FROM news WHERE !(news_status='deleted') ORDER BY news_id DESC"; $result3 = mysql_query($query3) or die("Couldn't execute QUERY - Select NEWS"); while ($row = mysql_fetch_array($result3)) { $news_id = $row['news_id']; $news_title = $row['news_title']; $news_story = $row['news_story']; $news_image = $row['news_image']; $news_image_caption = $row['news_image_caption']; $news_image_link = $row['news_image_link']; $news_date_day = $row['news_date_day']; $news_date_month = $row['news_date_month']; $news_date_year = $row['news_date_year']; $news_status = $row['news_status']; $news_website = $row['news_website']; $news_date_created = $row['news_date_created']; $news_date_modified = $row['news_date_modified']; ?> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#eeeeee"> <tr> <td width="60"><span class="hofblack10"> <?php if($news_status=="deleted"){ print("<a class='hifblack10'>deleted</span>"); }ELSE{ print("<a class='blueul' href='edit.php?id=$news_id'>edit</a>"); } ?> </span></td> <td width="140"><span class="titlegrey12"> <?php if(!$news_date_day) { echo "00"; } else{ echo $news_date_day; } echo "/"; if(!$news_date_month) { echo "00"; }else{ echo $news_date_month; } echo "/"; if(!$news_date_year) { echo "0000"; }else{ echo $news_date_year; } ?> </span></td> <td width="80"><span class="titlegrey12"><?php print("$news_id"); ?></span> </td> <td><?php if($news_status=="deleted") { print("<class='hofblack10'>$news_title</span>"); }ELSE{ print("<a class='blueul' href='edit.php?id=$news_id'>$news_title</a>"); } ?></td> <td width="100"> <form id="list_update" action="status_update.php" method="post" name="list_update"> <select name="newnstatus" size="1"> <option <?php if($row['news_status'] == "") { print("selected"); } ?> selected="selected" value="">Status...</option> <option <?php if($row['news_status'] == "on") { print("selected"); } ?> value="on">On</option> <option <?php if($row['news_status'] == "off") { print("selected"); } ?> value="off">Off</option> <option <?php if($row['news_status'] == "deleted") { print("selected"); } ?> value="deleted">Delete</option> </select> <input type="hidden" name="nstatus" value="<?php echo $row[news_status]; ?>" /> <input type="hidden" name="id" value="<?php echo $row[news_id]; ?>" /> <input type="submit" name="update" value="update" /> </form> </td> </tr> <tr height="0"> <td bgcolor="white" width="60"></td> <td bgcolor="white" width="140" height="0"></td> <td bgcolor="white" width="80" height="0"></td> <td bgcolor="white" height="0"></td> <td bgcolor="white" width="100" height="0"></td> </tr> </table> <?php } mysql_close($connection);//}?> <table width="780" border="0" cellspacing="0" cellpadding="4"> <tr> <td width="60"></td> <td width="80"></td> <td><a class="blueullrg" href="add.php">Add News</a></td> <td align="right" width="120"></td> </tr> </table><?php // include("list_navigation.html"); ?> <?php include("../footer.html"); ?> </div></body></html> The action script php Code: [Select] <?php /* echo "fstatus: ".$fstatus."<BR>"; echo "id: ".$id."<BR>"; echo "fclient: ".$fclient."<BR>"; echo "newfstatus: ".$newfstatus."<BR>";*/ //set the date of agreement $timestamp = date('l jS \of F Y h:i:s A'); //get the DB connection variables include("../../../includes/config.php"); //connect to DB $connection = @mysql_connect($db_address,$db_username,$db_password) or die("Couldn't CONNECT."); $db = @mysql_select_db($db_name, $connection) or die("Couldn't select FILMS DATABASE."); // All appears well, so enter into database $query= "UPDATE news SET news_status = '$newnstatus' WHERE news_id='$id'"; $result = mysql_query($query) or die("could not execute query - Update FILMS Record to DB"); //setup an email to the Admin @ hof, w/o attachment $emailto="xx@xxx.co.uk"; $emailfrom="no-reply@xxxx.co.uk"; $emailsubject="xx Record Updated"; $emailmessage="Hello Registrar\n\n"; $emailmessage.="News ID: ".$id."\n"; $emailmessage.="Updated on: ".$timestamp."\n\n"; $emailmessage.="Status was: ".$nstatus."\n"; $emailmessage.="Status now: ".$newfnstatus."\n"; $emailmessage.="Thank you,\n\n"; $emailmessage.="Web Site ROBOT\n"; $emailmessage.="(Administrator)\n"; $emailmessage.="xxx.co.uk | xxx.biz\n"; $emailmessage.="----------------------------------------------\n"; $emailmessage.="e. http://www.xxx.co.uk/contact.php\n"; $emailmessage.="w. http://www.xxx.co.uk\n"; $emailheader="From: xxx.co.uk<$emailfrom>"; $emailheader .= 'Cc: xxx@xxx.co.uk'."\r\n"; $emailheader .= 'Bcc: xxx@xxxxx.co.uk'."\r\n"; $ok=mail($emailto,$emailsubject,$emailmessage,$emailheader); mysql_close($connection); if ($ok) { header("Location: list.php"); /* Redirect browser */ exit; } else { $errmsg="There was a problem, please try later or telephone us direct."; $errsta="1"; include("edit_error.html"); //echo "<p>Mail could not be sent. Sorry!</p>"; exit; } ?> Thanks in advance Good morning. I am looking fo some help with an update script to update all rows in a table. This is what I have for a form and all looks well. form.php <?php // run the query and put the results in an array variable called $result $result = mysql_query("SELECT * FROM table ORDER BY 'id', 'title', 'text', 'number'"); print "<form method='post' action='update.php'> <table width='100%' border='0' cellspacing='1' cellpadding='1'><tr> <td align='center'><strong>ID</strong></td> <td align='center'><strong>Title</strong></td> <td align='center'><strong>text</strong></td> <td align='center'><strong>Number</strong></td> </tr>\n"; // start a loop to print all of the courses with their book information // the mysql_fetch_array function puts each record into an array. each time it is called, it moves the array counter up until there are no more records left while ($Update = mysql_fetch_array($result)) { // start displaying the info; the most important part is to make the name an array (notice bookinfo[$i]) print "<td align='center'><p>{$Update['id']}</p></td>\n"; print "<td align='center'><input type='text' name='title' value='{$Update['title']}' /></td>"; print "<td align='center'><input type='text' size='40' name='text' value='{$Update['text']}' /></td>\n"; print "<td align='center'><input type='text' size='40' name='number' value='{$Update['number']}' /></td>\n"; print "</tr>\n"; // add 1 to the count, close the loop, close the form, and the mysql connection } print "<tr> <td colspan='4' align='center'><input type='submit' value='submit' />"; print "</td> </tr> </table> </td> </tr> </form> </table>"; print "</tr>\n"; ?><br /><br /> My question is. How do I update this info into the database with the proper info. ie. Update.php? Hello How can i add google recaptcha to this code https://github.com/Tutorialwork/Tutorials/blob/master/PHP Rechtesystem/addnews.php Hi there guys, what would be the best way to print information from PHP contact form to google spreadsheet, i've tried to follow this tutorial: http://www.farinspace.com/saving-form-data-to-google-spreadsheets/ And i fail in every way. I have few fields only, let's say Full name, Email, Address, Checkbox and Select (dropdown) option, i would like to know how can i store inputs to the google spreadsheet, not single one, but all of them... Help is much appreciated! The upload script I'm using performs successfully in Google, but not in IE or FF. My code is supposed to update the table but it just wipes all the fields clean if (isset($_POST['Update'])){ // here we encrypt the password and add slashes if needed if (isset($_POST['add'])) { $_POST['element_1'] = addslashes($_POST['element_1']); $_POST['element_7_1'] = addslashes($_POST['element_7_1']); $_POST['element_7_2'] = addslashes($_POST['element_7_2']); $_POST['element_2'] = addslashes($_POST['element_2']); $_POST['element_3'] = addslashes($_POST['element_3']); $_POST['element_4'] = addslashes($_POST['element_4']); $_POST['element_5'] = addslashes($_POST['element_5']); $_POST['element_13'] = addslashes($_POST['element_13']); $_POST['element_11'] = addslashes($_POST['element_11']); $_POST['element_6'] = addslashes($_POST['element_6']); $_POST['element_12'] = addslashes($_POST['element_12']); $_POST['element_8'] = addslashes($_POST['element_8']); //------------------// $e1 = $_POST['element_1']; $e71 = $_POST['element_7_1']; $e72 = $_POST['element_7_2']; $e2 = $_POST['element_2']; $e3 = $_POST['element_3']; $e4 = $_POST['element_4']; $e5 = $_POST['element_5']; $e13 = $_POST['element_13']; $e11 = $_POST['element_11']; $e6 = $_POST['element_6']; $e12 = $_POST['element_12']; $e8 = $_POST['element_8']; } mysql_real_escape_string($update = "UPDATE `YBK_Ads` SET `BSN` = '{$e1}', `CNF` = '{$e71}', `CNL` = '{$e72}', `ADD` = '{$e2}', `CITY` = '{$e3}', `STATE` = '{$e4}', `ZIP` = '{$e5}', `AS` = '{$e13}', `PT` = '{$e11}', `CN` = '{$e6}', `BY` = '{$e12}', `ACI` = '{$e8}' WHERE `ID` = '{$_POST['id']}'"); mysql_query($update) or die( 'Query string: ' . $update . '<br />Produced an error: ' . mysql_error() . '<br />' ); //header("Location: http://ybk.watsonn.com/list.php"); } I am a php newbie and with help from someone on this forum managed to get my php form working. I am now trying to add recaptcha 3 but can't get it to work. I have added my code to this post and would appreciate some pointers. <?php /* This is the Header PHP file */ ?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content="My Name"> <title>My Title</title> <!--Bootstrap Core CSS--> <link href="assets/css/bootstrap.min.css" rel="stylesheet"> <!--Font Awresome Icons--> <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600&display=swap" rel="stylesheet"> <!--Google Fonts--> <link href="assets/css/fontawesome/css/all.min.css" rel="stylesheet"> <!--Adobe Typekit Fonts--> <link href="https://use.typekit.net/jtf1geg.css" rel="stylesheet"> <!--Custom CSS--> <link href="assets/css/custom.css" rel="stylesheet"> <!--Favicon--> <link rel="icon" type="image/png" sizes="32x32" href="assets/img/MyFavicon32WhiteAlt.png"> <!--Google reCaptcha--> <script src="https://www.google.com/recaptcha/api.js"></script> <script> function onSubmit(token) { document.getElementById("contact-form").submit(); } </script> </head> <body> <!--HEADER--> <header class="site-header"> <!--Navbar--> <nav class="navbar"> <!-- Navbar brand --> <div class="navbar-brand"> <img src="assets/img/myLogo.png" id="wd-logo" alt="My Logo"> </div> <!-- Linking Menu Text to Collapse Button --> <div class="menu-button"> <button class="navbar-toggler button" type="button" data-toggle="collapse" data-target="#navbarSupportedContent20" aria-controls="navbarSupportedContent20" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-text">Menu</span> </button> <!-- Collapse Button --> <button class="navbar-toggler button animated-icon" type="button" data-toggle="collapse" data-target="#navbarSupportedContent20" aria-controls="navbarSupportedContent20" aria-expanded="false" aria-label="Toggle navigation"> <span></span> <span></span> <span></span> </button> <!-- Collapse Button End --> </div> <!-- Linking Menu Text to Collapse Button End --> <!-- Collapsible content --> <div class="collapse navbar-collapse" id="navbarSupportedContent20"> <!-- Links --> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="index.php">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="contact.php">About</a> </li> <li class="nav-item"> <a class="nav-link" href="contact.php">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="contact.php">Our Work</a> </li> <li class="nav-item active"> <a class="nav-link" href="contact.php">Contact<span class="sr-only">(current)</span></a> </li> </ul> <!-- Links End --> </div> <!-- Collapsible Content End --> </nav> <!--Navbar End--> </header> <!--Header End--> <hr> <!--Content--> <section class="main"> <?php // This is the contact form // Message Vars $msg = ''; $msgClass = ''; // Check to see if the form has been submitted if(filter_has_var(INPUT_POST, 'submit')) { // Input Data Variables $firstname = htmlspecialchars($_POST['firstname']); $lastname = htmlspecialchars($_POST['lastname']); $phonenumber = htmlspecialchars($_POST['phonenumber']); $email = htmlspecialchars($_POST['email']); $dropdown = htmlspecialchars($_POST['selectdropdown']); $message = htmlspecialchars($_POST['message']); $checkbox = htmlspecialchars($_POST['checkbox'] ?? 0); // Check required fields if(!empty($firstname) && !empty($lastname) && !empty($phonenumber) && !empty($email) && !empty($dropdown) && !empty($message) && !empty($checkbox)) { // If passed, check email address if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) { // If failed, Email address is not valid $msg = 'Please use a valid email address'; $msgClass = 'alert-danger'; } else { // Recipient email address and information to be sent to them $toEmail = 'hello@example.co.uk'; $subject = 'Contact Request from Website'; $body = '<h2>Contact Request</h2> <h4>Name</h4><p>'.$firstname. ' '.$lastname.'</p> <h4>Phone Number</h4><p>'.$phonenumber.'</p> <h4>Email Address</h4><p>'.$email.'</p> <h4>Subject</h4><p>'.$dropdown.'</p> <h4>Message</h4><p>'.$message.'</p>'; // Email Headers $headers = "MIME-VERSION: 1.0" ."\r\n"; $headers .="Content-Type:text/html;charset=UTF-8" ."\r\n"; // Additional Headers $headers .= "From: " .$firstname. "".$lastname." <".$email.">" ."\r\n"; $recaptcha_url = "https://www.google.com/recaptcha/api/siteverify"; $recaptcha_secret ="secrettoken"; $recaptcha_response = $_POST['g-recaptcha-response']; $recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response); $recaptcha = json_decode($recaptcha, true); if($recaptcha['success'] == 1 AND $recaptcha['score'] >= 0.5 AND $recaptcha['action'] == "submit") { if(mail($toEmail, $subject, $body, $headers)) { // Message Sent $msg = 'Verfication successful, your message has been sent'; $msgClass = 'alert-success'; } else { // Message failed $msg = 'Your message has NOT been sent'; $msgClass = 'alert-danger'; } } } } else { // Failed $msg = 'Please fill in all fields'; $msgClass = 'alert-danger'; } } ?> <div class="container clearfix content-container"> <h1 class="section-title">Contact Us</h1> <p>If you have any questions about the services we provide or would like to chat about a new website project, please get in touch using any of the options below. We would love to hear from you!</p> <!--Contact Page Row--> <div class="row"> <div class="col-lg-6 contact-details"> <div class="row"> <div class="col-lg-12"> <img src="assets/img/contact-us.jpg" class="img-responsive d-block contact-image" alt="Contact Us Image"> </div> </div> <div class="row"> <div class="col-lg-12 contact-name"> <span class="d-inline-block contact-inline-block"><i class="fas fa-user fa-2x"> </i></span> <span class="d-inline-block"><p class="contact-details">me</p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-phone"> <span class="d-inline-block contact-inline-block"><a href="tel:01234 567890"><i class="fas fa-mobile-alt fa-2x"></i></a></span> <span class="d-inline-block"><a href="tel:01234 567890"><p class="contact-details">01234 567890</a></p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-email"> <span class="d-inline-block contact-inline-block"><a href="mailhandler.php"><i class="fas fa-envelope-square fa-2x"></i></a></span> <span class="d-inline-block"><a href="mailhandler.php"><p class="contact-details">hello@wexample.co.uk</a></p></span> </div> </div> <div class="row"> <div class="col-lg-12 contact-fb"> <span class="d-inline-block contact-inline-block"><a href="https://www.facebook.com/example/" target="_blank"><i class="fab fa-facebook-square fa-2x"></a></i></span> <span class="d-inline-block"><a href="https://www.facebook.com/example/" target="_blank"><p class="contact-details">@example</a></p></span> </div> </div> </div> <!--Contact Form--> <div class="col-lg-6 contact-form d-block"> <?php if($msg != ''): ?> <div class="alert <?php echo $msgClass; ?>"><?php echo $msg; ?></div> <?php endif;?> <form method="post" action="contact.php" role="form" id="contact-form"> <div class=" row form-group"> <div class="col-lg-6"> <label for="firstnameid">First name<span class="asterisk"> *</span></label> <input type="text" name="firstname" class="form-control mb-3" id="firstnameid"> </div> <div class="col-lg-6"> <label for="lastnameid">Last name<span class="asterisk"> *</span></label> <input type="text" name="lastname" class="form-control mb-3" id="lastnameid"> </div> </div> <div class="row form-group"> <div class="col-lg-6"> <label for="phonenumber">Phone number<span class="asterisk"> *</span></label> <input type="tel" name="phonenumber" class="form-control mb-3" id="phonenumberid"> </div> <div class="col-lg-6"> <label for="emailid">Email address<span class="asterisk"> *</span></label> <input type="email" name="email" class="form-control mb-3" id="emailid"> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <label for="subjectid">How can we help<span class="asterisk"> *</span></label> <select class="form-control mb-3" name="selectdropdown" id="subjectid"> <option value="">Please choose an option</option> <option value="I would like to discuss a project">I would like to discuss a project</option> <option value="Existing Web 2 Digital client enquiry">Existing client enquiry</option> <option value="General enquiry">General enquiry</option> </select> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <label for="messageid">Tell us a little bit more<span class="asterisk"> *</span></label> <textarea name="message" class="form-control mb-3" id="messageid" rows="6"></textarea> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <p><span class="asterisk"> *</span> indicates required field</p> </div> </div> <div class="row form-group"> <div class="col-lg-12 form-check"> <input type="checkbox" name="checkbox" class="form-check-input" id="formcheckid"> <label for="formcheckid" class=form-check-label mb-3>By checking this tickbox you have confirmed that we can collect the information in this form for the purposes outlined in our <a href="privacypolicy.php">privacy policy.</a></label> </div> </div> <div class="row form-group"> <div class="col-lg-12"> <button type="submit" name="submit" class="btn btn-primary mt-4 g-recaptcha" data-sitekey="sitetoken" data-callback='onSubmit' data-action='submit'>Send Message </button> </div> </div> </form> </div> <!--Contact Form End--> </div> <!--Contact Page Row End--> </div> <!--Container end--> <?php echo file_get_contents('footer.php'); ?>
Hopefully I can explain this well. I have a list, which is linked he http://hoosierhoopsreport.com/test-11-rank/ When I'm done, I'm trying to set up the list I, as ADMIN, can make changes to the list without having to go into my database. I'm mostly concerned with the # column, but once we get through this, I can apply what I've learned. I'm setting the form to print # and school as text fields. I'm getting id, nameFirst and nameLast as hidden values to pass to my form handler. When I hit submit, I'm getting this error: Quote You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id='172'' at line 5 Query: UPDATE wp_playerRank_copy SET rankClass='10', hschool='Avon HS', WHERE id='172' I'm pretty sure it's just filtering through the information to most last piece of data handled, which isn't what I want, but I also don't understand why I'm getting the error. Here is the code dealing with the form: Code: [Select] <form id="class2011" action="/resources/form/dbplayerUpdate.php" method="post"> <table class="playerTable" border="0" width="100%"> <thead> <tr> <th class="num">#</th> <th class="top">Top 10</th> <th class="height">HT</th> <th class="pos">POS</th>'; if (current_user_can("access_s2member_level4")){ echo '<th class="level">Level</th>'; } echo '<th class="school">City (School)</th>'; if (current_user_can("access_s2member_level4")){ echo '<th class="summer">Summer Team</th>'; } echo '<th class="college">College</th> </tr> </thead> <tfoot> <tr> <td colspan="8" align="right">(+) moved up; (d) debut; (s) switched from another position / <b>Colleges in bold print means committed</b></td> </tr> <tr> <td><input id="Submit" name="Submit" type="submit" value="Submit" /></td> </tr> </tfoot> <tbody>';$query = 'SELECT * FROM wp_playerRank_copy WHERE year="2011" ORDER BY rankClass ASC'; $results = mysql_query($query); while($line = mysql_fetch_assoc($results)) { if ($line['rankClass'] != 0) { echo ' <tr> <td> <input type="hidden" name="db_id" value="' . $line['id'] . '"size="2"> <input type="text" name="rankClass" value="' . $line['rankClass'] . '"size="2">' . $line['devClass'] .'</td> <td>'; if ($line['wpID'] > '0') { echo ' <input type="hidden" name="nameFirst" value="' . $line['nameFirst'] . '"size="2"> <input type="hidden" name="nameLast" value="' . $line['nameLast'] . '"size="2"> <a href="/tag/' . $line['nameFirst'] . '-' . $line['nameLast'] .'">'. $line['nameFirst'] . ' ' . $line['nameLast'] . '</a>'; } else { echo $line['nameFirst'] . ' ' . $line['nameLast']; } echo '</td><td>'. $line['height'] . '</td> <td>'. $line['position'] . '</td>'; if (current_user_can("access_s2member_level4")){ echo '<td>'. $line['level'] . '</td>'; } echo '<td><input type="text" name="hschool" value="' . $line['hschool'] .'"size="30"></td>'; if (current_user_can("access_s2member_level4")){ echo '<td>'. $line['summer'] . '</td>'; } if ($line['committed'] == 'y') { echo ' <td><strong>'. $line['college'] . '</strong></td> ';} echo '</tr> ';} } echo ' </tbody></table></form> Here is the form handler: Code: [Select] if(!$con = mysql_connect("localhost","jwrbloom_","redcoach")) { die("Could not connect to database: ".mysql_error()); } mysql_select_db("jwrbloom_wpHHR", $con); $nameFirst = $_POST['nameFirst']; $nameLast = $_POST['nameLast']; $db_id = $_POST['db_id']; $rankClass = $_POST['rankClass']; $hschool = $_POST['hschool']; //$grade = $_POST['grade']; //$coachSchool = $_POST['coachSchool']; //$feet = $_POST['feet']; //$inches = $_POST['inches']; /* search for existing row */ $sql = "SELECT id FROM wp_playerRank_copy WHERE nameFirst='".mysql_real_escape_string($nameFirst)."' AND nameLast='".mysql_real_escape_string($nameLast)." '"; if(!$result = mysql_query($sql)) { die(mysql_error()."<br />Query: ".$sql); } if(mysql_num_rows($result)) { $row = mysql_fetch_assoc($result); /* update existing row */ $sql = "UPDATE wp_playerRank_copy SET rankClass='".mysql_real_escape_string($rankClass)."', hschool='".mysql_real_escape_string($hschool)."', WHERE id='".$row['id']."'"; if(!$result = mysql_query($sql)) { die(mysql_error()."<br />Query: ".$sql); } } I am trying to create a form on my website to have people sign up for email notifications. Little confuse on this. i know i can do a form to submit info into a db or for an email to be sent to me. i have seen some on website that have a sign up form for newsletters or etc... how do these forms work? is there someone receiving all these emails or getting signed up user from a db and emailing each person? confuse on this topic. can someone explain? Having trouble where I think I need to provide most of my code to see what is happening. Trying to output a simple table of cameras. They are stored as part of a form with data filled in already. A user can change and hit the apply button for any camera in the row. The changes should update the db for that camera only (just that one row). The problem is that when I hit apply it doesn't make the change to the row. The exception is the very last row (last camera in the list). I tried to simplify the mysql update query to just one select (camera_status) to figure out what is going on. The problem is that if I echo camera_status it is showing the wrong value. i.e. if I change the form select from Enabled to Disabled. Something wrong with how I'm doing the POST? I appreciate any guidance. Code: [Select] <?php // Dont allow direct linking defined('_JEXEC') or die('Direct Access to this location is not allowed.'); //get current user $user =& JFactory::getUser(); // get a reference to the database $db = &JFactory::getDBO(); if (isset($_POST['apply_changes'])) { //process changes to camera options $camera_id = (int) $_POST['camera_id']; echo "CAMERA ID ".$camera_id; $camera_status = check_input($_POST['camera_status']); echo "CAMERA STATUS ".$camera_status; $camera_name = check_input($_POST['camera_name']); $camera_quality = check_input($_POST['camera_quality']); $query_insert_camera = 'UPDATE `#__cameras` SET `camera_status` ="'.$camera_status.'" WHERE `camera_id`='.$camera_id; echo "CAMERA query ".$query_insert_camera; $db->setQuery($query_insert_camera); $db->query(); } function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { show_error($problem); } return $data; } function show_error($myError) { echo $myError; exit(); } echo "<html>"; echo "<head>"; ?> <script type="text/javascript"> function oncameraSubmit(camera_id) { //TODO get camera name i.e. "Apply changes to <camera name>" document.active_cameras.camera_id.value = camera_id; return confirm('Apply changes?'); } </script> <?php $query_camera_name = "SELECT camera_id, camera_name, camera_status, camera_quality, camera_hash, camera_type FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'"; $db->setQuery($query_camera_name); //get number of cameras so we can build the table accordingly $db->query(); $num_rows = $db->getNumRows(); // We can use array names with loadAssocList. $result_cameras = $db->loadAssocList(); echo "</head>"; echo "<body>"; //check if we have cameras running (basically someone logged in) if (!isset($result_cameras)) { //TODO check if query failed } else { if ($num_rows == 0) { echo '<b><i><center>You currently have no cameras setup. Add a Camera below.</center></i></b>'; } else { ?> <form name="active_cameras" action="<?php htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST"> <input type="hidden" name="camera_id" value="" /> <table id="webcam-table"> <thead> <tr> <th>Camera Type</th> <th>Name</th> <th>Quality</th> <th>Status</th> <th>Camera Actions</th> </tr> </thead> <tbody> <?php for($i=0;$i<$num_rows;$i++) { //camera_status if ($result_cameras[$i]["camera_status"] == "ENABLED") { $enabled_option = "value='ENABLED' selected='selected'"; $disabled_option = "value='DISABLED'"; } else { $enabled_option = "value='ENABLED'"; $disabled_option = "value='DISABLED' selected='selected'"; } //camera_quality if ($result_cameras[$i]["camera_quality"] == "HIGH") { $high_option = "value='HIGH' selected='selected'"; $medium_option = "value='MEDIUM'"; $mobile_option = "value='MOBILE'"; } else if ($result_cameras[$i]["camera_quality"] == "MEDIUM") { $high_option = "value='HIGH'"; $medium_option = "value='MEDIUM' selected='selected'"; $mobile_option = "value='MOBILE'"; } else if ($result_cameras[$i]["camera_quality"] == "MOBILE") { $high_option = "value='HIGH'"; $medium_option = "value='MEDIUM'"; $mobile_option = "value='MOBILE' selected='selected'"; } else { //TODO proper logging } //camera_type if ($result_cameras[$i]["camera_type"] == "WEBCAM") { $webcam = "value='WEBCAM' selected='selected'"; $axis = "value='AXIS'"; $other = "value='IPCAM'"; } else if ($result_cameras[$i]["camera_type"] == "AXIS") { $webcam = "value='WEBCAM'"; $axis = "value='AXIS' selected='selected'"; $other = "value='IPCAM'"; } else if ($result_cameras[$i]["camera_type"] == "IPCAM") { $webcam = "value='WEBCAM'"; $axis = "value='AXIS'"; $other = "value='IPCAM' selected='selected'"; } else { //TODO proper logging } echo $result_cameras[$i]["camera_id"]; ?> <tr> <td> <?php echo $result_cameras[$i]["camera_type"] ?> </td> <td> <input type="text" size="32" maxlength="64" name="camera_name" value="<?php echo $result_cameras[$i]["camera_name"]; ?>" /> </td> <td> <select name="camera_quality"> <option <?php echo $high_option; ?>>High</option> <option <?php echo $medium_option; ?>>Medium</option> <option <?php echo $mobile_option; ?>>Mobile</option> </select> </td> <td> <select name="camera_status"> <option <?php echo $enabled_option; ?>>Enabled</option> <option <?php echo $disabled_option; ?>>Disabled</option> </select> </td> <td> <input type="submit" name="apply_changes" value="Apply" onClick="oncameraSubmit(<?php echo $result_cameras[$i]["camera_id"]; ?>);"/> <input type="submit" name="delete" value="Delete" onClick="oncameraDelete(<?php echo $result_cameras[$i]["camera_id"]; ?>);"/> <input type="submit" name="video" value="Launch" onClick="oncameraLaunch(<?php echo $result_cameras[$i]["camera_id"]; ?>);"/> </td> </tr> <?php } echo "</tbody>"; echo "</table>"; echo "</form>"; } } echo "</body>"; echo "</html>"; ?> Hi there i was wondering if its possible to have a count down timer (for say 5 mins) that when it reaches 0 a form is updated.. Code: [Select] <?php // set countdown timer for 5 mins $countdown = '300' if ($countdown == '0'){ update the form somehow? }?> <form id="form1" name="form1" method="POST" action="<?php echo $editFormAction; ?>"> <input name="hiddenField" type="hidden" value="<?php echo $row_query['somedata']; ?>" /> <input type="submit" name="Submit" value="Submit" /> </form> I'm a bit of a noob so any help would be ace. Thanks I have a list that goes about 50 deep that I make changes to quite a bit. Each row has five columns, and the information sits on a database. Instead of making the changes in the database, I'd like to make the changes right on my site, so I can actually the list in order, then submit any changes. (It's just easier to look on my web page than the data table, and it's easier to grant the ability to change data on that page than give another data table access.) They are ordered by rankings 1-50. To do that, I'm picturing rows of data, printed in form elements instead of just printed statically on the page. From there I can make the changes I need (mostly to just the one column) then his Submit. Here is how the code looks now: Code: [Select] <table class="playerTable" border="0" width="100%"> <thead> <tr> <th class="num">#</th> <th class="top">Top 10</th> <th class="height">HT</th> <th class="pos">POS</th>'; if (current_user_can("access_s2member_level4")){ echo '<th class="level">Level</th>'; } echo '<th class="school">City (School)</th>'; if (current_user_can("access_s2member_level4")){ echo '<th class="summer">Summer Team</th>'; } echo '<th class="college">College</th> </tr> </thead> <tfoot> <tr> <td colspan="8" align="right">(+) moved up; (d) debut; (s) switched from another position / <b>Colleges in bold print means committed</b></td> </tr> </tfoot> <tbody>';$query = 'SELECT * FROM wp_playerRank WHERE year="2011" ORDER BY rankClass ASC'; $results = mysql_query($query); while($line = mysql_fetch_assoc($results)) { if ($line['rankClass'] != 0) { echo ' <tr> <td>'. $line['rankClass'] . $line['devClass'] .'</td> <td>'; if ($line['wpID'] > '0') { echo '<a href="/tag/' . $line['nameFirst'] . '-' . $line['nameLast'] .'">'. $line['nameFirst'] . ' ' . $line['nameLast'] . '</a>'; } else { echo $line['nameFirst'] . ' ' . $line['nameLast']; } echo '</td><td>'. $line['height'] . '</td> <td>'. $line['position'] . '</td>'; I'm primarily interested in $line['rankClass'] being editable right on my web page. I"m seen syntax examples, but they have all been just changing one line at a time. I could theoretically make changes in all 50 rows. From a syntax perspective, I feel like I'm going to run into a NAME issue. Example: <input maxlength="5" name="rankClass" size="2" type="text" /> I realize I need to change "rankClass" to PHP that brings in the value from the data table. However, the PHP would also do that for 50 rows of data. Do I need to worry about duplicate instances being name="rankClass"? How would that look? Hi I currently have this form to update the names of each session in the database. However how do I go about updating more than one value. I also want to update the 'order' swell as the name so the order in which they're displayed is updated I want to have another text field next to it for the order which will just be a number but i can't figure out how to update both in the foreach() function Code: [Select] <?php if($_POST['update_sessions']){ foreach($_POST as $sessionid => $sessionname){ mysql_query("UPDATE `sessions` SET `name`='".mysql_real_escape_string($sessionname)."' WHERE `id`='".mysql_real_escape_string($sessionid)."'"); } echo("Done!"); } ?> <form method="post"> <?php $getsessions = mysql_query("SELECT * FROM `sessions` ORDER BY `order`"); while($sessions = mysql_fetch_array($getsessions)){ echo("<input type='text' name='".$sessions['id']."' value='".$sessions['name']."'><br />\n"); } ?> <input type="submit" value="Update" name="update_sessions" /> </form> have 2 scripts one that allows me to insert and upload image and one that allows me to delete and remove image so i was thinking in mix both together so it would be like this first the delete image in an if statment then close } and then { an insert image but with an update mysql query} i am trying to do a modify form where user can modify the data so i will need to update the image on the directory so with both delete and insert would it do the job??? <?php define('ROOT_DIR', './'); define('PROPER', TRUE); /** * include common files */ include_once(ROOT_DIR. 'includes/common.inc.php'); // No album id has been selected if (isset($_GET['drivers'])) { // get the image file name so we // can delete it from the server $sql = "SELECT id, image FROM driversnew WHERE id = {$_GET['drivers']}"; $result = mysql_query($sql) or die('Delete photo failed. ' . mysql_error()); if (mysql_num_rows($result) == 1) { $row = mysql_fetch_assoc($result); define("GALLERY_IMG_DIR", "./images/"); // remove the image and the thumbnail from the server unlink(GALLERY_IMG_DIR . $row['image']); unlink(GALLERY_IMG_DIR . 'thumbs/' . $row['image']); // and then remove the database entry } } /////////// this where the upload script starts/////////// this where the upload script starts//////// this where the upload script starts //define a maxim size for the uploaded images define ("MAX_SIZE","100"); // 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","150"); define ("HEIGHT","100"); // 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)) $src_img=imagecreatefromjpeg($img_name); if(!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 errro occures. If the error occures 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['image']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['image']['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 != "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['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*1024) { 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=time().'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="images/".$image_name; $copied = copy($_FILES['image']['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='images/thumbs/'.$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) { $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("eurico_edy", $con); $query = "UPDATE products SET name = '$name', location = '$location', date_of_birth='$date_of_birth', car_number='$car_number', favourite_track='$favourite_track', least_favourite_track='$least_favourite_track', achievements='$achievements', achievements='$achievements' email='$email', image='$image' WHERE id = '$id'"; echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; echo ''.$newname.''; mysql_close($con); } ?> |