PHP - Passing Session Var To Called File
Hi All,
I am using the uploadify script available at http://uploadify.com/ Now I can get the file uploads working fine with the script below: Code: [Select] <?php session_start(); ?> <link href="/uploadify/uploadify.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/uploadify/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="/uploadify/swfobject.js"></script> <script type="text/javascript" src="/uploadify/jquery.uploadify.v2.1.0.min.js"></script> <input id="fileInput" name="fileInput" type="file" /> <script type="text/javascript">// <![CDATA[ $(document).ready(function() { $('#fileInput').uploadify({ 'uploader' : '/uploadify/uploadify.swf', 'script' : '/uploadify/uploadify.php', 'cancelImg' : '/uploadify/cancel.png', 'auto' : true, 'folder' : '<?php echo $_SESSION['filepath']."/downloads/"; ?>', 'multi' : true }); }); // ]]></script> The problem that I am having is that I also store the mysql connection details in session vars (they change depending on who logs in). I have tried a number of ways of "passing" these session vars to the uploadify.php file which does the grunt work of the uploading, but I can never seem to access them. I obviously dont want to pass them to the uploadify.php script through the js because that will show my credentials in the source code. So, the question is, how can I access these session vars in the called file. I assume its a combination of session_write_end() and session_start() but I havent got the right combination yet. Similar TutorialsHi everyone!
I've been working on a php script to replace links that contain a query with direct links to the files they would redirect to. In this case I have to rewrite the xml with this script. Situation is not optimal, I'm running the chunk script because we're stuck with the execution time limit too. Export filter: This loops over a xml file and splits it into chunks <?php //ini_set('max_execution_time', 10); // ---- includes if ( ! defined('ABSPATH') ) { require_once( dirname( __FILE__ ) . '/wp-load.php' ); } // ---- end includes // console function vwaconsole($input) { $disabled = false; if ($disabled === false) { $a = print_r($input.'</br>'); $a = $input; echo "<script>console.log( '--log--: " . $a . "' );</script>"; } } //end console // settings // $chunk_size = 20; // $home = constant( 'ABSPATH' ); $xml_path = $home."/wp-content/uploads/wpallimport/files/Bastiaansen.xml"; if (fopen($xml_path,"r") != true) { vwaconsole("xml file does not exist"); exit(); } $xml = new DOMDocument(); $xml->formatOutput = true; $xml->preserveWhiteSpace = false; $xml->load($xml_path); // Main program // creates another file to be filled by sub scripts if (!empty($xml)) { vwaconsole("Running main program"); // backup xml first $date = "_".date("Y M D h i"); $date = str_replace(' ', '_', $date); $xpath = new DOMXpath($xml); $items = $xpath->query("//aanbiedingen//item"); $loopcount = 0; $processedamount = 0; $islast = 0; vwaconsole('total items: '.$items->length); vwaconsole('chunk size: '.$chunk_size); echo'<br>'; /* chunks processing: */ $chunkxml = new DOMDocument(); $chunkxml->formatOutput = true; $chunkxml->preserveWhiteSpace = false; $counter = 0; $chunkroot = null; foreach($items as $item) { //vwaconsole('processing item'); if ($chunkroot === null) { $chunkroot = $chunkxml->createElement('root'); $chunkxml->appendChild($chunkroot); //vwaconsole('created root'); } if (($processedamount + $chunk_size) > $items->length) { //vwaconsole("last chunk in progress..."); $islast = 1; } $chunkitem = $chunkxml->createElement($item->nodeName); $chunkroot->appendChild($chunkitem); //vwaconsole('appended child item to root'); foreach($item->childNodes as $spec) { //vwaconsole('processing specs in item'); $chunkspec = $chunkxml->createElement($spec->nodeName); $chunkitem->appendChild($chunkspec); $chunkspectext = $chunkxml->createTextNode($spec->nodeValue); $chunkspec->appendChild($chunkspectext); } $counter++; $processedamount++; if ($counter >= $chunk_size) { $chunkxml->save("wp-content/uploads/wpallimport/files/chunks_bast/bast_chunk_".$loopcount.".xml"); vwaconsole("saved array chunk"); $output = `php export_filter_chunk_processor.php $loopcount $islast `; vwaconsole($output); vwaconsole("creating new array chunk"); $chunkxml = new DOMDocument(); $chunkxml->formatOutput = true; $chunkxml->preserveWhiteSpace = false; $loopcount++; $counter = 0; $chunkroot = null; } if ($items->length === $processedamount) { $chunkxml->save("wp-content/uploads/wpallimport/files/chunks_bast/bast_chunk_".$loopcount.".xml"); vwaconsole("finished saving last chunk"); } } // merge documents later.. /* $newxml = new DOMDocument("1.0", "utf-8"); $newxml->formatOutput = true; $newxml->preserveWhiteSpace = false; $itemContainer = $newxml->createElement('aanbiedingen'); $newxml->appendChild($itemContainer); //$newxml->save("wp-content/uploads/wpallimport/files/TEMP_Bastiaansen.xml"); */ vwaconsole("main ending"); exit(); } else { //vwaconsole("xml is empty ?! exiting"); exit(); } ?>
Export chunk processor: The xml was split by the previous script. This one takes one of the chunks and calls get_headers() , sending a link containing a query multiple of this script run at same time. The queries are then picked up by the last php file. <?php //ini_set('max_execution_time', 10); // console function vwaconsole($input) { $disabled = false; if ($disabled === false) { $a = print_r($input.'</br>'); $a = $input; echo "<script>console.log( '--log--: " . $a . "' );</script>"; } } //end console //echo'<br>'; print_r("called chunk processor > Chunk processor started. "); //echo'<br>'; $loopcount=$argv[1]; $islast=$argv[2]; if ($loopcount === null || $islast === null) { print_r("CHUNK PROCESSOR ERROR > loop count is empty"); exit(); } else { print_r("CHUNK PROCESSOR variables set. loop count: ".$loopcount." is last: ".$islast."<br>"); } if ( ! defined('BAST_ROOT_DIR') ) { define('BAST_ROOT_DIR', __DIR__); } $home = constant( 'BAST_ROOT_DIR' ); $xml_path = $home."/wp-content/uploads/wpallimport/files/chunks_bast/bast_chunk_".$loopcount.".xml"; if (fopen($xml_path,"r") != true) { print_r("chunk file was not found at path: ".$xml_path); exit(); } $xmlChunk = new DOMDocument(); //$xmlChunk = new DOMDocument(); $xmlChunk->formatOutput = true; $xmlChunk->preserveWhiteSpace = false; $xmlChunk->load($xml_path); if (empty($xmlChunk)) { print_r("chunk data is empty, exiting"); exit(); } else { print_r("got chunk data <br>"); } $xpath = new DOMXpath($xmlChunk); $item = $xpath->query("//root//item"); //$items = $xmlChunk->getElementsByTagName('//root//item'); foreach ($item as $node) { echo'new item: <br>'; foreach ($node->childNodes as $spec) { //vwaconsole("processing spec: ".$spec->nodeName); if (($spec->nodeName == 'itemlink')) { $memValue = $spec->nodeValue; //setting new url spec node $spec->nodeValue = processItemLink($memValue); // add new itemfoto nodes to xml } elseif(($spec->nodeName == 'itemfoto1')) { $memValue = $spec->nodeValue; $imgurls = array(); $first = true; for ($i = 1; $i < 50; $i++) { if ($first === false) { $memValue = str_replace('bast_get_itemfoto_id='.strval($i-1), 'bast_get_itemfoto_id='.strval($i), $memValue); } vwaconsole("trying to get a itemfoto with id: ".strval($i)." link: " .$memValue); $triedFotoUrl = processItemLink($memValue); vwaconsole("tried url: ".$triedFotoUrl); if($triedFotoUrl !== $memValue) { $imgurls[] = $triedFotoUrl; } else { vwaconsole("tried url and processed url are equal. end of loop. No new images left or error happened."); break; } $first = false; } //remove the old single itemfoto from xml $spec->parentNode->removeChild($spec); // add sorted nodes from image array if (!empty($imgurls)) { sort($imgurls, SORT_NATURAL); print_r('<br> after sort;'); print_r($imgurls); print_r('<br>'); $arlength = count($imgurls); for($x = 0; $x < $arlength; $x++) { $newItemFoto = $xml->createElement('itemfoto'.strval($x+1)); $newItemFotoText = $xml->createTextNode($imgurls[$x]); $newItemFoto->appendChild($newItemFotoText); $node->appendChild($newItemFoto); } unset($imgurls); } } } echo'<br>'; } //returns string url //follow the query url from xml, return a direct link or returns input on failure. query is processed in Bastiaansen.php. function processItemLink($url) { if (!empty($url)) { $headers = get_headers($url, 1); if(!empty($headers['Location'])) { vwaconsole('test returning header location: '.$headers['Location']); return $headers['Location']; } else { vwaconsole("header empty ?!?! can't convert query"); } } return $url; } $xmlChunk->save("wp-content/uploads/wpallimport/files/chunks_bast/bast_chunk_test_".$loopcount.".xml"); ?>
When the chunk processor calls a query link with get_headers(), the query will be noticed by the next script, the query converter: <?php if ( ! defined('ABSPATH') ) { require_once( dirname( __FILE__ ) . '/wp-load.php' ); } // ---- vars $machineID = $_GET['bast_get_machine_id']; $itemlink = $_GET['bast_get_itemlink']; $itemfoto_id = $_GET['bast_get_itemfoto_id']; if (!empty($itemlink)) { $request = 'bast_get_itemlink'; $value = $itemlink; } elseif (!empty($itemfoto_id)) { $request = 'bast_get_itemfoto_id'; $value = $itemfoto_id; } // ---- end vars if (empty($machineID)) { echo 'please enter query ?bast_get_machine_id=(number) first'; exit(); } if (empty($request) || empty($value)) { echo 'Valid query request would be: bast_get_itemlink <br>'; echo 'Valid query request would be: bast_get_itemfoto_id <br>'; exit(); } // register custom query options function sm_register_query_vars( $vars ) { // get the right custom field names $vars[] = $request; $vars[] = 'pa_'.$request; return $vars; } add_filter( 'query_vars', 'sm_register_query_vars' ); //returns null or string url function fetch($machineID,$request,$value) { $return = null; $args = array( 'orderby' => 'meta_value_num', 'meta_key' => 'bast_get_machine_id', 'meta_type' => 'NUMERIC', 'post_type' => 'product', 'posts_per_page' => -1, 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'bast_get_machine_id', 'type' => 'NUMERIC', 'value' => $machineID, 'compare' => 'EXISTS', ) ) ); $wp_query = new WP_Query($args); if ( $wp_query->have_posts() ) { while ( $wp_query->have_posts() ) { $wp_query->the_post(); apply_filters( 'the_content', 'filter_post_content' ); echo 'found product " '.get_the_title().' " on machine ID '.$machineID.'<br>'; echo 'requested: '.$request.'<br>'; if ($request === 'bast_get_itemlink') { // product url $return = get_permalink(get_the_ID()); break; } elseif ($request === 'bast_get_itemfoto_id') { // image attachment $attachments = get_posts(array( 'post_type' => 'attachment', //'post_mime_type' => 'image', 'posts_per_page' => -1, 'post_parent' => get_the_ID() //'exclude' => get_post_thumbnail_id() )); // as the requested value should be 1, but the array starts at 0.. remove 1 from value if (!empty($attachments) && ($attachments != false) && !empty($attachments[$value-1]) && ($attachments[$value-1] != false) ) { $return = wp_get_attachment_image_src( $attachments[$value-1]->ID, 'full')[0]; echo 'attachment found'; } else { echo 'attachment empty...'; } echo 'total amount of images found on this machine: '.count($attachments); break; } break; } /* Reset Post Data after loop */ wp_reset_postdata(); } else { echo 'query on machine ID '.$machineID.' found no product. Exit.'; } return $return; } function filter_post_content( $content ) { // Check if we're inside the main loop in a single post page. if ( is_single() && in_the_loop() && is_main_query() ) { return $content; } return $content; } $finaldestination = fetch($machineID,$request,$value); if (empty($finaldestination)) { exit(); } //echo 'destination set: '.$finaldestination.'<br>'; header("Location: ".$finaldestination, true, 302); ?>
I use jQuery when adding messages. However, the file can be called directly. For example: includes/add_comment.php?id=2 So, I can make a form and call this file directly to add a message. ID is user id and form can be submited with HTML form wherever are located. How to prevent direct access to the file when called through a Ajax? Need Suggestion for my codes, I want msg1.php to be open in the frame bottomframe. if($username=="" || $password=="") { echo "<form method=\"post\" action=\"msg1.php\" target=\"bottomframe\" >"; } Hello All, I am in desperate help here since my site was DDoS attacked by some one in turkey (Ips originate mostly from turkey, Germany, and some other Europe countries). I have installed the ddos deflation and most of the IPs are now blocked. I have a php file in my server that I use to input data into my database and my streaming servers. This file is called connect.php and the hacker is basically created an automated script that repeatedly call the connect.php file from a botnet resulting in both apache and mysql dead. I use connect.php in the following way http.open('get', "ajax/createchannel_1.php?channel=" + channelname + "&sitename=" + sitename + "&privateurl=" + privateurl + "&privateurlcheck=" + privateurlcheck); How can i change the connect.php so that it only accept execution from my server/ Please your help is greatly appreciated. Hi, I have a user/password protected page that displays a list of clients. When clicking on them you're redirected to the client record update page. This is how I am linking to taht page now: Code: [Select] <a href="DIST_clientes_update.php?id_cliente=<?php echo $row_clients_RS['id_cliente']; ?>The problem with this is that the client id is appended to the url and so if the user chnges it will be able to access records from a different user...and I dont want that. So I have created a session: Code: [Select] $_SESSION["idCliente"] = $row_clients_RS['id_cliente'];but how do I pass it to the update page without showing in the url? Thanks I'm building a login page that then redirects to a new page. But it seems the session isn't working. But I don't know much about sessions, so I'm not sure what I might be doing wrong. The login page sets the session with this code: Code: [Select] // Fetch the result - This will tell us whether this user exists $userExists = mysql_fetch_assoc($doQuery); // If user exists log them in if($userExists){ mysql_free_result($doQuery); mysql_close(); // Set the SESSION variables $_SESSION['first_name'] = $userExists['first_name']; $_SESSION['id'] = $userExists['id']; The page that it redirects to is this: Code: [Select] <?php session_start(); if(isset($_SESSION['id'])) { echo "<html><body><p> You are now logged in,{$_SESSION['ID']}.</p>"; } else { echo 'something went wrong'; exit(); } ob_end_flush(); ?> Having some problems with PHP session i currently use cookies to log users in, but i have decided to use php session instead but i can get it to work, it simply dose not pass the variables unless include session id in every single link on my website, can anyone tell me where i am going wrong these are the session setting from php.in session.use_cookies = 1 session.use_only_cookies = 0 session.name = usersesid session.auto_start = 1 session.cookie_lifetime = 0 session.referer_check = 1 session.cache_expire = 180 session.use_trans_sid = 1 I have my php pages set up like this: 1. log in with login.php 2. that sends you to main.php 3. in main.php, there are links to page-a.php, page-b.php, page-c.php, etc. when you type in a password at login.php, it passes your input to main.php. the correct password is hardcoded in main.php. if it matches, a session variable is set, which should be able to be used on page-a.php, page-b.php, page-c.php, etc. to verify that whoever accesses those pages has gone through the login process. if the session variable doesn't match (or null) the user is redirected to the login page. also the session variable is checked (recursively) when accessing main.php, just like the other pages. the problem is, it's as if each page starts over. the session variable does not make it beyond the page that sets it. it should be passed on to the next page but it's not. I used an echo statement in page-a.php to verify and rem'd out the rest of the code. no echo because session value is null, page goes on to load the html. without the code rem'd out it redirects the user to login.php. code: LOGIN.PHP <? session_start(); if(isset($_SESSION['aaa'])) unset($_SESSION['aaa']); ?> <html> <head> <title>title</title> </head> <body> <table width="400" align="center" border="0" bordercolor="#000099" bordercolordark="#000066" bordercolorlight="#6666FF"> <tr bgcolor="#B0C4DE"> <td> <form action="main.php" method="POST"> <p align="center"><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif" color="#FFFFFF"><br> Password</font></strong> <input name="pwfield" type="password" value size="20" maxlength=20> <input type="submit" value="Login"></p> </form> </td></tr></table> </body></html> MAIN.PHP <? if ($_SESSION['aaa']!="abcdef") { $password="twinkies"; if ($_POST["pwfield"]==$password) $_SESSION['aaa']="abcdef"; // successful login else {header("Location: login.php"); exit();} } ?> <html> <head> <title>title</title> </head> <body> <a href="page-a.php">Page A</a> <a href="page-b.php">Page B</a> <a href="page-c.php">Page C</a> </body></html> PAGE-A.PHP <? echo $_SESSION['aaa']; //if ($_SESSION['aaa']!="abcdef") //header("Location: login.php"); //exit(); ?> <html> <head> <title>title</title> </head> <body> ... Hello, we got a site running in to different servers, the other one is a sub domain that will be use as internal pages and the other one is external. As of that I need to pass session to see if a user details.
Is there a another secure way to pass session data to other server without storing on the database?
I have a script that was written and tested on another server, but now when I transferred it to the live server, session values are not being passed. I made a couple test pages to check and confirmed that the only issue is the session variables. Here is the test I performed. Please tell me what I'm missing: page1.php <? session_start(); $_SESSION['var1'] = 'testing'; print_r($_SESSION); ?> Returns: Array ( [var1] => testing ) page2.php <? session_start(); print_r($_SESSION); ?> Returns: Array () Alright, So i want to pass a session from www.mysite.com to mobile.mysite.com And i'm doing so by calling this on the top of every page on each site: <?php session_set_cookie_params(360000, "/",".mysite.com"); session_start(); print_r($_SESSION); ?> yet, the session data that is set on one subdomain is NOT printed on the other subdomain. I've even tried destroying the sessions several times to start over. But it won't work. What could be up? Thanks Hola, I'm trying to create a web form to insert info into my database using session variables. I'm at my wits end at this point. The reset button does its job but when you click submit it doesn't do anything. I'm using the template from the lynda.com essential php web form tutorials. Any help would be appreciated Here is the client-side header code I'm working with, <?php 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 session_start(); if (!isset($_SESSION['SESSION'])) require ( "include/session_init.php"); $arVal = array(); require_once("include/session_funcs1.php"); // make sure the seesion vars are initialized... reset ($arVal); while (list ($key, $val) = each ($arVal)) { if (!isset($_SESSION[$key])) $_SESSION[$key] = ""; } if ($_SESSION["eventgenre_sel"] == "") $_SESSION["eventgenre_sel"] = 0; // if the bFlg is true then some validation problems in the data. // namely a blank field or a submission without the feedback page. // just present a general error... $flg = ""; $error = ""; if (isset($HTTP_GET_VARS["flg"])) $flg = $HTTP_GET_VARS["flg"]; switch ($flg) { case "red": $error = "<br><font class=\"txt12_red\">Please fill out all the required fields.<br>Please Try Again.<BR></font>"; break; case "blue": $error = "<br><font class=\"txt12_red\">Your Session has Expired.<br>Please Try Again.</font><BR>"; break; case "pink": $error = "<br><font class=\"txt12_red\"><BR>The Special Code you entered is not valid.<br>Please Try Again or Leave that field blank.</font><BR>"; break; case "white": $error = "<br><font class=\"txt12_red\"><BR>The fields are too long for our Database.<br>Please correct your data via this form.</font><BR>"; break; default: $error = ""; } ?> <?php echo $_SERVER['SCRIPT_NAME']."<BR>"; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="detect800.css"/> <link rel="stylesheet" type="text/css" href="detect1024.css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="detect.js"></script> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/ui.all.css" rel="stylesheet" type="text/css" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js" type="text/javascript"></script> <script src="jquery.ui.datetimepicker.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { $('#eventdate').datetimepicker(); }); </script> <script src="imageflow.js" type="text/javascript"></script> <script src="highslide-full.js" type="text/javascript"></script> <script src="autosuggest.js" type="text/javascript"></script> <script type="text/javascript"> hs.graphicsDir = 'graphics/'; </script> <script language="javascript"> function SubmitForm() { var form = document.forms[0]; var bRequired = true; if((form.eventname.value.length < 1) || (form.eventvenue.value.length < 1) || (form.eventdate.value.length < 1) || (form.eventgenre.value.length < 1) || (form.eventprice.value.length < 1) || (form.eventpromoter.value.length < 1) || (form.eventflyer.value.length < 1)) { alert("Please fill out all the required fields."); bRequired = false; } if (!bRequired) return false; form.eventgenre_sel.value = form.state.selectedIndex; form.submit(); } function ResetForm() { var form = document.forms[0]; form.eventname.value = ""; form.eventvenue.value = ""; form.eventdate.value = ""; form.eventgenre.value = ""; form.eventprice.value = ""; form.eventpromoter.value = ""; form.eventflyer.value = ""; form.eventgenre_sel.value = ""; } </script> </head> This is the client side form code <form action="scripts/register.php" method="post" name="userevent" id="userevent"> <input name="eventgenre_sel" type="hidden" id="eventgenre_sel" value="<?php echo $_SESSION['eventgenre_sel'] ?>" /> <?php echo $error; ?> <fieldset> <label for="eventname" accesskey="n" ><span>Event Name</span> <input type="text" name="eventname" id="eventname" value="<?php echo $_SESSION['eventname_sel'] ?>" size="32" maxlength="30" /></label> <div id="autosuggest"><ul><li></li></ul></div> <label for="eventvenue" accesskey="v" ><span>Event Venue</span> <input type="text" name="eventvenue" id="eventvenue" size="32" value="<?php echo $_SESSION['eventvenue'] ?>" maxlength="30" /></label> <script type="text/javascript"> var venues = new Array("Republik", "HiFi Club", "Bamboo Tiki Room", "Tantra", "Jubilee Auditorium", "Ironwood Stage & Grill", "Broken City", "Soda", "Amsterdam Rhino", "Olympic Plaza", "Stampede Casino", "Habitat Living Sound", "Cantos Music Foundation", "Flames Central", "Prince's Island Park", "Beat Niq Jazz & Social Club", "Giuseppe's Italian Market", "BLVD", "Fourth on 4th", "Opus on 8th", "Local 510", "Local 522", "Raw Bar", "Jupiter Restaurant & Bar", "Vern's", "Lord Nelson's", "Kings Head Pub", "Blind Beggar Pub", "Viscous Circle", "Milk Tiger Lounge", "Pengrowth Saddledome", "Tubby Dog", "Marquee Room", "Distillery Public House", "Cafe Koi", "Mikey's Juke Joint & Eatery", "Palomino", "Atlantic Trap & Gill", "Drake Inn", "Radiopark Music Room", "Rusty Cage South", "Big Al's Good Times Bar", "Rose & Crown", "Tudor Rose Pub", "Elbow River Casino & Lounge", "Rusty Cage Central", "Rusty Cage South", "Rusty Cage North", "Olive Grove", "Shamrock Hotel", "Woody's Taphouse Southland", "Woody's Taphouse Country Hills", "Murrieta's West Coast Bar & Grill", "Stageline Saloon", "Pig & Pint", "Ranchman's", "Red Pepper Pub", "Stavro's Steak House & Lounge Ranchlands", "Stageline Saloon", "Whiskey"); new AutoSuggest(document.getElementById("eventvenue"),venues); </script> <label for="eventdate" accesskey="d" ><span>Event Date</span> <input type="text" name="eventdate" id="eventdate" value="<?php echo $_SESSION['eventdate'] ?>" size="32" maxlength="30" /></label> <label for="eventgenre" accesskey="g" ><span>Event Genre</span> <select name="eventgenre" id="eventgenre"> <option value="none">--select one--</option> <option value="HipHop">Hip-Hop</option> <option value="Funk">Funk</option> <option value="Soul">Soul</option> <option value="Metal">Metal</option> <option value="Punk">Punk</option> <option value="Blues">Blues</option> <option value="Jazz">Jazz</option> <option value="Trance">Trance</option> <option value="Breaks">Breaks</option> <option value="Electro">Electro</option> <option value="House">House</option> <option value="DNB">Drum'N'Bass</option> <option value="Dubstep">Dubstep</option> <option value="Lounge">Lounge</option> <option value="Top40">Top 40</option> </select> </label> <label for="eventprice" accesskey="p" ><span id="eventprice">Event Price</span> <input type="text" name="eventprice" id="eventprice" value="<?php echo $_SESSION['eventprice'] ?>" size="6" maxlength="4"/></label> <label for="eventpromoter" accesskey="c" ><span id="eventpromoter">Event Promoter</span> <input type="text" name="eventpromoter" id="eventpromoter" value="<?php echo $_SESSION['eventpromoter'] ?>" size="25" maxlength="23"/></label> <label for="eventflyer" accesskey="f" ><span id="eventflyer">Event Flyer (jpg or png MAX 300kb)</span> <input type="file" name="eventflyer" id="eventflyer" value="<?php echo $_SESSION['eventflyer'] ?>" size="25" maxlength="23"/></label> <input type="button" name="Reset" value="Reset" onclick="ResetForm();"> <input type="button" name="Submit" value="Submit" onsubmit="return validateForm(this);" onclick="SubmitForm(); return false; " > </fieldset> </form> <script language="javascript"> // set the selection box values... var form = document.forms[0]; form.eventgenre.selectedIndex = parseInt("<?php echo $_SESSION['eventgenre_sel'] ?>"); </script> And this is the server-side code. <?php $debug = FALSE; /************************************************************ 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"); } // make sure fields are within the proper range... if (strlen($_SESSION['eventname']) > 35 || strlen($_SESSION['eventvenue']) > 35 || strlen($_SESSION['eventdate']) > 35 || strlen($_SESSION['eventgenre']) > 35 || strlen($_SESSION['eventprice']) > 35 || strlen($_SESSION['eventpromoter']) > 35 || strlen($_SESSION['eventflyer']) > 35 ) { resendToForm("?flg=white"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $query = "INSERT INTO td_events (seventname, seventvenue, seventdate, seventgenre, seventprice, seventpromoter, seventflyer) " ."VALUES (".$arVals['eventname'].", ".$arVals['eventvenue'].", ".$arVals['eventdate'].", ".$arVals['eventgenre'] .", ".$arVals['eventprice'].", ".$arVals['eventpromoter'].", ".$arVals['eventflyer'].")"; //echo $query; $result = mysql_query($query) or die("Invalid query: " . mysql_error() . "<br><br>". $query); $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; } ?> <p>SUCCESS!<br> The event was entered in the database!<br> You probably want to redirect to a thank you page or send an email to the user for confirmation.<br> <br> <br> Here are the variables...<br> <?php reset ($arVals); while (list ($key, $val) = each ($arVals)) { echo $key . " : " . $arVals[$key] . "<br>"; } echo "<br><br>The SQL Statment was:<br>"; echo $query."<br><br><br><br>"; ?> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <?php /********************************************************************************************** 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.'">'; } ?> i want to pass the information getting from the form and after storing in to the variables to a new php file ..how to pass all the value getting from the form Right, so I've made a very simple web app that allows.... 1.) People to register (adding them to the MySQL database) 2.) Login (providing they're in the database) I've gotten it all working, but I'm stuck at the last hurdle. If someone logs in using the correct username and password, it takes them to login_success.php. Here I query the database and use "SELECT * FROM Users WHERE Username = '$name'" I would have thought, that it would have returned that user's entry in the database. But instead I just get a blank page. Am I right in thinking that's because the contents of the $name variable aren't passed from log.php to login_success.php If so, how do I fix it? ---------------------------------------------------------------------------------------------------- LOGIN.PHP Code: [Select] <?php include_once "Common/header.php"; session_name("MyLogin"); $page = (isset($_GET['login']) ? strtolower($_GET['login']) : NULL); if($page == "failed"){ print $_GET['cause']; } ?> <div id="main"> <br />   <br />  <br /> <h2>Sign In</h2>   <form name="form1" method="post" action="log.php?action=login"> <b>Username:</b>  <input type="text" name="uname"/><br />  <br /> <b>Password:</b>                 <input type="password" name="pword" /><br />  <br /> <input type="submit" value="submit" /> </form> <?php include_once "Common/footer.php"; ?> LOG.PHP Code: [Select] <?php session_name("MyLogin"); session_start(); if($_GET['action'] == "login") { $conn = mysql_connect("localhost", "root", ""); $db = mysql_select_db("test"); $name = ($_POST['uname']); $word = ($_POST['pword']); $sql = "SELECT * FROM Users WHERE Username='$name' and Password='$word'"; $q_user = mysql_query($sql) or die(mysql_error() . ' <br /> in ' . $sql); if(mysql_num_rows($q_user) == 1){ $_SESSION['uname'] = $_POST['uname']; header("Location: login_success.php"); exit; } else{ header("Location: login.php?login=failed&cause=".urlencode('Invalid Username or Password')); exit; } } else{ header("Location: login.php?login=failed&cause=".urlencode('Invalid User')); exit; } if(session_is_registered("name") == false) { header("Location: login.php"); } ?> LOGIN_SUCCESS.PHP Code: [Select] <?php include_once "Common/header.php"; $connect=mysql_connect("localhost", "root", "")or die ("Could not connect to database"); $data = mysql_query("SELECT * FROM Users WHERE Username ='$name'") or die(mysql_error()); Print "<table border cellpadding=3>"; while($info = mysql_fetch_array( $data )) { Print "<tr>"; Print "<th>First Name:</th> <td>".$info['First_Name'] . "</td> "; Print "<th>Last:</th> <td>".$info['Last_Name'] . " </td></tr>"; } Print "</table>"; ?> Login Successful <?php include_once "Common/footer.php"; ?> Here is my PHP, i want to share voice_id and voice_name to another php file using ajax,
<?php //fetch_data.php include('database_connection.php'); if(isset($_POST["action"])) { $query = " SELECT * FROM voice_bank_data WHERE voice_status = '1' "; // if(isset($_POST["minimum_price"], $_POST["maximum_price"]) && !empty($_POST["minimum_price"]) && !empty($_POST["maximum_price"])) // { // $query .= " // AND product_price BETWEEN '".$_POST["minimum_price"]."' AND '".$_POST["maximum_price"]."' // "; // } // Gender if(isset($_POST["gender"])) { $gender_filter = implode("','", $_POST["gender"]); $query .= " AND voice_gender IN('".$gender_filter."') "; } // Genres if(isset($_POST["genres"])) { $genres_filter = implode("','", $_POST["genres"]); $query .= " AND voice_genres IN('".$genres_filter."') "; } // Voice Modulation if(isset($_POST["voice_modulation"])) { $voice_modulation_filter = implode("','", $_POST["voice_modulation"]); $query .= " AND voice_voice_modulation IN('".$voice_modulation_filter."') "; } // Languages if(isset($_POST["languages"])) { $languages_filter = implode("','", $_POST["languages"]); $query .= " AND voice_languages IN('".$languages_filter."') "; } // Jingle Moods if(isset($_POST["jingle_moods"])) { $jingle_moods_filter = implode("','", $_POST["jingle_moods"]); $query .= " AND voice_jingle_moods IN('".$jingle_moods_filter."') "; } // IVR if(isset($_POST["ivr"])) { $ivr_filter = implode("','", $_POST["ivr"]); $query .= " AND voice_ivr IN('".$ivr_filter."') "; } $statement = $connect->prepare($query); $statement->execute(); $result = $statement->fetchAll(); $total_row = $statement->rowCount(); $output = ''; if($total_row > 0) { foreach($result as $row) { $output .= ' <div class="col-sm-3 col-lg-4 col-md-3"> <div style="border:1px solid #ccc; border-radius:5px; padding:10px; margin-bottom:16px; height:300px;"> <audio controls controlsList="nodownload" style="padding: 10px 10px 10px 10px;margin-left: -21px;"> <source src="audio_sample/'. $row['voice_audio_file'] .'" alt="" class="img-responsive"> </audio> <p align="center"><strong> '. $row['voice_name'] .'</strong></p> <p style="font-size: 12px;"> Id : '. $row['voice_id'].' <br /> Name : '. $row['voice_name'].' <br /> Gender : '. $row['voice_gender'].' <br /> Genres : '. $row['voice_genres'].' <br /> Voice Modulation : '. $row['voice_voice_modulation'].' <br /> Languages : '. $row['voice_languages'].' <br /> Jingle Moods : '. $row['voice_jingle_moods'].' <br /> Ivr : '. $row['voice_ivr'].' <br /> </p> <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;">Add to PlayList </button> </div> </div> '; } } else { $output = '<h3>No Data Found</h3>'; } echo $output; } ?> <script> $('.button').on('click',function() { var voice_id = $("#voice_id").val(); var voice_name = $("#voice_name").val(); $.ajax({ type : "POST", url : "my_cart.php", datatype : "text", data : {voice_id: voice_id, voice_name: voice_name }, success: function(data) { console.log(data); // console.log('success',data); } }); }); </script> Not shared the details, Edited July 2, 2019 by aveevaHi Guys, I'm working on an image resizer, to create thumbnails for my page. The resizer works on principle of include a DIRECT link to the image. But what I want to do is put in the PHP Variable in the URL string, so that it points to that file and resizes it accordingly. My code is as follows : Code: [Select] <img src="thumbnail.php?image=<?php echo $row_select_property['image_url']; ?> Image Resize : Code: [Select] <?php // Resize Image To A Thumbnail // The file you are resizing $image = '$_GET[image_url]'; //This will set our output to 45% of the original size $size = 0.45; // This sets it to a .jpg, but you can change this to png or gif header('Content-type: image/jpeg'); // Setting the resize parameters list($width, $height) = getimagesize($image); $modwidth = $width * $size; $modheight = $height * $size; // Creating the Canvas $tn= imagecreatetruecolor($modwidth, $modheight); $source = imagecreatefromjpeg($image); // Resizing our image to fit the canvas imagecopyresized($tn, $source, 0, 0, 0, 0, $modwidth, $modheight, $width, $height); // Outputs a jpg image, you could change this to gif or png if needed imagejpeg($tn); ?> What I am trying to do is pass on the variable "image=<?php echo $row_select_property['image_url']; ?>" to the Thumbnail script. At the moment I am passing it through the URL string, but it doesnt seem to load the graphic. I'll try expand on this more, should you have questions as I am finding it a little difficult to explain. Thanks in advance. Hi, I need to pass value of variable to another php file. I thought it is possible to do it as following: <form action="products.php"> <INPUT TYPE=hidden NAME='id' . VALUE='$id'> </form> But the problem is like that. The php file inside which I want to write above html code has not using <form> tag and it has no buttons. So how to initiate the transfer of variable into another php file? Is the above idea is not the good idea? Are there any another ways? hi friends!! in php > 5 i use "session_regenerate_id(TRUE)" in order to generate a new session file and delete old one. In php 4.x the TRUE parameter doesn't exist: old files will be accumulated until the garbage collector will cleans all. How can I delete old session file in php 4.x having regenerated the new one? I am trying to pass a variable from inside of a function in a file that is included eg include.php Code: [Select] <? function noms(){ $foobar = "apples"; } ?> main.php Code: [Select] <? include("include.php"); noms(); echo "these ". $foobar. " are most delicious... OM NOM NOM"; ?> I am essentially using a include file for a mysql connection and based on the connection outcome i am either setting a value to true or false. It prints "Connected succesfully" and what not just fine, but, after that it wont pass on the variables data. I know its the function because, it passes the data if i put the variable before the function... i just dont get it.. any help would be great. Thanks. Ansel |