Quantcast
Channel: PHP Freaks: PHP Help
Viewing all 13200 articles
Browse latest View live

Keeping randomly generated numbers and checking the sum

$
0
0

Hey,

This is my first day with PHP and I'm given an assignment by my professor. Assignment is a very basic game, all i have to do is give 2 random numbers, and add them, and check if the user has submitted the correct answer. 

 

So i thought like this;

 

1-    first php file generates two random numbers

1.1- user submits the sum of those numbers

 

2-    second php file, gets the sum of the random generated numbers and checks if the submitted value is right.

 

I've come up this far;

 

<?php
echo "<html><head><title>calculation game!</title></head><body>";
echo "<h1>first number is</h1>";
echo (rand(100, 450));
echo "<h1>and the next number is</h1>";
echo (rand(100, 5000));
echo "<h1>now add the numbers and submit your output here!</h1>";
echo "<form name = \"myfirstform\" action  = \"formprocess.php\" method = \"PO$
echo "Enter data<br>";
echo "<input type = \"text\" name = \"firstdata\">";
echo "<br> <input type= \"submit\" value = \"Let's check!\">";
echo "</form>";

?>   

 

Now my problem is about; how can I keep those generated numbers and add them up. I've been digging all through the internet for syntax and php scripts, but I couldn't find an answer that helps me. 

 

Thanks in advance.


Striping text between certain characters

$
0
0

This is an easy question for those fluid in PHP and one area I struggle in. 

 

I have this variable. 

$downloadedmetar1wind

That outputs this.... S (180 degrees) at 26 MPH (23 KT) 

 

I am trying to strip away the (180 degrees) and the (23 KT) so it just reads S at 26 MPH

 

This is what I have done but it isn't removing the brackets and the contents between it.

$wind = preg_replace('/([\s.]\([0-9-]+\))/', '', $downloadedmetar1wind);

-Thanks

Prepared Delete Statement with Subquery in mysql table

$
0
0

i have a table of say 100 entries.  i want to delete all but the 10 newest of those rows with a prepared statement.  im fairly new with prepared statements so the syntax with a subquery is throwing me a bit.

$stmt = $db_connect->prepare('DELETE FROM table WHERE owner=? AND owner NOT IN (SELECT owner FROM table ORDER BY dob DESC LIMIT 10)');
$stmt->bind_param('i', 0);
$stmt->execute();
$stmt->close();

Display SQL data by clicking list

$
0
0

I am brand new to PHP but, after using W3 Schools,  can retrieve a record from a MySQL database using php & SQLi. 

 

I have a page with a list of between 20 and 30 items down one side and a panel on the other. When a user clicks a list item I want to display the details of the clicked item in the panel. The details are: Program (text), Convenor (text), Dates (text), Times (Text), Location (text), Notes (Text large). 

 

The details are stored in a MySQL Database 'Documents', in a table 'Programs' and I would like to put the details into text boxes in the panel.

 

Could you point me to some info on doing this please?

Thanks

 

Help connecting to Database

$
0
0

Can someone tell me why in the following code, in the 'try' section, this code works: (first line after 'try')

 

 $conn = new PDO("mysql:host=$servername;dbname=$dbasename", $username, $password); even though I have not declared a variable named $dbname,

but if I change it to "$databasename", which I have declared, it doesn't work. I don't understand that.

 

<code>

<?php
$databasename = "removed";
$servername = "removed";
$username = "removed";
$password = "removed";
$id=$_POST[id];
$courseID=$_POST[courseID];
$coursename=$_POST[coursename];
$firstname=$_POST[firstname];
$lastname=$_POST[lastname];
$middlename=$_POST[middlename];
$grade=$_POST[grade];
$year=$_POST[year];
$sex=$_POST[sex];
 
echo "<br/>Connecting to Database.....<br/>";
 
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbasename", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO $databasename (studentID, lastName, firstName, middleName, courseName, courseNumber, year, grade, gender) 
VALUES ('$id','$lastname','$firstname','$middlename','$coursename','$courseID','$year','$grade', '$sex')";
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }
$conn = null;
?>

</code>

How to return an array of emails.....

$
0
0

I am trying to write a program that sends out a newsletter but I am lost at returning an array of emails. This is what I have

<?php
require("../PHPMailer/class.phpmailer.php");
include 'includes.php';
        $mail = new PHPMailer;
        $subject = $_POST['subject'];
        $text = $_POST['newsletterBody'];
        $unsubscribe = "<br /><br /><br /><br />If you would no longer like to receive these emails, please <a href='removeemail.php'>Click Here</a> to unsubscribe.";
        $mail->IsSMTP();                                      // Set mailer to use SMTP
        $mail->Host = 'localhost';  // Specify main and backup server
        $mail->Port = '465';
        $mail->SMTPAuth = true;                               // Enable SMTP authentication
        $mail->Username = '****EMAIL ADDRESS****';                            // SMTP username
        $mail->Password = '****EMAIL PASSWORD*****';
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = 'ssl';                            // Enable encryption, 'ssl' also accepted

        $mail->From = '****EMAIL ADDRESS****';
        $mail->FromName = '****NAME****';
        
        $mail->AddAddress('****EMAIL ADDRESS****', '****NAME****');
        
        $email = getEmail("", $DBH);
        
        
        foreach ($email as $newEmail)
                {
                    $addEmail = $newEmail['email_addr'];
                    $mail->AddAddress($addEmail);
                    $DBH = null;
                }
        

        $mail->AddReplyTo('****EMAIL ADDRESS****', '****NAME****');
    
        $mail->WordWrap = 50;                                 // Set word wrap to 50 characters
        $mail->IsHTML(true);                                  // Set email format to HTML

        $mail->Subject = $subject;
        $mail->Body    = $text . "<br /><br /><br /> To unsubscribe to this email please  <a href='www.raven-consult.com/newsletter_remove.php'>Click Here</a>";
        $mail->AltBody = $text;

        if(!$mail->Send()) {
           echo 'Message could not be sent.';
           echo 'Mailer Error: ' . $mail->ErrorInfo;
           exit;
        }
        
        
        echo "Message has been sent <a href='newsletter.php'>Return back</a>";

?>

This is the portion of the includes file that you need to know. 

function getEmail($inId, $DBH)
    {
        if (!empty($inId))
        {
            $blogstmt = $DBH->prepare("SELECT email_addr FROM newsletter_emails WHERE id = :userId");
            $blogstmt->bindParam(":userId", $inId);
            $blogstmt->execute();
            $postArray = $blogstmt->fetchAll(PDO::FETCH_ASSOC);
        }
        else
        {
            $blogstmt = $DBH->prepare("SELECT * FROM newsletter_emails");
            $blogstmt->execute();
            $postArray = array();
        
        $results = $blogstmt->fetchAll(PDO::FETCH_ASSOC);
        foreach($results as $row){
            $myPost = new nlEmails($row['id'], $row['email_addr'], $DBH);
            array_push($postArray, $myPost);
        }
        }
    
        
        
        return $postArray;
        $DBH = null;
    }
 
class nlEmails {
    public $id;
    public $email;
    
    function __construct($inId=null, $inEmail=null, $DBH)
    {
        if(!empty($inId))
        {
            $this->id = $inId;
        }
        if(!empty($inEmail))
        {
        $this->email = $inEmail;
        }
    }
}

When I try and submit the newsletter to be sent out all I get back is this error. 

 

"Cannot use object of type nlEmails as array ......"

 

 

how to post this array post data in curl using php .

$
0
0
$post='{"cart_items":[{"configuration":{"price":100,"recharge_number":"9999999999"},"product_id":"999","qty":1}]}';

i try this n reslut was :There are no valid items in cart:   help me plz

Email with attachement

$
0
0

Hi Friends ,

 

I'm new to this forum and to the PHP world , please help me with the folowing code as it drives me creazy . I'm making a project for my studies a webpage to send email with attachement , 

if I send it without attachement , the mail goes through . if I attach any attachement it wont send the mail this is the code , please help : 

 

<?php
 
$to = $_POST['toemail'];
$subject = $_POST['subject'];
$message = $_POST['fieldDescription'];
$fromemail = $_POST['fromemail'];
$fromname = $_POST['fromname'];
$lt= '<';
$gt= '>';
$sp= ' ';
$from= 'From:';
$headers = $from.$fromname.$sp.$lt.$fromemail.$gt.$data;
 
 
 
/* GET File Variables */ 
$tmpName = $_FILES['attachment']['tmp_name']; 
$fileType = $_FILES['attachment']['type']; 
$fileName = $_FILES['attachment']['name']; 
 
/* Start of headers */ 
/* $headers = "From: $fromname"; */ 
 
if (file($tmpName)) { 
  /* Reading file ('rb' = read binary)  */
  $file = fopen($tmpName,'rb'); 
  $data = fread($file,filesize($tmpName)); 
  fclose($file); 
 
  /* a boundary string */
  $randomVal = md5(time()); 
  $mimeBoundary = "==Multipart_Boundary_x{$randomVal}x"; 
 
  /* Header for File Attachment */
  $headers .= "\nMIME-Version: 1.0\n"; 
  $headers .= "Content-Type: multipart/mixed;\n" ;
  $headers .= " boundary=\"{$mimeBoundary}\""; 
 
  /* Multipart Boundary above message */
  $message = "This is a multi-part message in MIME format.\n\n" . 
  "--{$mimeBoundary}\n" . 
  "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . 
  "Content-Transfer-Encoding: 7bit\n\n" . 
  $message . "\n\n"; 
 
  /* Encoding file data */
  $data = chunk_split(base64_encode($data)); 
 
  /* Adding attchment-file to message*/
  $message .= "--{$mimeBoundary}\n" . 
  "Content-Type: {$fileType};\n" . 
  " name=\"{$fileName}\"\n" . 
  "Content-Transfer-Encoding: base64\n\n" . 
  $data . "\n\n" . 
  "--{$mimeBoundary}--\n"; 
mail($to,$subject,$message,$headers,$data); 
 
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Email Attachment Without Upload - Excellent Web World</title>
<style>
body{ font-family:Arial, Helvetica, sans-serif; font-size:13px;}
th{ background:#999999; text-align:right; vertical-align:top;}
input{ width:181px;}
</style>
</head>
<body>
    
<form action="sendmail.php" method="post" name="mainform" enctype="multipart/form-data">
    </h3><br>
<p style="margin-left:15px">
<form action="sendmail.php" method="POST" name="mainform" enctype="multipart/form-data">
<b>From Name:</b><br>
<input type="text" name="fromname" size="50"><br>
<br><b>From Email:</b><br>
<input type="text" name="fromemail" size="50"><br>
<br><b>To Email:</b><br>
<input type="text" name="toemail" size="50"><br>
<br><b>Subject:</b><br>
<input type="text" name="subject" size="74"><br>
<tr>
        <th>Comments</th>
        <td><textarea name="fieldDescription" cols="20" rows="4" id="fieldDescription"></textarea></td>
    </tr>
</textarea><br>
   <br><b>Attach Your File</b><br>
    <input name="attachment" type="file">
 
    <tr>
        <td colspan="2" style="text-align:center;"><input type="submit" name="Submit" value="Send"><input type="reset" name="Reset" value="Reset"></td>
    </tr>
    </table>
    </form>
</body>
</html>
 

Attached Files


Error with login...Notice: Undefined index: salt

$
0
0

Hi

 

I'm having a strange error with this code and i get it working properly

 function CheckLoginInDB($username,$password)
    {
        if(!$this->DBLogin())
        {
            $this->HandleError("Erro na ligação à Base de Dados!");
            return false;
        }
		
        $username = $this->SanitizeForSQL($username);
		$nresult = mysql_query("SELECT * FROM utilizador WHERE utilizador = '$username'", $this->connection) or die(mysql_error());
        // check for result 
        $no_of_rows = mysql_num_rows($nresult);
        if ($no_of_rows > 0) {
            $nresult = mysql_fetch_array($nresult);
            $salt = $nresult['salt'];
			echo $salt;
            $encrypted_password = $nresult['password'];
			$hash = $this->checkhashSSHA($salt, $password);
			echo $hash;
        }
        $qry = "Select idutilizador, nome, email from utilizador where utilizador='$username' and password='$hash'";
        $result = mysql_query($qry,$this->connection);
        if(!$result || mysql_num_rows($result) <= 0)
        {
            $this->HandleError("Erro: Utilizador ou password errados");
            return false;
        }    
        $row = mysql_fetch_assoc($result);
		$_SESSION['idutilizador']  = $row['idutilizador'];
        $_SESSION['name_of_user']  = $row['nome'];
        $_SESSION['email_of_user'] = $row['email'];
		
        return true;
    }

This is my table

 

Field                                          Type         Collation          Null    Key     Default  Extra           Privileges                       Comment  
---------------------------------------------  -----------  -----------------  ------  ------  -------  --------------  -------------------------------  ---------
idutilizador                                   int(11)      (NULL)             NO      PRI     (NULL)   auto_increment  select,insert,update,references           
nome                                           varchar(45)  latin1_general_ci  NO              (NULL)                   select,insert,update,references           
utilizador                                     varchar(45)  latin1_general_ci  NO              (NULL)                   select,insert,update,references           
telefone                                       int(11)      (NULL)             YES             (NULL)                   select,insert,update,references           
email                                          varchar(45)  latin1_general_ci  NO              (NULL)                   select,insert,update,references           
password                                       varchar(45)  latin1_general_ci  NO              (NULL)                   select,insert,update,references           
sexo                                           int(11)      (NULL)             NO              (NULL)                   select,insert,update,references           
opcao                                          binary(10)   (NULL)             NO              (NULL)                   select,insert,update,references           
grupodisciplinar_idgrupodisciplinar            int(11)      (NULL)             YES     MUL     (NULL)                   select,insert,update,references           
escola_idescola                                int(11)      (NULL)             YES     MUL     (NULL)                   select,insert,update,references           
tipoutilizador_idtipoutilizador                int(11)      (NULL)             YES     MUL     (NULL)                   select,insert,update,references           
departamento_iddepartamento                    int(11)      (NULL)             YES     MUL     (NULL)                   select,insert,update,references           
categoriaprofissional_idcategoriaprofissional  int(11)      (NULL)             YES     MUL     (NULL)                   select,insert,update,references           
nivelensino_idnivelensino                      int(11)      (NULL)             YES     MUL     (NULL)                   select,insert,update,references           
privilegio_idprivilegio                        int(11)      (NULL)             YES     MUL     (NULL)                   select,insert,update,references           
 
 
Any help please?
 
Thanks

 

php Array groups - headers and footers

$
0
0

Hi

 

I have a two dimensional array and would like to output the results in groups depending upon one of the fields in the array. While i have managed this and have figured out how to create a header for each group, i would now like to create a footer (end of group) line where i could create a subtotal or similar.

 

my working code with the header is below but how do i add the footer?

$group = null;
for($i=0;$i<count($rowKitCharges);$i++){

		if($rowKitCharges[$i]['SubCategory'] != $group)
    {
         //echo the group header
         echo "<br><b>" . $rowKitCharges[$i]['SubCategory'] . "</b><br>";
				
				$group = $rowKitCharges[$i]['SubCategory'];
      }
    
		
		echo $rowKitCharges[$i]['HireID'] . " " . $rowKitCharges[$i]['SubCategory'];
                echo "<br>";
	
}

Thanks

Jon

Not a coder needs help with formatting to send email message

$
0
0

I have a bit of php code to send me an email when someone logs in to my site. I want to include the person's name and two other bits from my database, but I can't get the formatting correct. I keep getting errors when I try to load the page. Here's the code which obviously has mistakes. The first code works, it's the second one that does not work for the $message line .

if (mysql_num_rows($exe) == 1) {
		  	$message_m = "Someone with RefCode ".$RefC." has viewed the homepage for the first time.";
			mail("ray.fellers@gmail.com", "Good News! Someone just logged in to view the home page", $message_m);
		  	setcookie("has_entered_correct_refcode", "true", time()+27000000, "/");
		  	setcookie("has_entered_correct_refcode_value", $_POST["refcode"], time()+27000000, "/");
		  	header("Location: /index.php");
		  	die();
if (mysql_num_rows($exe) == 1) {
		  	$message_m =" "'.$_POST['fname'].'," with RefCode "'.$RefC.'," and refund amount of "'.$_POST['refvalact'].'," has viewed the homepage.";
			mail("ray.fellers@gmail.com", "Good News! Someone just logged in to view the home page", $message_m);

		  	setcookie("has_entered_correct_refcode", "true", time()+27000000, "/");
		  	setcookie("has_entered_correct_refcode_value", $_POST["refcode"], time()+27000000, "/");
		  	header("Location: /index.php");
		  	die();
		  }

Thanks for any help to resolve this.

notice:undefined index id

$
0
0

hi, can anyone tell me anything wrong with my  coding as it keeps mentioned undefined index,id

Attached Files

php websocket - How i can create chat room(s) and subscribe user to specific chat room?

$
0
0

i am new with web socket

and in same time

I try to make server and client communication for soccer manager application, and for this purpose, i need to create closed "chat rooms" or "games" where two users can watch (read game event) and menage (create) game event (make substitution, formation ... or if you want, to send message to server, that they make changes in formation)

this game (room) mast bi secret, and only this two player can use this game for "read" and "write" events in game

for example: Game no: 200001 between user A and user B in 14.05.

when User A, and User B click on game no. 200001 they can read and write game event.

PS: for now, i create basic chat aplication with PHP, jQuery and webSocket and in this app, all user see wath all other user do (public chat) and i want to make secret chat for specific user (already automate subscribed from server) All work with no problem (i work on this example http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket)

How i can create chat room(s) and subscribe user to specific chat room?

Thanks

try to get website speed, but i can read only ''domain.com'' i can't read files like css , js why?

$
0
0

Hello,

I try to get website speed of some website, but i can read only ''domain.com'' i can't read website files like css , js ... why ? i use proxies for this job.

here is the php code:

$options = array(
'useragent' => "Firefox (+http://www.firefox.org)", // who am i
'connecttimeout' => 120, // timeout on connect
'timeout' => 120, // timeout on response
'redirect' => 10, // stop after 10 redirects
'referer' => "http://www.google.com",
'proxyhost' =>'85.25.8.14:80'
);
$response = http_get("http://solve-ict.com/wp-content/themes/ict%20theme/js/jquery-1.7.1.min.js", $options , $info);

but it works fine with http://domain.com/ , but with files css or js it gives 404, using some free proxy servers available

?

Thanks.

Prevent named sessions form overwriting each other

$
0
0

I have two scripts: script1.php and script2.php.

 

Script1 creates if it doesn't already exist and adds to a session named "SESSION1" and displays it:

 

Script2 similarly adds to a session named "SESSION2", but then needs to display the session used by the first script (i.e. SESSION1), and then goes back to its original session (SESSION2).

 

Script1 works perfect.  But when Script2 is executed, it changes the session ID in the SESSION1 cookie to the same value as used in its SESSION2 cookie.  If Script1 is later executed, it obviously lost its previous session values as it is now using a new session ID.

 

If I comment out the two session_name() lines, it will not overwrite the other session, however, this doesn't provide the functionality I need.

 

What is causing this and how do I prevent it????

 

script1.php

<?php
// script 1.  Will be accessed as http://one.example.com

$t=time();

//Access the primary session for script 1
session_name('SESSION1');
session_start();
$_SESSION['s1_'.$t]=$t;
echo("SESSION1<pre>".print_r($_SESSION,1)."</pre>");
?>

script2.php

<?php
// script 2.  Will be accessed as http://two.one.example.com

$t=time();

//Access the primary session for script 2
$default_name=session_name('SESSION2');
session_start();
$_SESSION['s2_'.(2*$t)]=2*$t;
echo("SESSION2<pre>".print_r($_SESSION,1)."</pre>");

//Use session created by script 1
$old_id_script2 = session_id();
session_write_close();
$old_name_script2 = session_name('SESSION1');
session_start();
echo("SESSION1<pre>".print_r($_SESSION,1)."</pre>");

//Go back to primary session
session_write_close();
$old_id_script1 = session_id($old_id_script2);
$old_name_script1 = session_name($old_name_script2);
session_start();
echo("SESSION2<pre>".print_r($_SESSION,1)."</pre>");

echo("default_name: $default_name<br>");
echo("old_id_script2: $old_id_script2<br>");
echo("old_name_script2: $old_name_script2<br>");
echo("old_id_script1: $old_id_script1<br>");
echo("old_name_script1: $old_name_script1<br>");
?>

MySQLi Errors

$
0
0

I have just started using MySQLi and am clueless it is giving me the follow errors in which i do not understand

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\Login\connect.php on line 23

Notice: Trying to get property of non-object in C:\xampp\htdocs\Login\connect.php on line 25

Notice: Use of undefined constant mysqli - assumed 'mysqli' in C:\xampp\htdocs\Login\connect.php on line 32

Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\Login\connect.php on line 32

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in C:\xampp\htdocs\Login\connect.php on line 33
 

 

can someone please explain to me why i am getting these?

 

and my code is

$mysqli_db = mysqli_select_db("$db_name");

if($mysqli_db->connect_errno) {

	printf("Database not found: %s\n", $mysql->connect_error);
	exit();
}

$sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'";
$result = mysqli_query($sql);
$row = mysqli_fetch_assoc($result);

I just got rid off most the errors the only ones left are 

Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\Login\connect.php on line 32

Fatal error: Call to undefined function mysqli_result() in C:\xampp\htdocs\Login\connect.php on line 33

 

Code Updated: 

$mysqli_db = mysqli_select_db($mysqli_connect, $db_name);

if(!$mysqli_db) {

	printf("Database not found: %s\n", $mysqli->connect_error);
	exit();
}

$sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'";
$query = mysqli_query($sql);
$result = mysqli_result($query);
$row = mysqli_fetch_assoc($result);

Differentiate between products for E-commerce site from database

$
0
0

I am building an e-commerce site and I am aiming to create a front end displaying my products with an option for customers to buy them, and have a content management system as a back end for an admin to edit product information. 

 

Currently I am storing information about my products on a mysql database. I access and display the product info using a while loop. Below is a simplified version of what I am doing without any html to style it. This code will go through the database and each iteration will go the to the next row and display the info about the next product.

$query = mysql_query("SELECT * FROM truffleProducts");

while ($row = mysql_fetch_array($query)) {
	$id = $row['id'];
	$name = $row{'Name'};
	$price = $row{'Price'};
	$desc = $row{'Description'};
			
	echo $id;
	echo $name;
	echo $price;
        echo $desc;		
}

I have began to implement a 'buy' button so that customers are able to click on a button next to the product info and purchase it. However I have come across a problem which is where my program won't be able to tell which product you have selected as the number stored in the $id variable will  just be the last product it has fetched from the database. I can't differentiate between all the product's buy buttons, so it will impossible to place an order for a customer with the current system I have.

 

Can any one tell me how to get the id number of the specific product that a user has selected?

 

I only started learning PHP a month or two ago so assume I know nothing :)

Table Columns and Counting

$
0
0

Hi,

 

I am trying to make a list of all countries listed in a database and the number of times they appear. But I am clearly doing something wrong as I am not able to list out the number of times that they appear.

 

This is what I have got so far:

<h4>Countries</h4>
<table><col width='150px'><col width='150px'>
<tr>
	<th>
		Country
	</th>
	<th>
		Number of Occurences
	</th>
</tr>
<?php
$location = DB::getInstance()->query("SELECT country, COUNT(country) as countCountry FROM users GROUP BY country ORDER BY count DESC");
foreach ($location->results() as $locations)
{
	echo "<tr><td>";
	echo $locations->country;
	echo "</td><td>";
	echo $locations->countCountry;
	echo "</td></tr>";
}
?>
</table>

Can anyone point me in the right direction?

Access cookie of parent domain

$
0
0

I expected the following script to display a single cookie on the main page (cookie_2, and both the main page cookie and the subdomain cookie (cookie_3) within the iframe.

 

In actuality, the main page was as expected, but the iframe only displays cookie_3.

 

Can anyone explain what I am witnessing, and why the subdomain wouldn't be able to access the cookie set in the parent?

<?php
setcookie("cookie_".count(explode('.', $_SERVER['HTTP_HOST'])), 'Hello from '.$_SERVER['HTTP_HOST']);
echo('<pre>'.print_r($_COOKIE,1).'</pre>');
?>

<iframe src="http://test.mysite.com/testing/cookietest.php"></iframe>

help with form(submit) [CodeIgniter]

$
0
0

I'm a bit new to PHP and I'm getting my feet wet with mvc with code igniter. I'm having a bit of trouble with my view accessing a function from my controller. If anyone has seen CodeIgniter from Scratch Day 4, it's that tutorial - i've created an email newsletter signup.

 

In my my view (newsletter.php), my submit button is not working and isn't able to access a function from my controller (email.php). The inaccessible function is called function send(). Instead, I get a 404 error. I'll post the code from both the view and controller, but I highly suspect the error is contained within the view because my controller loads the view, but my view can't call a function from the controller. Any help you can provide would be greatly appreciated. Thanks.

 

Here's the code from my view (newsletter.php):

 

<html lang='en'>
<head>
<title>untitled</title>
<link rel ='stylesheet' href='<?php echo base_url(); ?>css/style.css' type='text/css' media='screen' />
</head>
 
<body>
 
<div id="newsletter_form">
<?php 
echo form_open('email/send'); 
?>
 
<?php 
 
 
$name_data = array(
'name' => 'name',
'id' => 'name',
'value' => set_value('name')
);
 
?>
 
<p><label for="name">Name: </label><?php echo form_input($name_data); ?></p>
 
<p>
<label for="name">Email Address: </label>
<input type = 'text' name = 'email' id = 'email' value = '<?php echo set_value('email'); ?>'>
</p>
 
<p>
<?php 
echo form_submit('submit', 'Submit'); 
?> 
</p>
 
 
 
<?php 
echo form_close(); 
?>
 
<?php 
echo validation_errors('<p class = "error">'); 
?>
</div><!--end newsletter-form-->
</body>
</html>
 
Here's the code from my controller (email.php):
 
?php
 
/* SENDS EMAIL WITH GMAIL */
 
class Email extends CI_Controller 
{
 
 
function index()
{
$this->load->view('newsletter');
}
 
function send()
{
$this->load->library('form_validation');
 
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email Address', 'trim|required|valid_email');
if($this->form_validation->run() == FALSE)
{
$this->load->view('newsletter');
}
else
{
$name = $this->input->post('name');
$email = $this->input->post('email');
 
$this->load->library('email');
$this->email->set_newline("\r\n");
 
$this->email->from('myemail@gmail.com', 'My Email Name');
$this->email->to($email);
$this->email->subject('Hey, from Codeigniter');
$this->email->message('It is working');
 
/*attachments */
 
$path = $this->config->item('server_root');
echo $path;
$file = $path . '/ci/attachments/yourinfo.txt';
 
$this->email->attach($file);
 
if($this->email->send()) 
{
echo 'Your email was sent';
}
else
{
show_error($this->email->print_debugger()); 
}
}
 
 
}
}

 

Viewing all 13200 articles
Browse latest View live